repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
ryokbys/nap | [
"ddd0b5a5a956f7c335a22adb4f8e00f1d38a7804"
]
| [
"nappy/vasp/make_random_deform_POSCARs.py"
]
| [
"#!/usr/bin/env python\n\"\"\"\nMake randomly deformed POSCAR files from the non-deformed POSCAR file.\n\nUsage:\n make_random_deform_POSCARs.py [options] POSCAR\n\nOptions:\n -h, --help Show this help message and exit.\n -n NUM Number of output POSCARs to be created. [default: 100]\n --deform-range=DEFORM_RANGE\n Range of the lattice deformation ratio. [default: 0.01,0.2]\n --displace-range=DISPLACE_RANGE\n Range of the atom displacements in ratio to (atomic volume)^{-3}. [default: 0.1]\n --num-displace=NUM_DISPLACE\n Number of displacements per deformation. [default: 2]\n\"\"\"\nfrom __future__ import print_function\n\nfrom docopt import docopt\nimport numpy as np\nimport random\nfrom ase.io import read,write\n\n#======================================== subroutines and functions\ndef rotate(vec,axis,angle):\n \"\"\"\n Rotate the vector `vec` by `angle` around `axis`.\n `vec` and `axis` are 3-D vector, `angle` is in degree.\n \"\"\"\n theta = angle/180. *np.pi\n n = np.array(axis)\n n = n/np.linalg.norm(n)\n newvec = np.zeros(3,dtype=float)\n newvec = n *np.dot(n,vec) \\\n +(vec- n*np.dot(n,vec))*np.cos(theta) \\\n +np.cross(vec,n)*np.sin(theta)\n return newvec\n\ndef deformed_vector(a,maxlen):\n if type(a) is not np.ndarray:\n a = np.array(a)\n \n r = np.array([0.5-random.random(), 0.5-random.random(), 0.5-random.random()])\n #...make random vector normal to the vector `a`\n axr = np.cross(a,r)\n #...n is the axis of rotation\n n = axr / np.linalg.norm(axr)\n #...rotation angle between 0 to 180\n angle = 180.0 *random.random()\n #...length of deformation vector\n length = maxlen *random.random()\n da = a /np.linalg.norm(a) *length\n da = rotate(da,n,angle)\n return a+da\n\n\n############################################################ main\n\nif __name__ == \"__main__\":\n\n args = docopt(__doc__)\n\n num_data = int(args['-n'])\n deform_range = [ float(x) for x in args['--deform-range'].split(',') ]\n displace_range = float(args['--displace-range'])\n num_displace = int(args['--num-displace'])\n infname= args['POSCAR']\n\n atoms0 = read(infname,format='vasp')\n\n dlatd = (deform_range[1] -deform_range[0])/(num_data-1)\n ddisp = displace_range/num_displace\n print('deformation range = ',deform_range[0],deform_range[1])\n print('displace range = ',displace_range)\n print('num of displace = ',num_displace)\n print('dlatd = ',dlatd)\n print('ddisp = ',ddisp)\n\n n = 0\n while True:\n latd = dlatd*n +deform_range[0]\n cell0 = atoms0.get_cell()\n a = np.array(cell0[0])\n b = np.array(cell0[1])\n c = np.array(cell0[2])\n anew = deformed_vector(a,np.linalg.norm(a)*latd)\n bnew = deformed_vector(b,np.linalg.norm(b)*latd)\n cnew = deformed_vector(c,np.linalg.norm(c)*latd)\n cell = [anew,bnew,cnew]\n for idisp in range(num_displace):\n n += 1\n if n > num_data:\n break\n disp = ddisp*(idisp+1)\n atoms = atoms0.copy()\n atoms.set_cell(cell,scale_atoms=True)\n avol = atoms.get_volume()/len(atoms)\n avol3= avol**(1.0/3)\n dmax = avol3*disp\n pos = atoms.get_positions()\n for ia in range(1,len(atoms)):\n for l in range(3):\n pos[ia,l] = pos[ia,l] +dmax*(2.0*random.random()-1.0)\n atoms.set_positions(pos)\n outfname = 'POSCAR_{0:05d}'.format(n)\n write(outfname,images=atoms,format='vasp',\n direct=True,vasp5=True,sort=True)\n print('fname,avol= {0:s} {1:7.2f}'.format(outfname,\n atoms.get_volume()/len(atoms)))\n if n > num_data:\n break\n"
]
| [
[
"numpy.sin",
"numpy.array",
"numpy.linalg.norm",
"numpy.dot",
"numpy.zeros",
"numpy.cos",
"numpy.cross"
]
]
|
ngodber/discretize | [
"2329c9e9552b5c05f40ebf62f0bb207267bd2f92"
]
| [
"tests/tree/test_tree_utils.py"
]
| [
"import numpy as np\nimport unittest\nfrom discretize.utils import mesh_builder_xyz, refine_tree_xyz\n\nTOL = 1e-8\nnp.random.seed(12)\n\n\nclass TestRefineOcTree(unittest.TestCase):\n def test_radial(self):\n dx = 0.25\n rad = 10\n mesh = mesh_builder_xyz(\n np.c_[0.01, 0.01, 0.01],\n [dx, dx, dx],\n depth_core=0,\n padding_distance=[[0, 20], [0, 20], [0, 20]],\n mesh_type=\"TREE\",\n )\n\n radCell = int(np.ceil(rad / dx))\n mesh = refine_tree_xyz(\n mesh,\n np.c_[0, 0, 0],\n octree_levels=[radCell],\n method=\"radial\",\n finalize=True,\n )\n cell_levels = mesh.cell_levels_by_index(np.arange(mesh.n_cells))\n\n vol = 4.0 * np.pi / 3.0 * (rad+dx) ** 3.0\n\n vol_mesh = mesh.cell_volumes[cell_levels == mesh.max_level].sum()\n\n self.assertLess(np.abs(vol - vol_mesh)/vol, 0.05)\n\n levels, cells_per_level = np.unique(cell_levels, return_counts=True)\n\n self.assertEqual(mesh.n_cells, 311858)\n np.testing.assert_array_equal(levels, [3, 4, 5, 6, 7])\n np.testing.assert_array_equal(cells_per_level, [232, 1176, 2671, 9435, 298344])\n\n\n def test_box(self):\n dx = 0.25\n dl = 10\n\n # Create a box 2*dl in width\n X, Y, Z = np.meshgrid(np.c_[-dl, dl], np.c_[-dl, dl], np.c_[-dl, dl])\n xyz = np.c_[np.ravel(X), np.ravel(Y), np.ravel(Z)]\n mesh = mesh_builder_xyz(\n np.c_[0.01, 0.01, 0.01],\n [dx, dx, dx],\n depth_core=0,\n padding_distance=[[0, 20], [0, 20], [0, 20]],\n mesh_type=\"TREE\",\n )\n\n mesh = refine_tree_xyz(\n mesh, xyz, octree_levels=[0, 1], method=\"box\", finalize=True\n )\n cell_levels = mesh.cell_levels_by_index(np.arange(mesh.n_cells))\n\n vol = (2*(dl+2*dx))**3 # 2*dx is cell size at second to highest level\n vol_mesh = np.sum(mesh.cell_volumes[cell_levels == mesh.max_level - 1])\n self.assertLess((vol-vol_mesh)/vol, 0.05)\n\n levels, cells_per_level = np.unique(cell_levels, return_counts=True)\n\n self.assertEqual(mesh.n_cells, 80221)\n np.testing.assert_array_equal(levels, [3, 4, 5, 6])\n np.testing.assert_array_equal(cells_per_level, [80, 1762, 4291, 74088])\n\n def test_surface(self):\n dx = 0.1\n dl = 20\n\n # Define triangle\n xyz = np.r_[\n np.c_[-dl / 2, -dl / 2, 0],\n np.c_[dl / 2, -dl / 2, 0],\n np.c_[dl / 2, dl / 2, 0],\n ]\n mesh = mesh_builder_xyz(\n np.c_[0.01, 0.01, 0.01],\n [dx, dx, dx],\n depth_core=0,\n padding_distance=[[0, 20], [0, 20], [0, 20]],\n mesh_type=\"TREE\",\n )\n\n mesh = refine_tree_xyz(\n mesh, xyz, octree_levels=[1], method=\"surface\", finalize=True\n )\n\n # Volume of triangle\n vol = dl * dl * dx / 2\n\n residual = (\n np.abs(\n vol\n - mesh.cell_volumes[\n mesh._cell_levels_by_indexes(range(mesh.nC)) == mesh.max_level\n ].sum()\n / 2\n )\n / vol\n * 100\n )\n\n self.assertLess(residual, 5)\n\n def test_errors(self):\n dx = 0.25\n rad = 10\n self.assertRaises(\n ValueError,\n mesh_builder_xyz,\n np.c_[0.01, 0.01, 0.01],\n [dx, dx, dx],\n depth_core=0,\n padding_distance=[[0, 20], [0, 20], [0, 20]],\n mesh_type=\"cyl\",\n )\n\n mesh = mesh_builder_xyz(\n np.c_[0.01, 0.01, 0.01],\n [dx, dx, dx],\n depth_core=0,\n padding_distance=[[0, 20], [0, 20], [0, 20]],\n mesh_type=\"tree\",\n )\n\n radCell = int(np.ceil(rad / dx))\n self.assertRaises(\n NotImplementedError,\n refine_tree_xyz,\n mesh,\n np.c_[0, 0, 0],\n octree_levels=[radCell],\n method=\"other\",\n finalize=True,\n )\n\n self.assertRaises(\n ValueError,\n refine_tree_xyz,\n mesh,\n np.c_[0, 0, 0],\n octree_levels=[radCell],\n octree_levels_padding=[],\n method=\"surface\",\n finalize=True,\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
]
| [
[
"numpy.ceil",
"numpy.random.seed",
"numpy.sum",
"numpy.testing.assert_array_equal",
"numpy.arange",
"numpy.ravel",
"numpy.abs",
"numpy.meshgrid",
"numpy.unique"
]
]
|
tzcskys/Attention-Gated-Networks | [
"186cc2d054acc2a1938acc3450f0efaa7a167382"
]
| [
"models/layers/nonlocal_layer.py"
]
| [
"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom models.networks_other import init_weights\n\n\nclass _NonLocalBlockND(nn.Module):\n def __init__(self, in_channels, inter_channels=None, dimension=3, mode='embedded_gaussian',\n sub_sample_factor=4, bn_layer=True):\n super(_NonLocalBlockND, self).__init__()\n\n assert dimension in [1, 2, 3]\n assert mode in ['embedded_gaussian', 'gaussian', 'dot_product', 'concatenation', 'concat_proper', 'concat_proper_down']\n\n # print('Dimension: %d, mode: %s' % (dimension, mode))\n\n self.mode = mode\n self.dimension = dimension\n self.sub_sample_factor = sub_sample_factor if isinstance(sub_sample_factor, list) else [sub_sample_factor]\n\n self.in_channels = in_channels\n self.inter_channels = inter_channels\n\n if self.inter_channels is None:\n self.inter_channels = in_channels // 2\n if self.inter_channels == 0:\n self.inter_channels = 1\n\n if dimension == 3:\n conv_nd = nn.Conv3d\n max_pool = nn.MaxPool3d\n bn = nn.BatchNorm3d\n elif dimension == 2:\n conv_nd = nn.Conv2d\n max_pool = nn.MaxPool2d\n bn = nn.BatchNorm2d\n else:\n conv_nd = nn.Conv1d\n max_pool = nn.MaxPool1d\n bn = nn.BatchNorm1d\n\n self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,\n kernel_size=1, stride=1, padding=0)\n\n if bn_layer:\n self.W = nn.Sequential(\n conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,\n kernel_size=1, stride=1, padding=0),\n bn(self.in_channels)\n )\n nn.init.constant(self.W[1].weight, 0)\n nn.init.constant(self.W[1].bias, 0)\n else:\n self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels,\n kernel_size=1, stride=1, padding=0)\n nn.init.constant(self.W.weight, 0)\n nn.init.constant(self.W.bias, 0)\n\n self.theta = None\n self.phi = None\n\n if mode in ['embedded_gaussian', 'dot_product', 'concatenation', 'concat_proper', 'concat_proper_down']:\n self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,\n kernel_size=1, stride=1, padding=0)\n self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels,\n kernel_size=1, stride=1, padding=0)\n\n if mode in ['concatenation']:\n self.wf_phi = nn.Linear(self.inter_channels, 1, bias=False)\n self.wf_theta = nn.Linear(self.inter_channels, 1, bias=False)\n elif mode in ['concat_proper', 'concat_proper_down']:\n self.psi = nn.Conv2d(in_channels=self.inter_channels, out_channels=1, kernel_size=1, stride=1,\n padding=0, bias=True)\n\n if mode == 'embedded_gaussian':\n self.operation_function = self._embedded_gaussian\n elif mode == 'dot_product':\n self.operation_function = self._dot_product\n elif mode == 'gaussian':\n self.operation_function = self._gaussian\n elif mode == 'concatenation':\n self.operation_function = self._concatenation\n elif mode == 'concat_proper':\n self.operation_function = self._concatenation_proper\n elif mode == 'concat_proper_down':\n self.operation_function = self._concatenation_proper_down\n else:\n raise NotImplementedError('Unknown operation function.')\n\n if any(ss > 1 for ss in self.sub_sample_factor):\n self.g = nn.Sequential(self.g, max_pool(kernel_size=sub_sample_factor))\n if self.phi is None:\n self.phi = max_pool(kernel_size=sub_sample_factor)\n else:\n self.phi = nn.Sequential(self.phi, max_pool(kernel_size=sub_sample_factor))\n if mode == 'concat_proper_down':\n self.theta = nn.Sequential(self.theta, max_pool(kernel_size=sub_sample_factor))\n\n # Initialise weights\n for m in self.children():\n init_weights(m, init_type='kaiming')\n\n def forward(self, x):\n '''\n :param x: (b, c, t, h, w)\n :return:\n '''\n\n output = self.operation_function(x)\n return output\n\n def _embedded_gaussian(self, x):\n batch_size = x.size(0)\n\n # g=>(b, c, t, h, w)->(b, 0.5c, t, h, w)->(b, thw, 0.5c)\n g_x = self.g(x).view(batch_size, self.inter_channels, -1)\n g_x = g_x.permute(0, 2, 1)\n\n # theta=>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, thw, 0.5c)\n # phi =>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, 0.5c, thw)\n # f=>(b, thw, 0.5c)dot(b, 0.5c, twh) = (b, thw, thw)\n theta_x = self.theta(x).view(batch_size, self.inter_channels, -1)\n theta_x = theta_x.permute(0, 2, 1)\n phi_x = self.phi(x).view(batch_size, self.inter_channels, -1)\n f = torch.matmul(theta_x, phi_x)\n f_div_C = F.softmax(f, dim=-1)\n\n # (b, thw, thw)dot(b, thw, 0.5c) = (b, thw, 0.5c)->(b, 0.5c, t, h, w)->(b, c, t, h, w)\n y = torch.matmul(f_div_C, g_x)\n y = y.permute(0, 2, 1).contiguous()\n y = y.view(batch_size, self.inter_channels, *x.size()[2:])\n W_y = self.W(y)\n z = W_y + x\n\n return z\n\n def _gaussian(self, x):\n batch_size = x.size(0)\n g_x = self.g(x).view(batch_size, self.inter_channels, -1)\n g_x = g_x.permute(0, 2, 1)\n\n theta_x = x.view(batch_size, self.in_channels, -1)\n theta_x = theta_x.permute(0, 2, 1)\n\n if self.sub_sample_factor > 1:\n phi_x = self.phi(x).view(batch_size, self.in_channels, -1)\n else:\n phi_x = x.view(batch_size, self.in_channels, -1)\n\n f = torch.matmul(theta_x, phi_x)\n f_div_C = F.softmax(f, dim=-1)\n\n y = torch.matmul(f_div_C, g_x)\n y = y.permute(0, 2, 1).contiguous()\n y = y.view(batch_size, self.inter_channels, *x.size()[2:])\n W_y = self.W(y)\n z = W_y + x\n\n return z\n\n def _dot_product(self, x):\n batch_size = x.size(0)\n\n g_x = self.g(x).view(batch_size, self.inter_channels, -1)\n g_x = g_x.permute(0, 2, 1)\n\n theta_x = self.theta(x).view(batch_size, self.inter_channels, -1)\n theta_x = theta_x.permute(0, 2, 1)\n phi_x = self.phi(x).view(batch_size, self.inter_channels, -1)\n f = torch.matmul(theta_x, phi_x)\n N = f.size(-1)\n f_div_C = f / N\n\n y = torch.matmul(f_div_C, g_x)\n y = y.permute(0, 2, 1).contiguous()\n y = y.view(batch_size, self.inter_channels, *x.size()[2:])\n W_y = self.W(y)\n z = W_y + x\n\n return z\n\n def _concatenation(self, x):\n batch_size = x.size(0)\n\n # g=>(b, c, t, h, w)->(b, 0.5c, thw/s**2)\n g_x = self.g(x).view(batch_size, self.inter_channels, -1)\n\n # theta=>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, thw, 0.5c)\n # phi =>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, thw/s**2, 0.5c)\n theta_x = self.theta(x).view(batch_size, self.inter_channels, -1).permute(0, 2, 1)\n phi_x = self.phi(x).view(batch_size, self.inter_channels, -1).permute(0, 2, 1)\n\n # theta => (b, thw, 0.5c) -> (b, thw, 1) -> (b, 1, thw) -> (expand) (b, thw/s**2, thw)\n # phi => (b, thw/s**2, 0.5c) -> (b, thw/s**2, 1) -> (expand) (b, thw/s**2, thw)\n # f=> RELU[(b, thw/s**2, thw) + (b, thw/s**2, thw)] = (b, thw/s**2, thw)\n f = self.wf_theta(theta_x).permute(0, 2, 1).repeat(1, phi_x.size(1), 1) + \\\n self.wf_phi(phi_x).repeat(1, 1, theta_x.size(1))\n f = F.relu(f, inplace=True)\n\n # Normalise the relations\n N = f.size(-1)\n f_div_c = f / N\n\n # g(x_j) * f(x_j, x_i)\n # (b, 0.5c, thw/s**2) * (b, thw/s**2, thw) -> (b, 0.5c, thw)\n y = torch.matmul(g_x, f_div_c)\n y = y.contiguous().view(batch_size, self.inter_channels, *x.size()[2:])\n W_y = self.W(y)\n z = W_y + x\n\n return z\n\n def _concatenation_proper(self, x):\n batch_size = x.size(0)\n\n # g=>(b, c, t, h, w)->(b, 0.5c, thw/s**2)\n g_x = self.g(x).view(batch_size, self.inter_channels, -1)\n\n # theta=>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, 0.5c, thw)\n # phi =>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, 0.5c, thw/s**2)\n theta_x = self.theta(x).view(batch_size, self.inter_channels, -1)\n phi_x = self.phi(x).view(batch_size, self.inter_channels, -1)\n\n # theta => (b, 0.5c, thw) -> (expand) (b, 0.5c, thw/s**2, thw)\n # phi => (b, 0.5c, thw/s**2) -> (expand) (b, 0.5c, thw/s**2, thw)\n # f=> RELU[(b, 0.5c, thw/s**2, thw) + (b, 0.5c, thw/s**2, thw)] = (b, 0.5c, thw/s**2, thw)\n f = theta_x.unsqueeze(dim=2).repeat(1,1,phi_x.size(2),1) + \\\n phi_x.unsqueeze(dim=3).repeat(1,1,1,theta_x.size(2))\n f = F.relu(f, inplace=True)\n\n # psi -> W_psi^t * f -> (b, 1, thw/s**2, thw) -> (b, thw/s**2, thw)\n f = torch.squeeze(self.psi(f), dim=1)\n\n # Normalise the relations\n f_div_c = F.softmax(f, dim=1)\n\n # g(x_j) * f(x_j, x_i)\n # (b, 0.5c, thw/s**2) * (b, thw/s**2, thw) -> (b, 0.5c, thw)\n y = torch.matmul(g_x, f_div_c)\n y = y.contiguous().view(batch_size, self.inter_channels, *x.size()[2:])\n W_y = self.W(y)\n z = W_y + x\n\n return z\n\n def _concatenation_proper_down(self, x):\n batch_size = x.size(0)\n\n # g=>(b, c, t, h, w)->(b, 0.5c, thw/s**2)\n g_x = self.g(x).view(batch_size, self.inter_channels, -1)\n\n # theta=>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, 0.5c, thw)\n # phi =>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, 0.5c, thw/s**2)\n theta_x = self.theta(x)\n downsampled_size = theta_x.size()\n theta_x = theta_x.view(batch_size, self.inter_channels, -1)\n phi_x = self.phi(x).view(batch_size, self.inter_channels, -1)\n\n # theta => (b, 0.5c, thw) -> (expand) (b, 0.5c, thw/s**2, thw)\n # phi => (b, 0.5, thw/s**2) -> (expand) (b, 0.5c, thw/s**2, thw)\n # f=> RELU[(b, 0.5c, thw/s**2, thw) + (b, 0.5c, thw/s**2, thw)] = (b, 0.5c, thw/s**2, thw)\n f = theta_x.unsqueeze(dim=2).repeat(1,1,phi_x.size(2),1) + \\\n phi_x.unsqueeze(dim=3).repeat(1,1,1,theta_x.size(2))\n f = F.relu(f, inplace=True)\n\n # psi -> W_psi^t * f -> (b, 0.5c, thw/s**2, thw) -> (b, 1, thw/s**2, thw) -> (b, thw/s**2, thw)\n f = torch.squeeze(self.psi(f), dim=1)\n\n # Normalise the relations\n f_div_c = F.softmax(f, dim=1)\n\n # g(x_j) * f(x_j, x_i)\n # (b, 0.5c, thw/s**2) * (b, thw/s**2, thw) -> (b, 0.5c, thw)\n y = torch.matmul(g_x, f_div_c)\n y = y.contiguous().view(batch_size, self.inter_channels, *downsampled_size[2:])\n\n # upsample the final featuremaps # (b,0.5c,t/s1,h/s2,w/s3)\n y = F.upsample(y, size=x.size()[2:], mode='trilinear')\n\n # attention block output\n W_y = self.W(y)\n z = W_y + x\n\n return z\n\n\nclass NONLocalBlock1D(_NonLocalBlockND):\n def __init__(self, in_channels, inter_channels=None, mode='embedded_gaussian', sub_sample_factor=2, bn_layer=True):\n super(NONLocalBlock1D, self).__init__(in_channels,\n inter_channels=inter_channels,\n dimension=1, mode=mode,\n sub_sample_factor=sub_sample_factor,\n bn_layer=bn_layer)\n\n\nclass NONLocalBlock2D(_NonLocalBlockND):\n def __init__(self, in_channels, inter_channels=None, mode='embedded_gaussian', sub_sample_factor=2, bn_layer=True):\n super(NONLocalBlock2D, self).__init__(in_channels,\n inter_channels=inter_channels,\n dimension=2, mode=mode,\n sub_sample_factor=sub_sample_factor,\n bn_layer=bn_layer)\n\n\nclass NONLocalBlock3D(_NonLocalBlockND):\n def __init__(self, in_channels, inter_channels=None, mode='embedded_gaussian', sub_sample_factor=2, bn_layer=True):\n super(NONLocalBlock3D, self).__init__(in_channels,\n inter_channels=inter_channels,\n dimension=3, mode=mode,\n sub_sample_factor=sub_sample_factor,\n bn_layer=bn_layer)\n\n\nif __name__ == '__main__':\n from torch.autograd import Variable\n\n mode_list = ['concatenation']\n #mode_list = ['embedded_gaussian', 'gaussian', 'dot_product', ]\n\n for mode in mode_list:\n print(mode)\n img = Variable(torch.zeros(2, 4, 5))\n net = NONLocalBlock1D(4, mode=mode, sub_sample_factor=2)\n out = net(img)\n print(out.size())\n\n img = Variable(torch.zeros(2, 4, 5, 3))\n net = NONLocalBlock2D(4, mode=mode, sub_sample_factor=1, bn_layer=False)\n out = net(img)\n print(out.size())\n\n img = Variable(torch.zeros(2, 4, 5, 4, 5))\n net = NONLocalBlock3D(4, mode=mode)\n out = net(img)\n print(out.size())\n"
]
| [
[
"torch.zeros",
"torch.nn.Linear",
"torch.nn.init.constant",
"torch.nn.Conv2d",
"torch.nn.functional.softmax",
"torch.nn.functional.relu",
"torch.matmul"
]
]
|
nalbarr/kubeflow-tutorial | [
"80ad975b60517f2d25f38ef455373c43a0a788d3"
]
| [
"4_WORKING_DIRX/web-ui/hello_tf.py"
]
| [
"# NAA. \n# - below uses Tensorflow 2.0 in backward compatibility mode\n\n#import tensorflow.compat.v1 as tf\n#from tensorflow.examples.tutorials.mnist import input_data\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport tensorflow as tf\n\n#sess = tf.Session()\n#print(sess.run(hello))\n\n# test imports\nhello = tf.constant('Hello, TensorFlow!')\n\nmnist = tf.keras.datasets.mnist\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train, x_test = x_train / 255.0, x_test / 255.0\n\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(10, activation='softmax')\n ])\n\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\nmodel.fit(x_train, y_train, epochs=5)\n\nmodel.evaluate(x_test, y_test, verbose=2)\n"
]
| [
[
"tensorflow.keras.layers.Flatten",
"tensorflow.constant",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.Dense"
]
]
|
christophertbrown/bioscripts | [
"c8c657b7895681b539bdfd8c78f786f9b99ab230"
]
| [
"ctbBio/genome_coverage.py"
]
| [
"#!/usr/bin/env python3\n\n\"\"\"\nscript for calculating genome coverage\n\"\"\"\n\nimport os\nimport sys\nimport argparse\nimport pandas as pd\nfrom ctbBio.fasta import iterate_fasta as parse_fasta\n\ndef parse_cov(cov_table, scaffold2genome):\n \"\"\"\n calculate genome coverage from scaffold coverage table\n \"\"\"\n size = {} # size[genome] = genome size\n mapped = {} # mapped[genome][sample] = mapped bases\n # parse coverage files\n for line in open(cov_table):\n line = line.strip().split('\\t')\n if line[0].startswith('#'):\n samples = line[1:]\n samples = [i.rsplit('/', 1)[-1].split('.', 1)[0] for i in samples]\n continue\n scaffold, length = line[0].split(': ')\n length = float(length)\n covs = [float(i) for i in line[1:]]\n bases = [c * length for c in covs]\n if scaffold not in scaffold2genome:\n continue\n genome = scaffold2genome[scaffold]\n if genome not in size:\n size[genome] = 0\n mapped[genome] = {sample:0 for sample in samples}\n # keep track of genome size\n size[genome] += length\n # keep track of number of mapped bases\n for sample, count in zip(samples, bases):\n mapped[genome][sample] += count\n # calculate coverage from base counts and genome size\n coverage = {'genome':[], 'genome size (bp)':[], 'sample':[], 'coverage':[]}\n for genome, length in size.items():\n for sample in samples:\n cov = mapped[genome][sample] / length\n coverage['genome'].append(genome)\n coverage['genome size (bp)'].append(length)\n coverage['sample'].append(sample)\n coverage['coverage'].append(cov)\n return pd.DataFrame(coverage)\n\ndef genome_coverage(covs, s2b):\n \"\"\"\n calculate genome coverage from scaffold coverage\n \"\"\"\n COV = []\n for cov in covs:\n COV.append(parse_cov(cov, s2b))\n return pd.concat(COV)\n\ndef parse_s2bs(s2bs):\n \"\"\"\n convert s2b files to dictionary\n \"\"\"\n s2b = {}\n for s in s2bs:\n for line in open(s):\n line = line.strip().split('\\t')\n s, b = line[0], line[1]\n s2b[s] = b\n return s2b\n\ndef fa2s2b(fastas):\n \"\"\"\n convert fastas to s2b dictionary\n \"\"\"\n s2b = {}\n for fa in fastas:\n for seq in parse_fasta(fa):\n s = seq[0].split('>', 1)[1].split()[0]\n s2b[s] = fa.rsplit('/', 1)[-1].rsplit('.', 1)[0]\n return s2b\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description = '# calculate genome coverage from scaffold coverage')\n parser.add_argument(\\\n '-c', required = True, nargs = '*', \\\n help = 'calculate_coverage.py scaffold coverage file(s) - required')\n parser.add_argument(\\\n '-s', required = False, nargs = '*', \\\n help = 'scaffold to bin files(s)')\n parser.add_argument(\\\n '-f', required = False, nargs = '*', \\\n help = 'fasta file(s) for each genome - use instead of -s')\n args = vars(parser.parse_args())\n s2bs, fastas, coverages = args['s'], args['f'], args['c']\n if s2bs is None and fastas is None:\n print('-s or -f is required')\n exit()\n if s2bs is not None:\n s2b = parse_s2bs(s2bs)\n else:\n s2b = fa2s2b(fastas)\n df = genome_coverage(coverages, s2b)\n df['genome: length (bp)'] = ['%s: %s' % (g, l) for g, l in zip(df['genome'], df['genome size (bp)'])]\n print(df.pivot('genome: length (bp)', 'sample', 'coverage').to_csv(sep = '\\t'))\n"
]
| [
[
"pandas.DataFrame",
"pandas.concat"
]
]
|
scottstanie/RAiDER | [
"7cf0299f045b13b00b416f31bf3f8d9f1bd825b2",
"7cf0299f045b13b00b416f31bf3f8d9f1bd825b2"
]
| [
"tools/RAiDER/prepFromAria.py",
"test/test_checkArgs.py"
]
| [
"#!/usr/bin/env python3\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# Author: Jeremy Maurer\n# Copyright 2020, by the California Institute of Technology. ALL RIGHTS\n# RESERVED. United States Government Sponsorship acknowledged.\n#\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nimport numpy as np\nfrom osgeo import gdal\n\nfrom RAiDER.utilFcns import gdal_open, writeArrayToRaster\n\n\ndef parse_args():\n \"\"\"Parse command line arguments using argparse.\"\"\"\n import argparse\n p = argparse.ArgumentParser(\n description='Prepare files from ARIA-tools output to use with RAiDER')\n\n # Line of sight\n p.add_argument(\n '--incFile', '-i', type=str,\n help='GDAL-readable raster image file of inclination',\n metavar='INC', required=True)\n p.add_argument(\n '--azFile', '-a', type=str,\n help='GDAL-readable raster image file of azimuth',\n metavar='AZ', required=True)\n\n p.add_argument(\n '--los_filename', '-f', default='los.rdr', type=str, dest='los_file',\n help=('Output Line-of-sight filename'))\n p.add_argument(\n '--lat_filename', '-l', default='lat.rdr', type=str, dest='lat_file',\n help=('Output latitude filename'))\n p.add_argument(\n '--lon_filename', '-L', default='lon.rdr', type=str, dest='lon_file',\n help=('Output longitude filename'))\n\n p.add_argument(\n '--format', '-t', default='ENVI', type=str, dest='fmt',\n help=('Output file format'))\n\n return p.parse_args(), p\n\n\ndef makeLatLonGrid(inFile, lonFileName, latFileName, fmt='ENVI'):\n '''\n Convert the geocoded grids to lat/lon files for input to RAiDER\n '''\n ds = gdal.Open(inFile, gdal.GA_ReadOnly)\n xSize = ds.RasterXSize\n ySize = ds.RasterYSize\n gt = ds.GetGeoTransform()\n proj = ds.GetProjection()\n\n # Create the xy grid\n xStart = gt[0]\n yStart = gt[3]\n xStep = gt[1]\n yStep = gt[-1]\n\n xEnd = xStart + xStep * xSize - 0.5*xStep\n yEnd = yStart + yStep * ySize - 0.5*yStep\n\n x = np.arange(xStart, xEnd, xStep)\n y = np.arange(yStart, yEnd, yStep)\n X, Y = np.meshgrid(x, y)\n writeArrayToRaster(X, lonFileName, 0., fmt, proj, gt)\n writeArrayToRaster(Y, latFileName, 0., fmt, proj, gt)\n\n\ndef makeLOSFile(incFile, azFile, fmt='ENVI', filename='los.rdr'):\n '''\n Create a line-of-sight file from ARIA-derived azimuth and inclination files\n '''\n az, az_proj, az_gt = gdal_open(azFile, returnProj=True)\n az[az == 0] = np.nan\n inc = gdal_open(incFile)\n\n heading = 90 - az\n heading[np.isnan(heading)] = 0.\n\n array_shp = np.shape(az)[:2]\n dType = az.dtype\n\n if 'complex' in str(dType):\n dType = gdal.GDT_CFloat32\n elif 'float' in str(dType):\n dType = gdal.GDT_Float32\n else:\n dType = gdal.GDT_Byte\n\n # Write the data to a file\n driver = gdal.GetDriverByName(fmt)\n ds = driver.Create(filename, array_shp[1], array_shp[0], 2, dType)\n ds.SetProjection(az_proj)\n ds.SetGeoTransform(az_gt)\n b1 = ds.GetRasterBand(1)\n b1.WriteArray(inc)\n b1.SetNoDataValue(0.)\n b2 = ds.GetRasterBand(2)\n b2.WriteArray(heading)\n b2.SetNoDataValue(0.)\n ds = None\n b1 = None\n b2 = None\n\n return 0\n\n\ndef prepFromAria():\n '''\n A command-line utility to convert ARIA standard product outputs from ARIA-tools to\n RAiDER-compatible format\n '''\n args, p = parse_args()\n makeLOSFile(args.incFile, args.azFile, args.fmt, args.los_file)\n makeLatLonGrid(args.incFile, args.lon_file, args.lat_file, args.fmt)\n",
"import datetime\nimport os\nimport pytest\nimport sys\n\nimport multiprocessing as mp\nimport numpy as np\nimport pandas as pd\n\nfrom argparse import ArgumentParser\nfrom test import TEST_DIR, pushd\n\nimport RAiDER.runProgram\n\nfrom RAiDER.checkArgs import checkArgs, makeDelayFileNames, modelName2Module\nfrom RAiDER.constants import _ZREF\nfrom RAiDER.losreader import Zenith\n\n\nSCENARIO_1 = os.path.join(TEST_DIR, \"scenario_1\")\nSCENARIO_2 = os.path.join(TEST_DIR, \"scenario_2\")\n\n\ndef isWriteable(dirpath):\n '''Test whether a directory is writeable'''\n try:\n filehandle = open(os.path.join(dirpath, 'tmp.txt'), 'w')\n filehandle.close()\n return True\n except IOError:\n return False\n\n\[email protected]\ndef parsed_args(tmp_path):\n parser = RAiDER.runProgram.create_parser()\n args = parser.parse_args([\n '--date', '20200103',\n '--time', '23:00:00',\n #'--latlon', 'latfile.dat', 'lonfile.dat',\n '--bbox', '-1', '1', '-1', '1',\n '--model', 'ERA5',\n '--outformat', 'hdf5'\n ])\n return args, parser\n\n\ndef test_checkArgs_outfmt_1(parsed_args):\n '''Test that passing height levels with hdf5 outformat works'''\n args, p = parsed_args\n args.outformat = 'hdf5'\n args.heightlvs = [10, 100, 1000]\n checkArgs(args, p)\n assert True\n\n\ndef test_checkArgs_outfmt_2(parsed_args):\n '''Test that passing a raster format with height levels throws an error'''\n args, p = parsed_args\n args.heightlvs = [10, 100, 1000]\n args.outformat = 'envi'\n with pytest.raises(ValueError):\n checkArgs(args, p)\n\n\ndef test_checkArgs_outfmt_3(parsed_args):\n '''Test that passing a raster format with height levels throws an error'''\n args, p = parsed_args\n args.query_area = os.path.join(SCENARIO_2, 'stations.csv')\n argDict = checkArgs(args, p)\n assert argDict['flag'] == 'station_file'\n\n\ndef test_checkArgs_outfmt_4(parsed_args):\n '''Test that passing a raster format with height levels throws an error'''\n args, p = parsed_args\n args.query_area = [os.path.join(SCENARIO_1, 'geom', 'lat.dat'), os.path.join(SCENARIO_1, 'geom', 'lat.dat')]\n argDict = checkArgs(args, p)\n assert argDict['flag'] == 'files'\n\n\ndef test_checkArgs_outfmt_5(parsed_args):\n '''Test that passing a raster format with height levels throws an error'''\n args, p = parsed_args\n args.query_area = os.path.join(SCENARIO_2, 'stations.csv')\n argDict = checkArgs(args, p)\n assert pd.read_csv(argDict['wetFilenames'][0]).shape == (8,4)\n\ndef test_checkArgs_outloc_1(parsed_args):\n '''Test that the default output and weather model directories are correct'''\n args, p = parsed_args\n argDict = checkArgs(args, p)\n out = argDict['out']\n wmLoc = argDict['wmLoc']\n assert os.path.abspath(out) == os.getcwd()\n assert os.path.abspath(wmLoc) == os.path.join(os.getcwd(), 'weather_files')\n\n\ndef test_checkArgs_outloc_2(parsed_args, tmp_path):\n '''Tests that the correct output location gets assigned when provided'''\n with pushd(tmp_path):\n args, p = parsed_args\n args.out = tmp_path\n argDict = checkArgs(args, p)\n out = argDict['out']\n assert out == tmp_path\n\n\ndef test_checkArgs_outloc_2b(parsed_args, tmp_path):\n ''' Tests that the weather model directory gets passed through by itself'''\n with pushd(tmp_path):\n args, p = parsed_args\n args.out = tmp_path\n args.wmLoc = 'weather_dir'\n argDict = checkArgs(args, p)\n assert argDict['wmLoc'] == 'weather_dir'\n\n\ndef test_checkArgs_outloc_3(parsed_args):\n '''Tests that the weather model directory gets created when needed'''\n args, p = parsed_args\n argDict = checkArgs(args, p)\n assert os.path.isdir(argDict['wmLoc'])\n\n\ndef test_checkArgs_outloc_4(parsed_args):\n '''Tests for creating writeable weather model directory'''\n args, p = parsed_args\n argDict = checkArgs(args, p)\n\n assert isWriteable(argDict['wmLoc'])\n\n\ndef test_ll_bounds_1(parsed_args):\n '''Tests that lats out of bounds raises error'''\n args, p = parsed_args\n args.query_area[0] = -91\n with pytest.raises(ValueError):\n checkArgs(args, p)\n\n\ndef test_ll_bounds_2(parsed_args):\n '''Tests that lats out of bounds raises error'''\n args, p = parsed_args\n args.query_area[1] = 91\n with pytest.raises(ValueError):\n checkArgs(args, p)\n\n\ndef test_los_1(parsed_args):\n '''Tests that lats out of bounds raises error'''\n args, p = parsed_args\n args.lineofsight = 'los.rdr'\n argDict = checkArgs(args, p)\n assert argDict['los'][0] == 'los'\n assert argDict['los'][1] == 'los.rdr'\n\n\ndef test_los_2(parsed_args):\n '''Tests that lats out of bounds raises error'''\n args, p = parsed_args\n args.statevectors = 'sv.txt'\n argDict = checkArgs(args, p)\n assert argDict['los'][0] == 'sv'\n assert argDict['los'][1] == 'sv.txt'\n\n\ndef test_los_3(parsed_args):\n '''Tests that lats out of bounds raises error'''\n args, p = parsed_args\n argDict = checkArgs(args, p)\n assert argDict['los'] == Zenith\n\n\ndef test_models_1a(parsed_args):\n '''Tests that the weather model gets passed through correctly'''\n args, p = parsed_args\n argDict = checkArgs(args, p)\n assert argDict['weather_model']['type'].Model() == 'ERA-5'\n assert argDict['weather_model']['name'] == 'era5'\n\n\ndef test_models_1b(parsed_args):\n '''Tests that the weather model gets passed through correctly'''\n args, p = parsed_args\n args.model = 'HRRR'\n argDict = checkArgs(args, p)\n assert argDict['weather_model']['type'].Model() == 'HRRR'\n assert argDict['weather_model']['name'] == 'hrrr'\n\n\ndef test_models_1c(parsed_args):\n '''Tests that the weather model gets passed through correctly'''\n args, p = parsed_args\n args.model = 'NCMR'\n argDict = checkArgs(args, p)\n assert argDict['weather_model']['type'].Model() == 'NCMR'\n assert argDict['weather_model']['name'] == 'ncmr'\n\n\ndef test_models_1d(parsed_args):\n '''Tests that the weather model gets passed through correctly'''\n args, p = parsed_args\n args.model = 'era-5'\n argDict = checkArgs(args, p)\n assert argDict['weather_model']['type'].Model() == 'ERA-5'\n assert argDict['weather_model']['name'] == 'era5'\n\n\ndef test_models_1e(parsed_args):\n '''Tests that the weather model gets passed through correctly'''\n args, p = parsed_args\n args.model = 'ERA-5'\n argDict = checkArgs(args, p)\n assert argDict['weather_model']['type'].Model() == 'ERA-5'\n assert argDict['weather_model']['name'] == 'era5'\n\n\ndef test_models_1f(parsed_args):\n '''Tests that the weather model gets passed through correctly'''\n args, p = parsed_args\n args.model = 'Era-5'\n argDict = checkArgs(args, p)\n assert argDict['weather_model']['type'].Model() == 'ERA-5'\n assert argDict['weather_model']['name'] == 'era5'\n\n\ndef test_models_2(parsed_args):\n '''Tests that unknown weather models get rejected'''\n args, p = parsed_args\n args.model = 'unknown'\n with pytest.raises(NotImplementedError):\n checkArgs(args, p)\n\n\ndef test_models_3a(parsed_args):\n '''Tests that WRF weather models requires files'''\n args, p = parsed_args\n args.model = 'WRF'\n with pytest.raises(RuntimeError):\n checkArgs(args, p)\n\n\ndef test_models_3b(parsed_args):\n '''Tests that HDF5 weather models requires files'''\n args, p = parsed_args\n args.model = 'HDF5'\n with pytest.raises(RuntimeError):\n checkArgs(args, p)\n\n\ndef test_models_3c(parsed_args):\n '''Tests that WRF weather models requires files'''\n args, p = parsed_args\n args.model = 'WRF'\n args.files = ['file1.wrf', 'file2.wrf']\n argDict = checkArgs(args, p)\n assert True\n\n\ndef test_zref_1(parsed_args):\n '''tests that default zref gets generated'''\n args, p = parsed_args\n argDict = checkArgs(args, p)\n assert argDict['zref'] == _ZREF\n\n\ndef test_zref_2(parsed_args):\n '''tests that default zref gets generated'''\n ztest = 20000\n args, p = parsed_args\n args.zref = ztest\n argDict = checkArgs(args, p)\n assert argDict['zref'] == ztest\n\n\ndef test_parallel_1(parsed_args):\n '''tests that parallel options are handled correctly'''\n args, p = parsed_args\n argDict = checkArgs(args, p)\n assert argDict['parallel'] == 1\n\n\ndef test_parallel_2(parsed_args):\n '''tests that parallel options are handled correctly'''\n args, p = parsed_args\n args.parallel = 'all'\n argDict = checkArgs(args, p)\n assert argDict['parallel'] == mp.cpu_count()\n\n\ndef test_parallel_3(parsed_args):\n '''tests that parallel options are handled correctly'''\n args, p = parsed_args\n args.parallel = 2\n argDict = checkArgs(args, p)\n assert argDict['parallel'] == 2\n\n\ndef test_parallel_4(parsed_args):\n '''tests that parallel options are handled correctly'''\n args, p = parsed_args\n args.parallel = 2000\n argDict = checkArgs(args, p)\n assert argDict['parallel'] == mp.cpu_count()\n\n\ndef test_verbose_1(parsed_args):\n '''tests that verbose option is handled correctly'''\n args, p = parsed_args\n argDict = checkArgs(args, p)\n assert not argDict['verbose']\n\n\ndef test_verbose_2(parsed_args):\n '''tests that verbose option is handled correctly'''\n args, p = parsed_args\n args.verbose = True\n argDict = checkArgs(args, p)\n assert argDict['verbose']\n\n\ndef test_download_only_1(parsed_args):\n '''tests that the download-only option is handled correctly'''\n args, p = parsed_args\n argDict = checkArgs(args, p)\n assert not argDict['download_only']\n\n\ndef test_download_only_2(parsed_args):\n '''tests that the download-only option is handled correctly'''\n args, p = parsed_args\n args.download_only = True\n argDict = checkArgs(args, p)\n assert argDict['download_only']\n\n\ndef test_useWeatherNodes_1(parsed_args):\n '''tests that the correct flag gets passed'''\n args, p = parsed_args\n argDict = checkArgs(args, p)\n assert argDict['flag'] == 'bounding_box' # default arguments use a bounding box\n\n\ndef test_filenames_1(parsed_args):\n '''tests that the correct filenames are generated'''\n args, p = parsed_args\n argDict = checkArgs(args, p)\n assert 'Delay' not in argDict['wetFilenames'][0]\n assert 'wet' in argDict['wetFilenames'][0]\n assert 'hydro' in argDict['hydroFilenames'][0]\n assert '20200103' in argDict['wetFilenames'][0]\n assert '20200103' in argDict['hydroFilenames'][0]\n assert len(argDict['hydroFilenames']) == 1\n\n\ndef test_filenames_2(parsed_args):\n '''tests that the correct filenames are generated'''\n args, p = parsed_args\n args.query_area = os.path.join(SCENARIO_2, 'stations.csv')\n argDict = checkArgs(args, p)\n assert 'Delay' in argDict['wetFilenames'][0]\n assert '20200103' in argDict['wetFilenames'][0]\n assert len(argDict['wetFilenames']) == 1\n\n\ndef test_makeDelayFileNames_1():\n assert makeDelayFileNames(None, None, \"h5\", \"name\", \"dir\") == \\\n (\"dir/name_wet_ztd.h5\", \"dir/name_hydro_ztd.h5\")\n\n\ndef test_makeDelayFileNames_2():\n assert makeDelayFileNames(None, (), \"h5\", \"name\", \"dir\") == \\\n (\"dir/name_wet_std.h5\", \"dir/name_hydro_std.h5\")\n\n\ndef test_makeDelayFileNames_3():\n assert makeDelayFileNames(datetime.datetime(2020, 1, 1, 1, 2, 3), None, \"h5\", \"model_name\", \"dir\") == \\\n (\n \"dir/model_name_wet_20200101T010203_ztd.h5\",\n \"dir/model_name_hydro_20200101T010203_ztd.h5\"\n )\n\n\ndef test_makeDelayFileNames_4():\n assert makeDelayFileNames(datetime.datetime(1900, 12, 31, 1, 2, 3), \"los\", \"h5\", \"model_name\", \"dir\") == \\\n (\n \"dir/model_name_wet_19001231T010203_std.h5\",\n \"dir/model_name_hydro_19001231T010203_std.h5\"\n )\n\n\ndef test_model2module():\n model_module_name, model_obj = modelName2Module('ERA5')\n assert model_obj().Model() == 'ERA-5'\n\n\ndef test_dem_1(parsed_args):\n '''Test that passing a raster format with height levels throws an error'''\n args, p = parsed_args\n argDict = checkArgs(args, p)\n assert argDict['heights'][0] == 'skip'\n assert argDict['heights'][1] is None\n\n\ndef test_dem_2(parsed_args):\n '''Test that passing a raster format with height levels throws an error'''\n args, p = parsed_args\n args.heightlvs = [10, 100, 1000]\n argDict = checkArgs(args, p)\n assert argDict['heights'][0] == 'lvs'\n assert np.allclose(argDict['heights'][1], [10, 100, 1000])\n\n\ndef test_dem_3(parsed_args):\n '''Test that passing a raster format with height levels throws an error'''\n args, p = parsed_args\n args.heightlvs = [10, 100, 1000]\n args.query_area = os.path.join(SCENARIO_2, 'stations.csv')\n argDict = checkArgs(args, p)\n assert argDict['heights'][0] == 'lvs'\n assert np.allclose(argDict['heights'][1], [10, 100, 1000])\n\n\ndef test_dem_4(parsed_args):\n '''Test that passing a raster format with height levels throws an error'''\n args, p = parsed_args\n args.query_area = os.path.join(SCENARIO_2, 'stations.csv')\n argDict = checkArgs(args, p)\n assert argDict['heights'][0] == 'pandas'\n assert argDict['heights'][1][0] == argDict['wetFilenames'][0]\n\n\ndef test_dem_5(parsed_args):\n '''Test that passing a raster format with height levels throws an error'''\n args, p = parsed_args\n args.query_area = [os.path.join(SCENARIO_1, 'geom', 'lat.dat'), os.path.join(SCENARIO_1, 'geom', 'lat.dat')]\n argDict = checkArgs(args, p)\n assert argDict['heights'][0] == 'download'\n assert argDict['heights'][1] == os.path.join(argDict['out'], 'geom', 'warpedDEM.dem')\n"
]
| [
[
"numpy.meshgrid",
"numpy.isnan",
"numpy.arange",
"numpy.shape"
],
[
"numpy.allclose",
"pandas.read_csv"
]
]
|
rtpsw/ibis | [
"14b9baf3e1021e8698e7f0ae3c0ae5747543431c"
]
| [
"ibis/backends/pandas/execution/arrays.py"
]
| [
"import operator\nfrom typing import Any, Collection\n\nimport numpy as np\nimport pandas as pd\nfrom pandas.core.groupby import SeriesGroupBy\n\nimport ibis.expr.operations as ops\nfrom ibis.backends.pandas.dispatch import execute_node\n\n\n@execute_node.register(ops.ArrayColumn, list)\ndef execute_array_column(op, cols, **kwargs):\n df = pd.concat(cols, axis=1)\n return df.apply(lambda row: np.array(row, dtype=object), axis=1)\n\n\n@execute_node.register(ops.ArrayLength, pd.Series)\ndef execute_array_length(op, data, **kwargs):\n return data.apply(len)\n\n\n@execute_node.register(ops.ArrayLength, np.ndarray)\ndef execute_array_length_scalar(op, data, **kwargs):\n return len(data)\n\n\n@execute_node.register(ops.ArraySlice, pd.Series, int, (int, type(None)))\ndef execute_array_slice(op, data, start, stop, **kwargs):\n return data.apply(operator.itemgetter(slice(start, stop)))\n\n\n@execute_node.register(ops.ArraySlice, np.ndarray, int, (int, type(None)))\ndef execute_array_slice_scalar(op, data, start, stop, **kwargs):\n return data[start:stop]\n\n\n@execute_node.register(ops.ArrayIndex, pd.Series, int)\ndef execute_array_index(op, data, index, **kwargs):\n return data.apply(\n lambda array, index=index: (\n array[index] if -len(array) <= index < len(array) else None\n )\n )\n\n\n@execute_node.register(ops.ArrayIndex, np.ndarray, int)\ndef execute_array_index_scalar(op, data, index, **kwargs):\n try:\n return data[index]\n except IndexError:\n return None\n\n\ndef _concat_iterables_to_series(\n iter1: Collection[Any],\n iter2: Collection[Any],\n) -> pd.Series:\n \"\"\"Concatenate two collections elementwise (\"horizontally\") to create a\n Series. The two collections are assumed to have the same length.\n\n Used for ArrayConcat implementation.\n \"\"\"\n assert len(iter1) == len(iter2)\n # Doing the iteration using `map` is much faster than doing the iteration\n # using `Series.apply` due to Pandas-related overhead.\n result = pd.Series(map(lambda x, y: np.concatenate([x, y]), iter1, iter2))\n return result\n\n\n@execute_node.register(ops.ArrayConcat, pd.Series, pd.Series)\ndef execute_array_concat_series(op, left, right, **kwargs):\n return _concat_iterables_to_series(left, right)\n\n\n@execute_node.register(ops.ArrayConcat, pd.Series, np.ndarray)\n@execute_node.register(ops.ArrayConcat, np.ndarray, pd.Series)\ndef execute_array_concat_mixed(op, left, right, **kwargs):\n # ArrayConcat given a column (pd.Series) and a scalar (np.ndarray).\n # We will broadcast the scalar to the length of the column.\n if isinstance(left, np.ndarray):\n # Broadcast `left` to the length of `right`\n left = np.tile(left, (len(right), 1))\n elif isinstance(right, np.ndarray):\n # Broadcast `right` to the length of `left`\n right = np.tile(right, (len(left), 1))\n return _concat_iterables_to_series(left, right)\n\n\n@execute_node.register(ops.ArrayConcat, np.ndarray, np.ndarray)\ndef execute_array_concat_scalar(op, left, right, **kwargs):\n return np.concatenate([left, right])\n\n\n@execute_node.register(ops.ArrayRepeat, pd.Series, int)\ndef execute_array_repeat(op, data, n, **kwargs):\n # Negative n will be treated as 0 (repeat will produce empty array)\n n = max(n, 0)\n return pd.Series(\n map(\n lambda arr: np.tile(arr, n),\n data,\n )\n )\n\n\n@execute_node.register(ops.ArrayRepeat, np.ndarray, int)\ndef execute_array_repeat_scalar(op, data, n, **kwargs):\n # Negative n will be treated as 0 (repeat will produce empty array)\n return np.tile(data, max(n, 0))\n\n\n@execute_node.register(ops.ArrayCollect, (pd.Series, SeriesGroupBy))\ndef execute_array_collect(op, data, aggcontext=None, **kwargs):\n return aggcontext.agg(data, np.array)\n"
]
| [
[
"numpy.concatenate",
"numpy.array",
"numpy.tile",
"pandas.concat"
]
]
|
dustinvanstee/pytorch-retinanet | [
"d55564fa5aa490d32b659772865bcecf8e1d4c6d"
]
| [
"coco_eval.py"
]
| [
"from __future__ import print_function\n\nfrom pycocotools.coco import COCO\nfrom pycocotools.cocoeval import COCOeval\n\nimport numpy as np\nimport json\nimport os\n\nimport torch\n\ndef evaluate_coco(dataset, model, threshold=0.05, num_images=5000):\n \n model.eval()\n if(len(dataset) < num_images) :\n num_images = len(dataset)\n\n with torch.no_grad():\n\n # start collecting results\n results = []\n image_ids = []\n\n for index in range(num_images):\n data = dataset[index]\n scale = data['scale']\n\n # run network\n scores, labels, boxes = model(data['img'].permute(2, 0, 1).cuda().float().unsqueeze(dim=0))\n scores = scores.cpu()\n labels = labels.cpu()\n boxes = boxes.cpu()\n\n # correct boxes for image scale\n boxes /= scale\n\n if boxes.shape[0] > 0:\n # change to (x, y, w, h) (MS COCO standard)\n boxes[:, 2] -= boxes[:, 0]\n boxes[:, 3] -= boxes[:, 1]\n\n # compute predicted labels and scores\n #for box, score, label in zip(boxes[0], scores[0], labels[0]):\n for box_id in range(boxes.shape[0]):\n score = float(scores[box_id])\n label = int(labels[box_id])\n box = boxes[box_id, :]\n\n # scores are sorted, so we can break\n if score < threshold:\n break\n\n # append detection for each positively labeled class\n image_result = {\n 'image_id' : dataset.image_ids[index],\n 'category_id' : dataset.label_to_coco_label(label),\n 'score' : float(score),\n 'bbox' : box.tolist(),\n }\n\n # append detection to results\n results.append(image_result)\n\n # append image to list of processed images\n image_ids.append(dataset.image_ids[index])\n\n # print progress\n print('{}/{}'.format(index, len(dataset)), end='\\r')\n\n #if not len(results):\n # return\n\n # write output\n json.dump(results, open('{}_bbox_results.json'.format(dataset.set_name), 'w'), indent=4)\n\n # load results in COCO evaluation tool\n coco_true = dataset.coco\n coco_pred = coco_true.loadRes('{}_bbox_results.json'.format(dataset.set_name))\n\n # run COCO evaluation\n coco_eval = COCOeval(coco_true, coco_pred, 'bbox')\n coco_eval.params.imgIds = image_ids\n coco_eval.evaluate()\n coco_eval.accumulate()\n coco_eval.summarize()\n\n model.train()\n\n return\n"
]
| [
[
"torch.no_grad"
]
]
|
MahmoudMirMohammadRezaei/newsvendor | [
"3470eedc27c72c17d986a9e7e09d764d73446130"
]
| [
"data/generator/uniform/nw-simulation-1-class.py"
]
| [
"import scipy.io as sio\nimport numpy as np\nimport os\n\nimport sys\nimport h5py\nimport shutil\nimport tempfile\n\nimport sklearn\nimport sklearn.datasets\nimport sklearn.linear_model\n\nimport scipy.stats as stso\nnp.random.seed(seed=4)\n\nimport sys\na = int(sys.argv[0].split('-')[2])\n\n\nif a == 1:\n cluster=1\n total=260000\nelif a==10:\n cluster=10\n total=26000\nelif a==100:\n cluster=100\n total=2600\nelif a==200:\n cluster=200\n total=1300\n\n\n# Use all the SQL you like\nrandom_demand = np.random.randint(1, 21, total)\n\nbinary_day = []\nbinary_month = []\nbinary_department = []\n\nA = np.identity(7)\nfor i in range(7):\n binary_day += [A[i : i + 1]]\n\nA = np.identity(10)\nfor i in range(12):\n binary_month += [A[i : i + 1]]\n \nA = np.identity(24)\nfor i in range(24):\n binary_department += [A[i : i + 1]]\n\ninputs = []\nsuma = []\nindex = []\n\nfor row in random_demand:\n suma += [[round(row)]]\n inputs += [[1]]\n index += [[1,1,21]]\n #inputs += [np.concatenate((binary_day[day_of_week[row[3]] - 1] , binary_department[departments[row[9]] - 1]) , axis = 1)]\n #fGroup.write(str(binary_day[1]) + ',' + str(binary_department[1]) + ',' + str(binary_month[1]) + ',' + str(row) + '\\n') \n \n\n#inputs += [np.concatenate((binary_day[1] , binary_month[3]) , axis = 1)]\n#fGroup.close() \n\n#-------------------------------------------------------------------------------------------------------------------------\n\n# Split into train and test \nX, Xt, y, yt, ind, indt = sklearn.cross_validation.train_test_split(inputs, suma, index, train_size=7500)\n\nsio.savemat('/home/afo214/tensorflow/newsvendor/simulation/data/uniform/IndexX-nw-10000-1-class', mdict={'IndexX': ind})\nsio.savemat('/home/afo214/tensorflow/newsvendor/simulation/data/uniform/IndexY-nw-10000-1-class', mdict={'IndexY': indt})\n\nsio.savemat('/home/afo214/tensorflow/newsvendor/simulation/data/uniform/TrainX-nw-10000-1-class', mdict={'trainX': X})\nsio.savemat('/home/afo214/tensorflow/newsvendor/simulation/data/uniform/TrainY-nw-10000-1-class', mdict={'trainY': y})\nsio.savemat('/home/afo214/tensorflow/newsvendor/simulation/data/uniform/TestX-nw-10000-1-class', mdict={'testX': Xt})\nsio.savemat('/home/afo214/tensorflow/newsvendor/simulation/data/uniform/TestY-nw-10000-1-class', mdict={'testY': yt})\n\n\nTrainh5 = 'Train-nw-10000-1-class.h5'\nTraintxt = 'Train-nw-10000-1-class.txt'\nTesth5 = 'Test-nw-10000-1-class.h5'\nTesttxt = 'Test-nw-10000-1-class.txt'\n\n# Write out the data to HDF5 files in a temp directory. # This file is assumed to be caffe_root/examples/hdf5_classification.ipynb \ndirname = os.path.abspath('/home/afo214/tensorflow/newsvendor/simulation/data/hdf5')\nif not os.path.exists(dirname):\n os.makedirs(dirname)\n\ntrain_filename = os.path.join(dirname, Trainh5)\ntest_filename = os.path.join(dirname, Testh5)\n\n# HDF5DataLayer source should be a file containing a list of HDF5 filenames. \n# To show this off, we'll list the same data file twice. \nwith h5py.File(train_filename, 'w') as f:\n f['data'] = X\n f['label'] = y.astype(np.float32)\nwith open(os.path.join(dirname, Traintxt), 'w') as f:\n f.write(train_filename + '\\n')\n f.write(train_filename + '\\n')\n\n# HDF5 is pretty efficient, but can be further compressed. \n \ncomp_kwargs = {'compression': 'gzip', 'compression_opts': 1}\nwith h5py.File(test_filename, 'w') as f:\n train_filename = os.path.join(dirname, Trainh5)\n test_filename = os.path.join(dirname, Testh5)\n\n# HDF5DataLayer source should be a file containing a list of HDF5 filenames. \n# To show this off, we'll list the same data file twice. \nwith h5py.File(train_filename, 'w') as f:\n f['data'] = X\n f['label'] = y.astype(np.float32)\nwith open(os.path.join(dirname,Traintxt), 'w') as f:\n f.write(train_filename + '\\n')\n f.write(train_filename + '\\n')\n\n# HDF5 is pretty efficient, but can be further compressed. \ncomp_kwargs = {'compression': 'gzip', 'compression_opts': 1}\nwith h5py.File(test_filename, 'w') as f:\n f.create_dataset('data', data=Xt, **comp_kwargs)\n f.create_dataset('label', data=yt.astype(np.float32), **comp_kwargs)\nwith open(os.path.join(dirname, Testtxt), 'w') as f:\n f.write(test_filename + '\\n')\n\n"
]
| [
[
"numpy.random.seed",
"scipy.io.savemat",
"numpy.identity",
"numpy.random.randint",
"sklearn.cross_validation.train_test_split"
]
]
|
takafreak/tensorflow | [
"b85cb440e257a367fb70f8321ddaa669d1bd9fae"
]
| [
"tensorflow/python/autograph/utils/ag_logging.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\"\"\"Logging and debugging utilities.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\n\n# TODO(mdan): Use a custom logger class.\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util.tf_export import tf_export\n\nVERBOSITY_VAR_NAME = 'AUTOGRAPH_VERBOSITY'\nDEFAULT_VERBOSITY = 0\n\nverbosity_level = None # vlog-like. Takes precedence over the env variable.\necho_log_to_stdout = False\n\n# In interactive Python, logging echo is enabled by default.\nif hasattr(sys, 'ps1') or hasattr(sys, 'ps2'):\n echo_log_to_stdout = True\n\n\n@tf_export('autograph.set_verbosity')\ndef set_verbosity(level, alsologtostdout=False):\n \"\"\"Sets the AutoGraph verbosity level.\n\n _Debug logging in AutoGraph_\n\n More verbose logging is useful to enable when filing bug reports or doing\n more in-depth debugging.\n\n There are two controls that control the logging verbosity:\n\n * The `set_verbosity` function\n\n * The `AUTOGRAPH_VERBOSITY` environment variable\n\n `set_verbosity` takes precedence over the environment variable.\n\n For example:\n\n ```python\n import os\n import tensorflow as tf\n\n os.environ['AUTOGRAPH_VERBOSITY'] = 5\n # Verbosity is now 5\n\n tf.autograph.set_verbosity(0)\n # Verbosity is now 0\n\n os.environ['AUTOGRAPH_VERBOSITY'] = 1\n # No effect, because set_verbosity was already called.\n ```\n\n Logs entries are output to [absl](https://abseil.io)'s default output,\n with `INFO` level.\n Logs can be mirrored to stdout by using the `alsologtostdout` argument.\n Mirroring is enabled by default when Python runs in interactive mode.\n\n Args:\n level: int, the verbosity level; larger values specify increased verbosity;\n 0 means no logging. When reporting bugs, it is recommended to set this\n value to a larges number, like 10.\n alsologtostdout: bool, whether to also output log messages to `sys.stdout`.\n \"\"\"\n global verbosity_level\n global echo_log_to_stdout\n verbosity_level = level\n echo_log_to_stdout = alsologtostdout\n\n\n@tf_export('autograph.trace')\ndef trace(*args):\n \"\"\"Traces argument information at compilation time.\n\n `trace` is useful when debugging, and it always executes during the tracing\n phase, that is, when the TF graph is constructed.\n\n _Example usage_\n\n ```python\n import tensorflow as tf\n\n for i in tf.range(10):\n tf.autograph.trace(i)\n # Output: <Tensor ...>\n ```\n\n Args:\n *args: Arguments to print to `sys.stdout`.\n \"\"\"\n print(*args)\n\n\ndef get_verbosity():\n global verbosity_level\n if verbosity_level is not None:\n return verbosity_level\n return int(os.getenv(VERBOSITY_VAR_NAME, DEFAULT_VERBOSITY))\n\n\ndef has_verbosity(level):\n return get_verbosity() >= level\n\n\ndef error(level, msg, *args, **kwargs):\n if has_verbosity(level):\n logging.error(msg, *args, **kwargs)\n if echo_log_to_stdout:\n print(msg % args)\n\n\ndef log(level, msg, *args, **kwargs):\n if has_verbosity(level):\n logging.info(msg, *args, **kwargs)\n if echo_log_to_stdout:\n print(msg % args)\n\n\ndef warn(msg, *args, **kwargs):\n logging.warn(msg, *args, **kwargs)\n\n\ndef warn_first_n(msg, *args, **kwargs):\n logging.log_first_n(logging.WARN, msg, *args, **kwargs)\n"
]
| [
[
"tensorflow.python.platform.tf_logging.info",
"tensorflow.python.platform.tf_logging.log_first_n",
"tensorflow.python.platform.tf_logging.error",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.python.platform.tf_logging.warn"
]
]
|
jbaviation/dfs_golf | [
"0c59962441f4f2db99a1534361170e6b8378e06b"
]
| [
"pga_data/scrape.py"
]
| [
"import pandas as pd\nimport numpy as np\nimport datetime as dt\nimport pga_data.mapping as mapping\n\nclass stat:\n def __init__(self, stat='', from_id=False, season=dt.datetime.now().year, tournament=None, just_tournament=False):\n \"\"\"This class is setup to provide a means for someone to request a particular stat and then\n it returns the url from PGATour.com to access the data.\n args:\n stat (str) - statistics to retrieve\n from_id (str) - use stat as 'stat id' rather than 'stat name'\n season (datetime) - for specific seasons (NOT WORKED ON YET)\n tournament (str) - specify tournament if not whole season is desired\n just_tournament (bool) - True for only tournament data False for season upto tourney\n \"\"\"\n \n # Generate instance of necessary classes/variables\n self.from_id = from_id\n self.season = season\n self.tournament = tournament\n self.just_tournament = just_tournament\n self.meta = mapping.mapping()\n \n # Write necessary inputs to self (new way)\n self._stat = self._check_stat(stat)\n \n # Set url for initial class conditions\n self._set_url()\n\n\n def _check_stat(self, stat):\n \"\"\"Primary purpose is to confirm that tournament, or year requested exists in particular stat.\"\"\"\n check_stat = self.meta.list_stat(stat, self.from_id)\n \n # todo: confirm that year and tournament are available in the meta data\n return check_stat\n \n \n def _set_url(self):\n '''Function to be called whenever statistic, season, time period, or tournament \n has been changed. For now this function just accepts seasons and categories.'''\n\n # Find season to determine base_url\n this_year = dt.datetime.now().year # for now set this to be calendar year, eventually will be seasons\n if self.season == this_year:\n # Set url for current season\n base_url = 'https://www.pgatour.com/stats/stat.{}.html'\n self.url = base_url.format(self.stat['stat id'])\n else:\n # Set url for entire alternate season\n base_url = 'https://www.pgatour.com/content/pgatour/stats/stat.{}.y{}.html'\n self.url = base_url.format(self.stat['stat id'], self.season)\n \n \n @property\n def stat(self):\n # stat is now a dictionary\n return self._stat\n \n @stat.setter\n def stat(self, new_stat):\n # stat is now a dictionary\n self._stat = self._check_stat(new_stat)\n self._set_url()\n \n def pull(self):\n \"\"\"Function to pull data from pgatour.com and put into dataframe\"\"\"\n return pd.read_html(self.url)[1]\n \n\nclass player:\n pass\n\n"
]
| [
[
"pandas.read_html"
]
]
|
szmybs/GOES-R-2017-HurricaneExtraction | [
"2bacc7e035183d89448835e30947f639cff2776c"
]
| [
"scale.py"
]
| [
"import numpy as np\nimport os\nfrom hurricane_generator import HurricaneGenerator\nfrom extract import HurricaneExtraction\n\nclass FixedScale(object):\n def __init__(self):\n pass\n \n @classmethod\n def goes_conv2d(self, x, kernel_size):\n if (x.shape[0] != x.shape[1]) or x.shape[0] % kernel_size !=0:\n return\n\n stride = kernel_size\n x = x / kernel_size\n\n y_shape = ( int(x.shape[0] / kernel_size), int(x.shape[0] / kernel_size) )\n y = np.zeros(y_shape, dtype = np.float32)\n\n for i in range(y_shape[0]):\n for j in range(y_shape[1]):\n x_start = i * stride\n y_start = j * stride\n y[i, j] = np.sum( x[x_start : x_start+stride, y_start : y_start+stride] )\n \n return y\n\n @classmethod\n def scale_to_fixed_size(self, x, fixed_size):\n nx = []\n for i in x:\n times = int(i.shape[0] / fixed_size)\n if times <= 1:\n nx.append(i)\n else:\n nx.append( self.goes_conv2d(i, times) )\n return nx \n\n\n# name - visibility - date\ndef goes16_5channels_scale_dir(root_path, save_path, read_data_func):\n name_dirs = HurricaneGenerator.directory_downstream(root_path)\n\n for name_dir in name_dirs:\n visibility_dirs = HurricaneGenerator.directory_downstream(name_dir)\n\n for visibility_dir in visibility_dirs:\n date_dirs = HurricaneGenerator.directory_downstream(visibility_dir)\n\n for date_dir in date_dirs:\n new_path = os.path.relpath(path=date_dir, start=root_path)\n new_path = os.path.join(save_path, new_path)\n if os.path.exists(new_path) == False:\n os.makedirs(new_path)\n\n data_list = sorted(os.listdir(date_dir))\n for df in data_list:\n if os.path.isfile == False:\n continue\n dp = os.path.join(date_dir, df)\n d = read_data_func(dp)\n #d = HurricaneExtraction.convert_unsigned_to_float(d)\n dfs = FixedScale.scale_to_fixed_size(d, 256)\n dfs = (np.asarray(dfs)).astype(np.uint16)\n\n file_save_loc = os.path.join(new_path, os.path.splitext(df)[0])\n np.save(file_save_loc, dfs)\n print(\"save to %s\" % (file_save_loc))\n\n\n\nif __name__ == \"__main__\":\n root_path = \"./Data/NpyData/\"\n save_path = \"./Data/ScaledData/\"\n\n goes16_5channels_scale_dir(root_path, save_path, HurricaneExtraction.read_extraction_data)\n\n "
]
| [
[
"numpy.sum",
"numpy.save",
"numpy.asarray",
"numpy.zeros"
]
]
|
hvhue/pymor | [
"0815d74514fa5c4e0ad6f379f29abdd7d067cedd",
"0815d74514fa5c4e0ad6f379f29abdd7d067cedd"
]
| [
"src/pymor/reductors/residual.py",
"src/pymor/algorithms/eigs.py"
]
| [
"# This file is part of the pyMOR project (http://www.pymor.org).\n# Copyright 2013-2020 pyMOR developers and contributors. All rights reserved.\n# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\nimport numpy as np\n\nfrom pymor.algorithms.image import estimate_image_hierarchical\nfrom pymor.algorithms.projection import project, project_to_subbasis\nfrom pymor.core.base import BasicObject\nfrom pymor.core.exceptions import ImageCollectionError\nfrom pymor.operators.constructions import ZeroOperator\nfrom pymor.operators.interface import Operator\n\n\nclass ResidualReductor(BasicObject):\n \"\"\"Generic reduced basis residual reductor.\n\n Given an operator and a right-hand side, the residual is given by::\n\n residual.apply(U, mu) == operator.apply(U, mu) - rhs.as_range_array(mu)\n\n When operator maps to functionals instead of vectors, we are interested in the Riesz\n representative of the residual::\n\n residual.apply(U, mu)\n == product.apply_inverse(operator.apply(U, mu) - rhs.as_range_array(mu))\n\n Given a basis `RB` of a subspace of the source space of `operator`, this reductor\n uses :func:`~pymor.algorithms.image.estimate_image_hierarchical` to determine\n a low-dimensional subspace containing the image of the subspace under\n `residual` (resp. `riesz_residual`), computes an orthonormal basis\n `residual_range` for this range space and then returns the Petrov-Galerkin projection ::\n\n projected_residual\n == project(residual, range_basis=residual_range, source_basis=RB)\n\n of the residual operator. Given a reduced basis coefficient vector `u`, w.r.t.\n `RB`, the (dual) norm of the residual can then be computed as ::\n\n projected_residual.apply(u, mu).norm()\n\n Moreover, a `reconstruct` method is provided such that ::\n\n residual_reductor.reconstruct(projected_residual.apply(u, mu))\n == residual.apply(RB.lincomb(u), mu)\n\n Parameters\n ----------\n RB\n |VectorArray| containing a basis of the reduced space onto which to project.\n operator\n See definition of `residual`.\n rhs\n See definition of `residual`. If `None`, zero right-hand side is assumed.\n product\n Inner product |Operator| w.r.t. which to orthonormalize and w.r.t. which to\n compute the Riesz representatives in case `operator` maps to functionals.\n riesz_representatives\n If `True` compute the Riesz representative of the residual.\n \"\"\"\n\n def __init__(self, RB, operator, rhs=None, product=None, riesz_representatives=False):\n assert RB in operator.source\n assert rhs is None \\\n or (rhs.source.is_scalar and rhs.range == operator.range and rhs.linear)\n assert product is None or product.source == product.range == operator.range\n\n self.__auto_init(locals())\n self.residual_range = operator.range.empty()\n self.residual_range_dims = []\n\n def reduce(self):\n if self.residual_range is not False:\n with self.logger.block('Estimating residual range ...'):\n try:\n self.residual_range, self.residual_range_dims = \\\n estimate_image_hierarchical([self.operator], [self.rhs],\n self.RB,\n (self.residual_range, self.residual_range_dims),\n orthonormalize=True, product=self.product,\n riesz_representatives=self.riesz_representatives)\n except ImageCollectionError as e:\n self.logger.warning(f'Cannot compute range of {e.op}. Evaluation will be slow.')\n self.residual_range = False\n\n if self.residual_range is False:\n operator = project(self.operator, None, self.RB)\n return NonProjectedResidualOperator(operator, self.rhs, self.riesz_representatives, self.product)\n\n with self.logger.block('Projecting residual operator ...'):\n if self.riesz_representatives:\n operator = project(self.operator, self.residual_range, self.RB, product=None) # the product cancels out\n rhs = project(self.rhs, self.residual_range, None, product=None)\n else:\n operator = project(self.operator, self.residual_range, self.RB, product=self.product)\n rhs = project(self.rhs, self.residual_range, None, product=self.product)\n\n return ResidualOperator(operator, rhs)\n\n def reconstruct(self, u):\n \"\"\"Reconstruct high-dimensional residual vector from reduced vector `u`.\"\"\"\n if self.residual_range is False:\n if self.product:\n return u * (u.norm() / u.norm(self.product))[0]\n else:\n return u\n else:\n return self.residual_range[:u.dim].lincomb(u.to_numpy())\n\n\nclass ResidualOperator(Operator):\n \"\"\"Instantiated by :class:`ResidualReductor`.\"\"\"\n\n def __init__(self, operator, rhs, name=None):\n self.__auto_init(locals())\n self.source = operator.source\n self.range = operator.range\n self.linear = operator.linear\n self.rhs_vector = rhs.as_range_array() if rhs and not rhs.parametric else None\n\n def apply(self, U, mu=None):\n V = self.operator.apply(U, mu=mu)\n if self.rhs:\n F = self.rhs_vector or self.rhs.as_range_array(mu)\n if len(V) > 1:\n V -= F[[0]*len(V)]\n else:\n V -= F\n return V\n\n def projected_to_subbasis(self, dim_range=None, dim_source=None, name=None):\n return ResidualOperator(project_to_subbasis(self.operator, dim_range, dim_source),\n project_to_subbasis(self.rhs, dim_range, None),\n name=name)\n\n\nclass NonProjectedResidualOperator(ResidualOperator):\n \"\"\"Instantiated by :class:`ResidualReductor`.\n\n Not to be used directly.\n \"\"\"\n\n def __init__(self, operator, rhs, riesz_representatives, product):\n super().__init__(operator, rhs)\n self.__auto_init(locals())\n\n def apply(self, U, mu=None):\n R = super().apply(U, mu=mu)\n if self.product:\n if self.riesz_representatives:\n R_riesz = self.product.apply_inverse(R)\n # divide by norm, except when norm is zero:\n inversel2 = 1./R_riesz.norm()\n inversel2 = np.nan_to_num(inversel2)\n R_riesz.scal(np.sqrt(R_riesz.pairwise_inner(R)) * inversel2)\n return R_riesz\n else:\n # divide by norm, except when norm is zero:\n inversel2 = 1./R.norm()\n inversel2 = np.nan_to_num(inversel2)\n R.scal(np.sqrt(self.product.pairwise_apply2(R, R)) * inversel2)\n return R\n else:\n return R\n\n def projected_to_subbasis(self, dim_range=None, dim_source=None, name=None):\n return self.with_(operator=project_to_subbasis(self.operator, None, dim_source))\n\n\nclass ImplicitEulerResidualReductor(BasicObject):\n \"\"\"Reduced basis residual reductor with mass operator for implicit Euler timestepping.\n\n Given an operator, mass and a functional, the concatenation of residual operator\n with the Riesz isomorphism is given by::\n\n riesz_residual.apply(U, U_old, mu)\n == product.apply_inverse(operator.apply(U, mu) + 1/dt*mass.apply(U, mu)\n - 1/dt*mass.apply(U_old, mu) - rhs.as_vector(mu))\n\n This reductor determines a low-dimensional subspace of the image of a reduced basis space under\n `riesz_residual` using :func:`~pymor.algorithms.image.estimate_image_hierarchical`, computes an\n orthonormal basis `residual_range` of this range space and then returns the Petrov-Galerkin\n projection ::\n\n projected_riesz_residual\n == riesz_residual.projected(range_basis=residual_range, source_basis=RB)\n\n of the `riesz_residual` operator. Given reduced basis coefficient vectors `u` and `u_old`,\n the dual norm of the residual can then be computed as ::\n\n projected_riesz_residual.apply(u, u_old, mu).norm()\n\n Moreover, a `reconstruct` method is provided such that ::\n\n residual_reductor.reconstruct(projected_riesz_residual.apply(u, u_old, mu))\n == riesz_residual.apply(RB.lincomb(u), RB.lincomb(u_old), mu)\n\n Parameters\n ----------\n operator\n See definition of `riesz_residual`.\n mass\n The mass operator. See definition of `riesz_residual`.\n dt\n The time step size. See definition of `riesz_residual`.\n rhs\n See definition of `riesz_residual`. If `None`, zero right-hand side is assumed.\n RB\n |VectorArray| containing a basis of the reduced space onto which to project.\n product\n Inner product |Operator| w.r.t. which to compute the Riesz representatives.\n \"\"\"\n\n def __init__(self, RB, operator, mass, dt, rhs=None, product=None):\n assert RB in operator.source\n assert rhs.source.is_scalar and rhs.range == operator.range and rhs.linear\n assert product is None or product.source == product.range == operator.range\n\n self.__auto_init(locals())\n self.residual_range = operator.range.empty()\n self.residual_range_dims = []\n\n def reduce(self):\n if self.residual_range is not False:\n with self.logger.block('Estimating residual range ...'):\n try:\n self.residual_range, self.residual_range_dims = \\\n estimate_image_hierarchical([self.operator, self.mass], [self.rhs],\n self.RB,\n (self.residual_range, self.residual_range_dims),\n orthonormalize=True, product=self.product,\n riesz_representatives=True)\n except ImageCollectionError as e:\n self.logger.warning(f'Cannot compute range of {e.op}. Evaluation will be slow.')\n self.residual_range = False\n\n if self.residual_range is False:\n operator = project(self.operator, None, self.RB)\n mass = project(self.mass, None, self.RB)\n return NonProjectedImplicitEulerResidualOperator(operator, mass, self.rhs, self.dt, self.product)\n\n with self.logger.block('Projecting residual operator ...'):\n # the product always cancels out\n operator = project(self.operator, self.residual_range, self.RB, product=None)\n mass = project(self.mass, self.residual_range, self.RB, product=None)\n rhs = project(self.rhs, self.residual_range, None, product=None)\n\n return ImplicitEulerResidualOperator(operator, mass, rhs, self.dt)\n\n def reconstruct(self, u):\n \"\"\"Reconstruct high-dimensional residual vector from reduced vector `u`.\"\"\"\n if self.residual_range is False:\n if self.product:\n return u * (u.norm() / u.norm(self.product))[0]\n else:\n return u\n else:\n return self.residual_range[:u.dim].lincomb(u.to_numpy())\n\n\nclass ImplicitEulerResidualOperator(Operator):\n \"\"\"Instantiated by :class:`ImplicitEulerResidualReductor`.\"\"\"\n\n def __init__(self, operator, mass, rhs, dt, name=None):\n self.__auto_init(locals())\n self.source = operator.source\n self.range = operator.range\n self.linear = operator.linear\n self.rhs_vector = rhs.as_range_array() if not rhs.parametric else None\n\n def apply(self, U, U_old, mu=None):\n V = self.operator.apply(U, mu=mu)\n V.axpy(1./self.dt, self.mass.apply(U, mu=mu))\n V.axpy(-1./self.dt, self.mass.apply(U_old, mu=mu))\n if not isinstance(self.rhs, ZeroOperator):\n F = self.rhs_vector or self.rhs.as_range_array(mu)\n if len(V) > 1:\n V -= F[[0]*len(V)]\n else:\n V -= F\n return V\n\n def projected_to_subbasis(self, dim_range=None, dim_source=None, name=None):\n return ImplicitEulerResidualOperator(project_to_subbasis(self.operator, dim_range, dim_source),\n project_to_subbasis(self.mass, dim_range, dim_source),\n project_to_subbasis(self.rhs, dim_range, None),\n self.dt,\n name=name)\n\n\nclass NonProjectedImplicitEulerResidualOperator(ImplicitEulerResidualOperator):\n \"\"\"Instantiated by :class:`ImplicitEulerResidualReductor`.\n\n Not to be used directly.\n \"\"\"\n\n def __init__(self, operator, mass, rhs, dt, product):\n super().__init__(operator, mass, rhs, dt)\n self.product = product\n\n def apply(self, U, U_old, mu=None):\n R = super().apply(U, U_old, mu=mu)\n if self.product:\n R_riesz = self.product.apply_inverse(R)\n # divide by norm, except when norm is zero:\n inversel2 = 1./R_riesz.norm()\n inversel2 = np.nan_to_num(inversel2)\n R_riesz.scal(np.sqrt(R_riesz.pairwise_inner(R)) * inversel2)\n return R_riesz\n else:\n return R\n\n def projected_to_subbasis(self, dim_range=None, dim_source=None, name=None):\n return self.with_(operator=project_to_subbasis(self.operator, None, dim_source),\n mass=project_to_subbasis(self.mass, None, dim_source))\n",
"# This file is part of the pyMOR project (http://www.pymor.org).\n# Copyright 2013-2020 pyMOR developers and contributors. All rights reserved.\n# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\nimport numpy as np\nimport scipy.linalg as spla\n\nfrom pymor.algorithms.gram_schmidt import gram_schmidt\nfrom pymor.core.logger import getLogger\nfrom pymor.operators.constructions import IdentityOperator\nfrom pymor.operators.interface import Operator\n\n\ndef eigs(A, E=None, k=3, which='LM', b=None, l=None, maxiter=1000, tol=1e-13,\n imag_tol=1e-12, complex_pair_tol=1e-12, seed=0):\n \"\"\"Approximate a few eigenvalues of a linear |Operator|.\n\n Computes `k` eigenvalues `w` with corresponding eigenvectors `v` which solve\n the eigenvalue problem\n\n .. math::\n A v_i = w_i v_i\n\n or the generalized eigenvalue problem\n\n .. math::\n A v_i = w_i E v_i\n\n if `E` is not `None`.\n\n The implementation is based on Algorithm 4.2 in :cite:`RL95`.\n\n Parameters\n ----------\n A\n The real linear |Operator| for which the eigenvalues are to be computed.\n E\n The real linear |Operator| which defines the generalized eigenvalue problem.\n k\n The number of eigenvalues and eigenvectors which are to be computed.\n which\n A string specifying which `k` eigenvalues and eigenvectors to compute:\n\n - `'LM'`: select eigenvalues with largest magnitude\n - `'SM'`: select eigenvalues with smallest magnitude\n - `'LR'`: select eigenvalues with largest real part\n - `'SR'`: select eigenvalues with smallest real part\n - `'LI'`: select eigenvalues with largest imaginary part\n - `'SI'`: select eigenvalues with smallest imaginary part\n b\n Initial vector for Arnoldi iteration. Default is a random vector.\n l\n The size of the Arnoldi factorization. Default is `min(n - 1, max(2*k + 1, 20))`.\n maxiter\n The maximum number of iterations.\n tol\n The relative error tolerance for the Ritz estimates.\n imag_tol\n Relative imaginary parts below this tolerance are set to 0.\n complex_pair_tol\n Tolerance for detecting pairs of complex conjugate eigenvalues.\n seed\n Random seed which is used for computing the initial vector for the Arnoldi\n iteration.\n\n Returns\n -------\n w\n A 1D |NumPy array| which contains the computed eigenvalues.\n v\n A |VectorArray| which contains the computed eigenvectors.\n \"\"\"\n logger = getLogger('pymor.algorithms.eigs.eigs')\n\n assert isinstance(A, Operator) and A.linear\n assert not A.parametric\n assert A.source == A.range\n\n if E is None:\n E = IdentityOperator(A.source)\n else:\n assert isinstance(E, Operator) and E.linear\n assert not E.parametric\n assert E.source == E.range\n assert E.source == A.source\n\n if b is None:\n b = A.source.random(seed=seed)\n else:\n assert b in A.source\n\n n = A.source.dim\n l_min = 20\n\n if l is None:\n l = min(n - 1, max(2 * k + 1, l_min))\n\n assert k < n\n assert l > k\n\n V, H, f = _arnoldi(A, E, k, b)\n k0 = k\n i = 0\n\n while True:\n i += 1\n\n V, H, f = _extend_arnoldi(A, E, V, H, f, l - k)\n\n ew, ev = spla.eig(H)\n\n # truncate small imaginary parts\n ew.imag[np.abs(ew.imag) / np.abs(ew) < imag_tol] = 0\n\n if which == 'LM':\n idx = np.argsort(-np.abs(ew))\n elif which == 'SM':\n idx = np.argsort(np.abs(ew))\n elif which == 'LR':\n idx = np.argsort(-ew.real)\n elif which == 'SR':\n idx = np.argsort(ew.real)\n elif which == 'LI':\n idx = np.argsort(-np.abs(ew.imag))\n elif which == 'SI':\n idx = np.argsort(np.abs(ew.imag))\n\n k = k0\n ews = ew[idx]\n evs = ev[:, idx]\n\n rres = f.norm()[0] * np.abs(evs[l - 1]) / np.abs(ews)\n\n # increase k by one in order to keep complex conjugate pairs together\n if ews[k - 1].imag != 0 and ews[k - 1].imag + ews[k].imag < complex_pair_tol:\n k += 1\n\n logger.info(f'Maximum of relative Ritz estimates at step {i}: {rres[:k].max():.5e}')\n\n if np.all(rres[:k] <= tol) or i >= maxiter:\n break\n\n # increase k in order to prevent stagnation\n k = min(l - 1, k + min(np.count_nonzero(rres[:k] <= tol), (l - k) // 2))\n\n # sort shifts for QR iteration based on their residual\n shifts = ews[k:l]\n srres = rres[k:l]\n idx = np.argsort(-srres)\n srres = srres[idx]\n shifts = shifts[idx]\n\n # don't use converged unwanted Ritz values as shifts\n shifts = shifts[srres != 0]\n k += np.count_nonzero(srres == 0)\n if shifts[0].imag != 0 and shifts[0].imag + ews[1].imag >= complex_pair_tol:\n shifts = shifts[1:]\n k += 1\n\n H, Qs = _qr_iteration(H, shifts)\n\n V = V.lincomb(Qs.T)\n f = V[k] * H[k, k - 1] + f * Qs[l - 1, k - 1]\n V = V[:k]\n H = H[:k, :k]\n\n return ews[:k0], V.lincomb(evs[:, :k0].T)\n\n\ndef _arnoldi(A, E, l, b):\n \"\"\"Compute an Arnoldi factorization.\"\"\"\n v = b * (1 / b.norm()[0])\n\n H = np.zeros((l, l))\n V = A.source.empty(reserve=l)\n\n V.append(v)\n\n for i in range(l):\n v = E.apply_inverse(A.apply(v))\n V.append(v)\n\n _, R = gram_schmidt(V, return_R=True, atol=0, rtol=0, offset=len(V) - 1, copy=False)\n H[:i + 2, i] = R[:l, i + 1]\n v = V[-1]\n\n return V[:l], H, v * R[l, l]\n\n\ndef _extend_arnoldi(A, E, V, H, f, p):\n \"\"\"Extend an existing Arnoldi factorization.\"\"\"\n k = len(V)\n\n res = f.norm()[0]\n H = np.pad(H, ((0, p), (0, p)))\n H[k, k - 1] = res\n v = f * (1 / res)\n V = V.copy()\n V.append(v)\n\n for i in range(k, k + p):\n v = E.apply_inverse(A.apply(v))\n V.append(v)\n\n _, R = gram_schmidt(V, return_R=True, atol=0, rtol=0, offset=len(V) - 1, copy=False)\n H[:i + 2, i] = R[:k + p, i + 1]\n\n v = V[-1]\n\n return V[:k + p], H, v * R[k + p, k + p]\n\n\ndef _qr_iteration(H, shifts):\n \"\"\"Perform the QR iteration.\"\"\"\n Qs = np.eye(len(H))\n\n i = 0\n while i < len(shifts) - 1:\n s = shifts[i]\n if shifts[i].imag != 0:\n Q, _ = np.linalg.qr(H @ H - 2 * s.real * H + np.abs(s)**2 * np.eye(len(H)))\n i += 2\n else:\n Q, _ = np.linalg.qr(H - s * np.eye(len(H)))\n i += 1\n Qs = Qs @ Q\n H = Q.T @ H @ Q\n\n return H, Qs\n"
]
| [
[
"numpy.nan_to_num"
],
[
"numpy.pad",
"numpy.count_nonzero",
"numpy.zeros",
"scipy.linalg.eig",
"numpy.argsort",
"numpy.abs",
"numpy.all"
]
]
|
siej88/FuzzyACO | [
"989a58049c8417cd023cfc312fb99d2649333ca7"
]
| [
"FuzzyMachine.py"
]
| [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nUNIVERSIDAD DE CONCEPCION\r\nDepartamento de Ingenieria Informatica y\r\nCiencias de la Computacion\r\n\r\nMemoria de Titulo Ingenieria Civil Informatica\r\nDETECCION DE BORDES EN IMAGENES DGGE USANDO UN\r\nSISTEMA HIBRIDO ACO CON LOGICA DIFUSA\r\n\r\nAutor: Sebastian Ignacio Espinoza Jimenez\r\nPatrocinante: Maria Angelica Pinninghoff Junemann\r\n\"\"\"\r\n\r\nimport numpy as N\r\nimport MathTools as mat\r\n\r\nclass FuzzyMachine(object):\r\n \"\"\"Mamdani-Type Fuzzy Inference Engine\"\"\"\r\n \r\n def __init__(self):\r\n \"\"\"FuzzyMachine FuzzyMachine()\"\"\"\r\n self._heuristicMatrix = None\r\n self._imageFlag = False\r\n self._mathTools = mat.MathTools()\r\n\r\n def hasHeuristicMatrix(self):\r\n \"\"\"bool hasHeuristicMatrix()\"\"\"\r\n return self._imageFlag\r\n\r\n def getHeuristicMatrix(self):\r\n \"\"\"numpy.array getHeuristicMatrix()\"\"\"\r\n return N.copy(self._heuristicMatrix)\r\n\r\n def generateHeuristicMatrix(self, intensityMatrix, categorySet, parameterSet, ruleList):\r\n \"\"\"numpy.array generateHeuristicMatrix(numpy.array intensityMatrix,\r\n dict categorySet, dict parameterSet, list ruleSet)\"\"\"\r\n deFuzzificationMode = parameterSet['deFuzzificationMode']\r\n variableMatrixSet = self._generateVariableMatrixSet(intensityMatrix)\r\n deFuzzifierAggregator = {}\r\n categoryKeys = categorySet.keys()\r\n for k in categoryKeys:\r\n if categorySet[k]['variable'] == 'edge':\r\n deFuzzifierAggregator[k] = []\r\n ruleCount = len(ruleList)\r\n for i in xrange(ruleCount):\r\n categoryCount = len(ruleList[i])\r\n minimumMatrixList = []\r\n edgeCategory = ''\r\n for j in xrange(categoryCount):\r\n category = ruleList[i][j]\r\n variable = categorySet[category]['variable']\r\n if variable != 'edge':\r\n mean = categorySet[category]['mean']\r\n scale = categorySet[category]['scale']\r\n minimumMatrixList.append(self._mathTools.gaussian(variableMatrixSet[variable], mean, scale))\r\n else:\r\n edgeCategory = category\r\n minimumMatrix = self._mathTools.minimum(minimumMatrixList)\r\n deFuzzifierAggregator[edgeCategory].append(minimumMatrix)\r\n maximumMatrixSet = {}\r\n maximumMatrixList = []\r\n edgeCategoryKeys = deFuzzifierAggregator.keys()\r\n for k in edgeCategoryKeys:\r\n if len(deFuzzifierAggregator[k]) > 0:\r\n maximumMatrixSet[k] = self._mathTools.maximum(deFuzzifierAggregator[k])\r\n maximumMatrixList.append(maximumMatrixSet[k])\r\n maximumValues = self._mathTools.maximum(maximumMatrixList)\r\n heuristicMatrix = N.zeros_like(intensityMatrix)\r\n edgeCategoryKeys = maximumMatrixSet.keys()\r\n if deFuzzificationMode != 2:\r\n for k in edgeCategoryKeys:\r\n indexes = N.where(maximumValues == maximumMatrixSet[k])\r\n values = maximumMatrixSet[k][indexes]\r\n values[N.where(values == 0)] = 1e-10\r\n mean = categorySet[k]['mean']\r\n scale = categorySet[k]['scale']\r\n heuristicMatrix[indexes] = self._mathTools.inverseGaussian(values, mean, scale, deFuzzificationMode)\r\n else:\r\n summationMatrix = N.zeros_like(intensityMatrix)\r\n for k in edgeCategoryKeys: \r\n mean = categorySet[k]['mean']\r\n scale = categorySet[k]['scale']\r\n heuristicMatrix += maximumMatrixSet[k] * mean * scale\r\n summationMatrix += maximumMatrixSet[k] * scale\r\n summationMatrix[N.where(summationMatrix == 0)] = 1e-10\r\n heuristicMatrix /= summationMatrix\r\n heuristicMatrix *= self._mathTools.standardDeviation(intensityMatrix)\r\n heuristicMatrix = self._mathTools.normalize(heuristicMatrix)\r\n self._heuristicMatrix = N.copy(heuristicMatrix)\r\n self._imageFlag = True\r\n return heuristicMatrix\r\n \r\n def _generateVariableMatrixSet(self, intensityMatrix):\r\n \"\"\"dict _generateFuzzyVariableMatrices(numpy.array intensityMatrix)\"\"\"\r\n variableMatrix = {}\r\n convolutionMask = {} \r\n convolutionMask['mRow'] = N.array([[1,1,1],[-2,-2,-2],[1,1,1]])/3.\r\n convolutionMask['mCol'] = N.array([[1,-2,1],[1,-2,1],[1,-2,1]])/3.\r\n convolutionMask['iDiag'] = N.array([[1,1,1],[1,-8,1],[1,1,1]]) \r\n for v in convolutionMask.keys():\r\n variableMatrix[v] = N.abs(self._mathTools.convolve(intensityMatrix, convolutionMask[v]))\r\n return variableMatrix"
]
| [
[
"numpy.zeros_like",
"numpy.array",
"numpy.copy",
"numpy.where"
]
]
|
ftshijt/Muskits | [
"f85ce2a0b35881c2f9d9072217a54121a25b935d"
]
| [
"muskit/fileio/utils.py"
]
| [
"import miditoolkit\nimport numpy as np\n\n\ndef get_tick_to_time_mapping(ticks_per_beat, tempo_changes, max_tick=np.int32(1e6)):\n \"\"\"\n Get mapping from ticks to seconds with tempo information\n \"\"\"\n tick_to_time = np.zeros(max_tick + 1)\n num_tempi = len(tempo_changes)\n\n fianl_tick = max_tick\n acc_time = 0\n\n for idx in range(num_tempi):\n start_tick = tempo_changes[idx].time\n cur_tempo = int(tempo_changes[idx].tempo)\n\n # compute tick scale\n seconds_per_beat = 60 / cur_tempo\n seconds_per_tick = seconds_per_beat / float(ticks_per_beat)\n\n # set end tick of interval\n end_tick = tempo_changes[idx + 1].time if (idx + 1) < num_tempi else fianl_tick\n\n # wrtie interval\n ticks = np.arange(end_tick - start_tick + 1)\n tick_to_time[start_tick : end_tick + 1] = acc_time + seconds_per_tick * ticks\n acc_time = tick_to_time[end_tick]\n return tick_to_time\n\n\ndef midi_to_seq(midi_obj, dtype=np.int16, rate=22050, pitch_aug_factor=0, time_aug_factor=1):\n \"\"\"method for midi_obj.\n Input:\n miditoolkit_object, sampling rate\n Output:\n note_seq: np.array([pitch1,pitch2....]), which length is equal to note.time*rate\n tempo_seq:np.array([pitch1,pitch2....]), which length is equal to note.time*rate\n \"\"\"\n tick_to_time = midi_obj.get_tick_to_time_mapping()\n max_time = tick_to_time[-1]\n notes = midi_obj.instruments[0].notes\n notes.sort(key=lambda x: (x.start, x.pitch))\n\n tempos = midi_obj.tempo_changes\n tempos.sort(key=lambda x: (x.time, x.tempo))\n assert len(tempos) == 1\n tempo_BPM = tempos[0].tempo # global information, beats per minute\n tempo_BPS = tempo_BPM / 60.0 # global information, beats per second\n\n note_seq = np.zeros(int(rate * max_time * time_aug_factor), dtype=dtype)\n tempo_seq = np.zeros(int(rate * max_time * time_aug_factor), dtype=dtype)\n for i in range(len(notes)):\n st = int(tick_to_time[notes[i].start] * rate * time_aug_factor)\n ed = int(tick_to_time[notes[i].end] * rate * time_aug_factor)\n note_seq[st:ed] = notes[i].pitch if (pitch_aug_factor == 0 or notes[i].pitch == 0) else (notes[i].pitch + pitch_aug_factor)\n\n st_time = tick_to_time[notes[i].start] * time_aug_factor\n ed_time = tick_to_time[notes[i].end] * time_aug_factor\n note_duration = ed_time - st_time # Beats in seconds\n beat_num = note_duration * tempo_BPS # Beats nums in note\n beat_input = int(beat_num / 0.0125 + 0.5)\n tempo_seq[st:ed] = beat_input\n\n return note_seq, tempo_seq\n\n\ndef seq_to_midi(\n note_seq,\n tempo_seq,\n rate=24000,\n DEFAULT_RESOLUTION=960,\n DEFAULT_TEMPO=120,\n DEFAULT_VELOCITY=64,\n):\n \"\"\"method for note_seq.\n Input:\n note_seq, tempo_seq, sampling rate\n Output:\n miditoolkit_object with default resolution, tempo and velocity.\n \"\"\"\n # get downbeat and note (no time)\n temp_notes = note_seq\n temp_tempos = tempo_seq\n ticks_per_beat = DEFAULT_RESOLUTION\n\n # get specific time for tempos\n tempos = []\n i = 0\n last_i = 0\n # acc_time = 0\n acc_tick = 0\n while i < len(temp_tempos):\n bpm = temp_tempos[i]\n ticks_per_second = DEFAULT_RESOLUTION * bpm / 60\n j = i\n while j + 1 < len(temp_tempos) and temp_tempos[j + 1] == bpm:\n j += 1\n if bpm == 0:\n bpm = DEFAULT_TEMPO\n tempos.append(miditoolkit.midi.containers.TempoChange(bpm, acc_tick))\n acc_tick += int((j - last_i + 1) * ticks_per_second / rate)\n\n last_i = j\n i = j + 1\n tick_to_time = get_tick_to_time_mapping(ticks_per_beat, tempos)\n\n # get specific time for notes\n notes = []\n i = 0\n while i < len(temp_notes):\n pitch = temp_notes[i]\n j = i\n while j + 1 < len(temp_notes) and temp_notes[j + 1] == pitch:\n j += 1\n st = i / rate\n ed = j / rate\n\n start = np.searchsorted(tick_to_time, st, \"left\")\n end = np.searchsorted(tick_to_time, ed, \"left\")\n if pitch > 0 and pitch <= 128:\n notes.append(\n miditoolkit.midi.containers.Note(\n start=start, end=end, pitch=pitch, velocity=DEFAULT_VELOCITY\n )\n )\n\n i = j + 1\n\n # write\n midi = miditoolkit.midi.parser.MidiFile()\n midi.ticks_per_beat = DEFAULT_RESOLUTION\n # write instrument\n inst = miditoolkit.midi.containers.Instrument(0, is_drum=False)\n inst.notes = notes\n midi.instruments.append(inst)\n # write tempo\n midi.tempo_changes = tempos\n return midi\n\n\nif __name__ == \"__main__\":\n import os\n\n # paths = os.listdir(\n # \"/data3/qt/Muskits/egs/kiritan/svs1/dump/raw/org/train/data/format_midi.18/\"\n # )\n # # print(paths)\n # for p in paths:\n # # path = '/data3/qt/Muskits/egs/kiritan/svs1/dump/raw/org/train/data/format_midi.18/kiritan11_0001.midi'\n # path = (\n # \"/data3/qt/Muskits/egs/kiritan/svs1/dump/raw/org/train/data/format_midi.18/\"\n # + p\n # )\n # print(path)\n # midi_obj = miditoolkit.midi.parser.MidiFile(path)\n # note_seq, tempo_seq = midi_to_seq(midi_obj, np.int16, np.int16(16000))\n # midi_obj = seq_to_midi(note_seq, tempo_seq, np.int16(16000))\n # midi_path = \"/data3/qt/songmass/output_res_prev/midiscp.mid\"\n # midi_obj.dump(midi_path) \n\n import miditoolkit\n path = \"/data5/gs/Muskits/egs/ofuton_p_utagoe_db/svs1/dump/raw/org/dev/data/format_midi.1/oniku_00000000000000momiji_0000.midi\"\n midi_obj = miditoolkit.midi.parser.MidiFile(path)\n\n # note_seq, tempo_seq = midi_to_seq(midi_obj, np.int16, np.int16(24000))\n\n \n"
]
| [
[
"numpy.searchsorted",
"numpy.int32",
"numpy.arange",
"numpy.zeros"
]
]
|
gicheonkang/DAN-VisDial | [
"a40422367f349b185c9f3abf5e99c7504eebdc81"
]
| [
"encoders/modules.py"
]
| [
"\"\"\"\nDual Attention Networks for Visual Reference Resolution in Visual Dialog\nGi-Cheon Kang, Jaeseo Lim, Byoung-Tak Zhang\nhttps://arxiv.org/abs/1902.09368\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.nn.utils.weight_norm import weight_norm\nfrom .submodules import MultiHeadAttention, PositionwiseFeedForward\nfrom .fc import FCNet\n\nclass REFER(nn.Module):\n \"\"\" This code is modified from Yu-Hsiang Huang's repository\n https://github.com/jadore801120/attention-is-all-you-need-pytorch\n \"\"\"\n def __init__(self, d_model, d_inner, n_head, d_k, d_v, dropout=0.2):\n super(REFER, self).__init__()\n self.slf_attn = MultiHeadAttention(n_head, d_model, d_k, d_v, dropout=dropout)\n self.pos_ffn = PositionwiseFeedForward(d_model, d_inner, dropout=dropout)\n\n def forward(self, q, m):\n enc_output, enc_slf_attn = self.slf_attn(q, m, m)\n enc_output = self.pos_ffn(enc_output)\n return enc_output, enc_slf_attn\n\nclass FIND(nn.Module):\n \"\"\" This code is modified from Hengyuan Hu's repository.\n https://github.com/hengyuan-hu/bottom-up-attention-vqa\n \"\"\"\n def __init__(self, v_dim, q_dim, num_hid, dropout=0.2):\n super(FIND, self).__init__()\n\n self.v_proj = FCNet([v_dim, num_hid])\n self.q_proj = FCNet([q_dim, num_hid])\n self.dropout = nn.Dropout(dropout)\n self.linear = weight_norm(nn.Linear(num_hid, 1), dim=None)\n\n def forward(self, v, q, v_mask=False):\n \"\"\"\n v: [batch, v, 2048]\n q: [10, batch, 1024]\n \"\"\"\n logits = self.logits(v, q)\n if v_mask:\n mask = (0 == v.abs().sum(2)).unsqueeze(2)\n logits.data.masked_fill_(mask.data, -float('inf'))\n \n w = nn.functional.softmax(logits, 1)\n return w\n\n def logits(self, v, q):\n batch, k, _ = v.size()\n v_proj = self.v_proj(v) \n q_proj = self.q_proj(q).unsqueeze(1).repeat(1, k, 1)\n joint_repr = v_proj * q_proj\n joint_repr = self.dropout(joint_repr)\n logits = self.linear(joint_repr)\n return logits\n"
]
| [
[
"torch.nn.Linear",
"torch.nn.Dropout",
"torch.nn.functional.softmax"
]
]
|
Mo-Saif/sktime | [
"63e7839e80ca6d5fe5fc4f33389ec3bcacd8aa59"
]
| [
"sktime/classifiers/compose/tests/test_TimeSeriesForestClassifier.py"
]
| [
"from sktime.classifiers.compose.ensemble import TimeSeriesForestClassifier\nfrom sktime.utils.testing import generate_df_from_array\nimport pandas as pd\nimport numpy as np\nfrom sktime.transformers.compose import RowwiseTransformer\nfrom sktime.datasets import load_gunpoint\nfrom sktime.pipeline import FeatureUnion, Pipeline\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sktime.transformers.segment import RandomIntervalSegmenter\nfrom sktime.transformers.summarise import RandomIntervalFeatureExtractor\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sktime.utils.time_series import time_series_slope\nimport pytest\n\n\nn_instances = 20\nn_columns = 1\nlen_series = 20\nn_classes = 2\n\nX = generate_df_from_array(np.random.normal(size=len_series), n_rows=n_instances, n_cols=n_columns)\ny = pd.Series(np.random.choice(np.arange(n_classes) + 1, size=n_instances))\n\n\n# Check if random state always gives same results\ndef test_random_state():\n N_ITER = 10\n\n random_state = 1234\n clf = TimeSeriesForestClassifier(n_estimators=2,\n random_state=random_state)\n clf.fit(X, y)\n first_pred = clf.predict_proba(X)\n for _ in range(N_ITER):\n clf = TimeSeriesForestClassifier(n_estimators=2,\n random_state=random_state)\n clf.fit(X, y)\n y_pred = clf.predict_proba(X)\n np.testing.assert_array_equal(first_pred, y_pred)\n\n\n# Check simple cases.\ndef test_predict_proba():\n clf = TimeSeriesForestClassifier(n_estimators=2)\n clf.fit(X, y)\n proba = clf.predict_proba(X)\n\n assert proba.shape == (X.shape[0], n_classes)\n np.testing.assert_array_equal(np.ones(n_instances), np.sum(proba, axis=1))\n\n # test single row input\n y_proba = clf.predict_proba(X.iloc[[0], :])\n assert y_proba.shape == (1, n_classes)\n\n y_pred = clf.predict(X.iloc[[0], :])\n assert y_pred.shape == (1,)\n\n\n# Compare results from different but equivalent implementations\nX_train, y_train = load_gunpoint(split=\"TRAIN\", return_X_y=True)\nX_test, y_test = load_gunpoint(split=\"TEST\", return_X_y=True)\nrandom_state = 1234\n\n\[email protected](\"n_intervals\", ['log', 'sqrt', 1, 3])\[email protected](\"n_estimators\", [1, 3])\ndef test_pipeline_predictions(n_intervals, n_estimators):\n random_state = 1234\n\n # Due to tie-breaking/floating point rounding in the final decision tree classifier, the results depend on the\n # exact column order of the input data\n\n # Compare pipeline predictions outside of ensemble.\n steps = [\n ('segment', RandomIntervalSegmenter(n_intervals=n_intervals)),\n ('transform', FeatureUnion([\n ('mean', RowwiseTransformer(FunctionTransformer(func=np.mean, validate=False))),\n ('std', RowwiseTransformer(FunctionTransformer(func=np.std, validate=False))),\n ('slope', RowwiseTransformer(FunctionTransformer(func=time_series_slope, validate=False)))\n ])),\n ('clf', DecisionTreeClassifier())\n ]\n clf1 = Pipeline(steps, random_state=random_state)\n clf1.fit(X_train, y_train)\n a = clf1.predict(X_test)\n\n steps = [\n ('transform', RandomIntervalFeatureExtractor(n_intervals=n_intervals,\n features=[np.mean, np.std, time_series_slope])),\n ('clf', DecisionTreeClassifier())\n ]\n clf2 = Pipeline(steps, random_state=random_state)\n clf2.fit(X_train, y_train)\n b = clf2.predict(X_test)\n np.array_equal(a, b)\n\n\n# Compare TimeSeriesForest ensemble predictions using pipeline as base_estimator\[email protected](\"n_intervals\", ['log', 'sqrt', 1, 3])\[email protected](\"n_estimators\", [1, 3])\ndef test_TimeSeriesForest_predictions(n_estimators, n_intervals):\n random_state = 1234\n\n # fully modular implementation using pipeline with FeatureUnion\n # steps = [\n # ('segment', RandomIntervalSegmenter(n_intervals=n_intervals)),\n # ('transform', FeatureUnion([\n # ('mean', RowwiseTransformer(FunctionTransformer(func=np.mean, validate=False))),\n # ('std', RowwiseTransformer(FunctionTransformer(func=np.std, validate=False))),\n # ('slope', RowwiseTransformer(FunctionTransformer(func=time_series_slope, validate=False)))\n # ])),\n # ('clf', DecisionTreeClassifier())\n # ]\n # base_estimator = Pipeline(steps)\n features = [np.mean, np.std, time_series_slope]\n steps = [('transform', RandomIntervalFeatureExtractor(n_intervals=n_intervals, features=features)),\n ('clf', DecisionTreeClassifier())]\n base_estimator = Pipeline(steps)\n\n clf1 = TimeSeriesForestClassifier(base_estimator=base_estimator,\n random_state=random_state,\n n_estimators=n_estimators)\n clf1.fit(X_train, y_train)\n a = clf1.predict_proba(X_test)\n\n # default, semi-modular implementation using RandomIntervalFeatureExtractor internally\n clf2 = TimeSeriesForestClassifier(random_state=random_state,\n n_estimators=n_estimators)\n clf2.set_params(**{'base_estimator__transform__n_intervals': n_intervals})\n clf2.fit(X_train, y_train)\n b = clf2.predict_proba(X_test)\n\n np.testing.assert_array_equal(a, b)\n\n\n\n"
]
| [
[
"numpy.random.normal",
"numpy.array_equal",
"sklearn.preprocessing.FunctionTransformer",
"numpy.sum",
"numpy.testing.assert_array_equal",
"numpy.ones",
"numpy.arange",
"sklearn.tree.DecisionTreeClassifier"
]
]
|
kaist-dmlab/COVID-EENet | [
"ee18e61027278d3386b22a2efaf1c749aaf8ce20"
]
| [
"models/TCN/TCN/copy_memory/.ipynb_checkpoints/copymem_test-checkpoint.py"
]
| [
"import argparse\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport numpy as np\nimport sys\nsys.path.append(\"../../\")\nfrom TCN.copy_memory.utils import data_generator\nfrom TCN.copy_memory.model import TCN\nimport time\n\n\nparser = argparse.ArgumentParser(description='Sequence Modeling - Copying Memory Task')\nparser.add_argument('--batch_size', type=int, default=2, metavar='N',\n help='batch size (default: 32)')\nparser.add_argument('--cuda', action='store_false',\n help='use CUDA (default: True)')\nparser.add_argument('--dropout', type=float, default=0.0,\n help='dropout applied to layers (default: 0.0)')\nparser.add_argument('--clip', type=float, default=1.0,\n help='gradient clip, -1 means no clip (default: 1.0)')\nparser.add_argument('--epochs', type=int, default=50,\n help='upper epoch limit (default: 50)')\nparser.add_argument('--ksize', type=int, default=8,\n help='kernel size (default: 8)')\nparser.add_argument('--iters', type=int, default=100,\n help='number of iters per epoch (default: 100)')\nparser.add_argument('--levels', type=int, default=8,\n help='# of levels (default: 8)')\nparser.add_argument('--blank_len', type=int, default=20, metavar='N',\n help='The size of the blank (i.e. T) (default: 1000)')\nparser.add_argument('--seq_len', type=int, default=10,\n help='initial history size (default: 10)')\nparser.add_argument('--log-interval', type=int, default=50, metavar='N',\n help='report interval (default: 50')\nparser.add_argument('--lr', type=float, default=5e-4,\n help='initial learning rate (default: 5e-4)')\nparser.add_argument('--optim', type=str, default='RMSprop',\n help='optimizer to use (default: RMSprop)')\nparser.add_argument('--nhid', type=int, default=10,\n help='number of hidden units per layer (default: 10)')\nparser.add_argument('--seed', type=int, default=1111,\n help='random seed (default: 1111)')\nargs = parser.parse_args()\n\ntorch.manual_seed(args.seed)\nif torch.cuda.is_available():\n if not args.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n\n\nbatch_size = args.batch_size\nseq_len = args.seq_len # The size to memorize\nepochs = args.epochs\niters = args.iters\nT = args.blank_len\nn_steps = T + (2 * seq_len)\nn_classes = 10 # Digits 0 - 9\nn_train = 10000\nn_test = 1000\n\nprint(args)\nprint(\"Preparing data...\")\ntrain_x, train_y = data_generator(T, seq_len, n_train)\ntest_x, test_y = data_generator(T, seq_len, n_test)\n\n\nchannel_sizes = [args.nhid] * args.levels\nkernel_size = args.ksize\ndropout = args.dropout\nmodel = TCN(1, n_classes, channel_sizes, kernel_size, dropout=dropout)\n\nif args.cuda:\n model.cuda()\n train_x = train_x.cuda()\n train_y = train_y.cuda()\n test_x = test_x.cuda()\n test_y = test_y.cuda()\n\ncriterion = nn.CrossEntropyLoss()\nlr = args.lr\noptimizer = getattr(optim, args.optim)(model.parameters(), lr=lr)\n\n\n\n\ndef evaluate():\n model.eval()\n with torch.no_grad():\n out = model(test_x.unsqueeze(1).contiguous())\n loss = criterion(out.view(-1, n_classes), test_y.view(-1))\n pred = out.view(-1, n_classes).data.max(1, keepdim=True)[1]\n correct = pred.eq(test_y.data.view_as(pred)).cpu().sum()\n counter = out.view(-1, n_classes).size(0)\n print('\\nTest set: Average loss: {:.8f} | Accuracy: {:.4f}\\n'.format(\n loss.item(), 100. * correct / counter))\n return loss.item()\n\n\ndef train(ep):\n global batch_size, seq_len, iters, epochs\n model.train()\n total_loss = 0\n start_time = time.time()\n correct = 0\n counter = 0\n for batch_idx, batch in enumerate(range(0, n_train, batch_size)):\n start_ind = batch\n end_ind = start_ind + batch_size\n\n x = train_x[start_ind:end_ind]\n y = train_y[start_ind:end_ind]\n \n print(\"x size: \", x.size())\n print(\"y size: \", y.size())\n print(\"x: \", x)\n print(\"y: \", y)\n \n optimizer.zero_grad()\n out = model(x.unsqueeze(1).contiguous())\n print(\"out size: \", out.size())\n \n loss = criterion(out.view(-1, n_classes), y.view(-1))\n pred = out.view(-1, n_classes).data.max(1, keepdim=True)[1]\n correct += pred.eq(y.data.view_as(pred)).cpu().sum()\n counter += out.view(-1, n_classes).size(0)\n if args.clip > 0:\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)\n loss.backward()\n optimizer.step()\n total_loss += loss.item()\n\n if batch_idx > 0 and batch_idx % args.log_interval == 0:\n avg_loss = total_loss / args.log_interval\n elapsed = time.time() - start_time\n print('| Epoch {:3d} | {:5d}/{:5d} batches | lr {:2.5f} | ms/batch {:5.2f} | '\n 'loss {:5.8f} | accuracy {:5.4f}'.format(\n ep, batch_idx, n_train // batch_size+1, args.lr, elapsed * 1000 / args.log_interval,\n avg_loss, 100. * correct / counter))\n start_time = time.time()\n total_loss = 0\n correct = 0\n counter = 0\n\n\nfor ep in range(1, epochs + 1):\n train(ep)\n evaluate()\n"
]
| [
[
"torch.manual_seed",
"torch.no_grad",
"torch.cuda.is_available",
"torch.nn.CrossEntropyLoss"
]
]
|
markvdw/RobustGP | [
"cfab7a9e7f56755bc7a6241f13a6f6ac29562107"
]
| [
"robustgp/init_methods/rls.py"
]
| [
"import numpy as np\nimport scipy\nfrom typing import Callable, Optional\nfrom .methods import InducingPointInitializer\n\n\nclass RLS(InducingPointInitializer):\n \"\"\"\n Implements a modified version of the \"fixed size\" variant of the (approximate)\n RLS algorithm given in Musco and Musco 2017\n @inproceedings{musco2017recursive,\n title={Recursive sampling for the nystrom method},\n author={Musco, Cameron and Musco, Christopher},\n booktitle={Advances in Neural Information Processing Systems},\n pages={3833--3845},\n year={2017}\n }\n \"\"\"\n\n def __init__(self, seed: Optional[int] = 0, **kwargs):\n super().__init__(seed=seed, randomized=True, **kwargs)\n\n def compute_initialisation(self, training_inputs: np.ndarray, M: int,\n kernel: Callable[[np.ndarray, Optional[np.ndarray], Optional[bool]], np.ndarray]):\n indices, _, _ = recursive_rls(training_inputs, M, kernel, np.arange(training_inputs.shape[0]))\n return training_inputs[indices], indices\n\n\ndef approximate_rls(training_inputs, kernel, regularization, subset_to_predict, subset_used, column_weights):\n X = training_inputs[subset_to_predict]\n Z = training_inputs[subset_used]\n regularization_matrix = np.diag(np.square(1. / column_weights) * regularization)\n regularized_Kuu = kernel(Z) + regularization_matrix\n L = np.linalg.cholesky(regularized_Kuu)\n kuf = kernel(Z, X)\n Linvkuf = scipy.linalg.solve_triangular(L, kuf, lower=True)\n posterior_variance = kernel(X, full_cov=False) - np.sum(np.square(Linvkuf), axis=0)\n\n return 1 / regularization * posterior_variance\n\n\ndef get_indices_and_weights(weighted_leverage, active_indices, k, top_level, M):\n probs = np.minimum(1., weighted_leverage * np.log(2*k))\n if not top_level:\n random_nums = np.random.rand(len(probs))\n indices = np.where(random_nums < probs)[0]\n # in cases where to few (potentially no) weights are sampled\n num_additional_indices = M - len(indices)\n if num_additional_indices > 0:\n candidate_indices = np.where(random_nums >= probs)[0]\n additional_indices = np.random.choice(candidate_indices, size=num_additional_indices,\n replace=False)\n indices = np.append(indices, additional_indices)\n indices_to_include = active_indices[indices]\n column_weights = np.sqrt(1. / probs[indices])\n else:\n probs = probs * M / np.sum(probs)\n random_nums = np.random.rand(len(probs))\n indices_to_include = active_indices[random_nums < probs]\n column_weights = np.sqrt(1. / probs[random_nums < probs])\n # If we sample too few inducing points, resample\n while len(indices_to_include) < M:\n random_nums = np.random.rand(len(probs)) # resample if not enough\n indices_to_include = active_indices[random_nums < probs]\n column_weights = np.sqrt(1. / probs[random_nums < probs])\n probs = np.clip(probs * M / np.sum(np.clip(probs, 0, 1)), 0, 1)\n probs *= 1.01\n inds = np.random.choice(len(indices_to_include), size=M, replace=False)\n indices_to_include, column_weights = indices_to_include[inds], column_weights[inds]\n return indices_to_include, column_weights, probs\n\n\ndef recursive_rls(training_inputs: np.ndarray,\n M: int,\n kernel: Callable[[np.ndarray, Optional[np.ndarray], Optional[bool]], np.ndarray],\n active_indices: np.ndarray):\n num_data = training_inputs.shape[0]\n top_level = len(active_indices) == num_data # boolean indicating we are at top level of recursion\n c = .25\n k = np.minimum(num_data, int(np.ceil(c * M / np.log(M+1))))\n\n if len(active_indices) <= M: # Base case of recursion, see l 1,2 in Musco and Musco, alg 3\n return active_indices, np.ones_like(active_indices), np.ones_like(active_indices)\n s_bar = np.random.randint(0, 2, len(active_indices)).nonzero()[0] # points sampled into Sbar, l4\n if len(s_bar) == 0:\n active_indices = np.random.choice(active_indices, (1+len(active_indices))//2, replace=False)\n return active_indices, np.ones_like(active_indices), np.ones_like(active_indices)\n\n indices_to_include, column_weights, probs = recursive_rls(training_inputs, M, kernel,\n active_indices=active_indices[s_bar])\n Z = training_inputs[indices_to_include]\n SKS = kernel(Z) * column_weights[None, :] * column_weights[:, None] # sketched kernel matrix\n eigvals = scipy.sparse.linalg.eigsh(SKS.numpy(), k=k, which='LM', return_eigenvectors=False)\n\n lam = 1 / k * (np.sum(np.diag(SKS)) - np.sum(eigvals))\n lam = np.maximum(1e-12, lam)\n\n weighted_leverage = approximate_rls(training_inputs, kernel, lam, subset_to_predict=active_indices,\n subset_used=indices_to_include, column_weights=column_weights)\n indices_to_include, column_weights, probs = get_indices_and_weights(weighted_leverage, active_indices, k,\n top_level, M)\n\n return indices_to_include, column_weights, probs"
]
| [
[
"numpy.square",
"numpy.append",
"numpy.clip",
"numpy.ones_like",
"numpy.random.choice",
"numpy.log",
"numpy.sum",
"numpy.where",
"numpy.arange",
"numpy.sqrt",
"numpy.linalg.cholesky",
"scipy.linalg.solve_triangular",
"numpy.diag",
"numpy.maximum"
]
]
|
afterloe/opencv-practice | [
"83d76132d004ebbc96d99d34a0fd3fc37a044f9f"
]
| [
"tf_aip_workshops/3-section/img_to_dataset.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding=utf-8 -*-\n\nimport tensorflow as tf\nfrom nets.nasnet import nasnet\nfrom preprocessing import preprocessing_factory\nfrom imutils.paths import list_images\nimport os\nimport logging\n\nslim = tf.contrib.slim\n\n\"\"\"\n处理图像数据集\n\"\"\"\n\nnum_workers = 8 # 定义并行处理数据的线程数量\nimage_size = nasnet.build_nasnet_mobile.default_image_size # 224\n# 图像批预处理\nimage_pre_processing_fn = preprocessing_factory.get_preprocessing(\"nasnet_mobile\", is_training=True)\nimage_eval_pre_processing_fn = preprocessing_factory.get_preprocessing(\"nasnet_mobile\", is_training=False)\n\nCONSOLE = logging.getLogger(\"dev\")\n\n\ndef get_images_list(directory):\n \"\"\"\n 获取目录下所有的图片和标签\n\n :param directory: 目录\n :return:\n \"\"\"\n labels = os.listdir(directory) # 获取所有标签\n labels.sort() # 对标签进行排序,以便训练和验证都采用相同的顺序进行\n files_and_labels = [] # 创建文件标签列表\n for label in labels:\n images = list_images(os.path.sep.join([directory, label]))\n for i in images:\n files_and_labels.append((i, label))\n file_names, labels = zip(*files_and_labels)\n file_names = list(file_names)\n labels = list(labels)\n unique_labels = list(set(labels))\n # 为每个分类打上标签 {\"none\":0, \"cat\": 1, \"dog\": 2, \"panda\":3}\n label_to_int = {}\n for i, label in enumerate(sorted(unique_labels)):\n label_to_int[label] = i + 1\n labels = [label_to_int[l] for l in labels]\n return file_names, labels\n\n\ndef parse_function(filename, label):\n \"\"\"\n 图像解码函数\n :param filename:\n :param label:\n :return:\n \"\"\"\n image_string = tf.read_file(filename)\n image = tf.image.decode_jpeg(image_string, channels=3)\n return image, label\n\n\ndef training_pre_process(image, label):\n image = image_pre_processing_fn(image, image_size, image_size)\n return image, label\n\n\ndef val_pre_process(image, label):\n image = image_eval_pre_processing_fn(image, image_size, image_size)\n return image, label\n\n\ndef create_batched_dataset(filenames, labels, batch_size, is_train=True):\n \"\"\"\n 创建带批次的数据集\n :param filenames:\n :param labels:\n :param batch_size:\n :param is_train:\n :return:\n \"\"\"\n data_set = tf.data.Dataset.from_tensor_slices((filenames, labels))\n data_set = data_set.map(parse_function, num_parallel_calls=num_workers)\n if True is is_train:\n data_set = data_set.shuffle(buffer_size=len(filenames))\n data_set = data_set.map(training_pre_process, num_parallel_calls=num_workers)\n else:\n data_set = data_set.map(val_pre_process, num_parallel_calls=num_workers)\n return data_set.batch(batch_size)\n\n\ndef create_dataset_fromdir(directory, batch_size, is_train=True):\n filenames, labels = get_images_list(directory)\n num_classes = len(set(labels))\n data_set = create_batched_dataset(filenames, labels, batch_size, is_train)\n return data_set, num_classes\n"
]
| [
[
"tensorflow.read_file",
"tensorflow.data.Dataset.from_tensor_slices",
"tensorflow.image.decode_jpeg"
]
]
|
rhugonnet/scikit-gstat | [
"a142ca13aa3b048c46613d1247396c80c32a8145"
]
| [
"skgstat/tests/test_variogram.py"
]
| [
"import unittest\nimport os\nimport pickle\n\nimport numpy as np\nimport pandas as pd\nfrom numpy.testing import assert_array_almost_equal\nimport matplotlib.pyplot as plt\n\ntry:\n import plotly.graph_objects as go\n PLOTLY_FOUND = True\nexcept ImportError:\n print('No plotly installed. Skip plot tests')\n PLOTLY_FOUND = False\n\nfrom skgstat import Variogram\nfrom skgstat import OrdinaryKriging\nfrom skgstat import estimators\nfrom skgstat import plotting\n\n\nclass TestSpatiallyCorrelatedData(unittest.TestCase):\n def setUp(self):\n # Generate some random but spatially correlated data\n # with a range of ~20\n \n np.random.seed(42)\n c = np.random.sample((50, 2)) * 60\n np.random.seed(42)\n v = np.random.normal(10, 4, 50)\n \n V = Variogram(c, v).describe()\n V[\"effective_range\"] = 20\n OK = OrdinaryKriging(V, coordinates=c, values=v)\n\n self.c = np.random.sample((500, 2)) * 60\n self.v = OK.transform(self.c)\n\n self.c = self.c[~np.isnan(self.v),:]\n self.v = self.v[~np.isnan(self.v)]\n\n def test_dense_maxlag_inf(self):\n Vdense = Variogram(self.c, self.v)\n Vsparse = Variogram(self.c, self.v, maxlag=10000000)\n\n for x, y in zip(Vdense.parameters, Vsparse.parameters):\n self.assertAlmostEqual(x, y, places=3)\n \n def test_sparse_maxlag_50(self):\n V = Variogram(self.c, self.v, maxlag=50)\n\n for x, y in zip(V.parameters, [20.264, 6.478, 0]):\n self.assertAlmostEqual(x, y, places=3)\n \n def test_sparse_maxlag_30(self):\n V = Variogram(self.c, self.v, maxlag=30)\n\n for x, y in zip(V.parameters, [17.128, 6.068, 0]):\n self.assertAlmostEqual(x, y, places=3)\n\n\nclass TestVariogramInstatiation(unittest.TestCase):\n def setUp(self):\n # set up default values, whenever c and v are not important\n np.random.seed(42)\n self.c = np.random.gamma(10, 4, (30, 2))\n np.random.seed(42)\n self.v = np.random.normal(10, 4, 30)\n\n def test_standard_settings(self):\n V = Variogram(self.c, self.v)\n\n for x, y in zip(V.parameters, [7.122, 13.966, 0]):\n self.assertAlmostEqual(x, y, places=3)\n \n def test_sparse_standard_settings(self):\n V = Variogram(self.c, self.v, maxlag=10000)\n\n for x, y in zip(V.parameters, [7.122, 13.966, 0]):\n self.assertAlmostEqual(x, y, places=3)\n\n def test_input_dimensionality(self):\n c1d = np.random.normal(0, 1, 100)\n c3d = np.random.normal(0, 1, size=(100, 3))\n v = np.random.normal(10, 4, 100)\n\n # test 1D coords\n V = Variogram(c1d, v)\n self.assertTrue(V.dim == 1)\n\n # test 3D coords\n V2 = Variogram(c3d, v)\n self.assertTrue(V2.dim == 3)\n\n def test_pass_median_maxlag_on_instantiation(self):\n np.random.seed(1312)\n c = np.random.gamma(5, 1, (50, 2))\n\n np.random.seed(1312)\n v = np.random.weibull(5, 50)\n\n V = Variogram(c, v, maxlag='median', n_lags=4)\n bins = [0.88, 1.77, 2.65, 3.53]\n\n for b, e in zip(bins, V.bins):\n self.assertAlmostEqual(b, e, places=2)\n\n def test_pass_mean_maxlag_on_instantiation(self):\n V = Variogram(self.c, self.v, maxlag='mean', n_lags=4)\n\n bins = [4.23, 8.46, 12.69, 16.91]\n\n for b, e in zip(bins, V.bins):\n self.assertAlmostEqual(b, e, places=2)\n\n def test_unknown_binning_func(self):\n with self.assertRaises(ValueError) as e:\n Variogram(self.c, self.v, bin_func='notafunc')\n\n self.assertEqual(\n \"'notafunc' is not a valid estimator for `bins`\",\n str(e.exception)\n )\n\n def test_invalid_binning_func(self):\n with self.assertRaises(AttributeError) as e:\n V = Variogram(self.c, self.v)\n V.set_bin_func(42)\n \n self.assertTrue('of type string' in str(e.exception))\n\n def test_unknown_model(self):\n with self.assertRaises(ValueError) as e:\n Variogram(self.c, self.v, model='unknown')\n\n self.assertEqual(\n 'The theoretical Variogram function unknown is not understood, please provide the function',\n str(e.exception)\n )\n\n def test_unsupported_n_lags(self):\n with self.assertRaises(ValueError) as e:\n Variogram(self.c, self.v, n_lags=15.7)\n\n self.assertEqual(\n 'n_lags has to be a positive integer',\n str(e.exception)\n )\n\n def test_value_warning(self):\n with self.assertRaises(Warning) as w:\n Variogram(self.c, [42] * 30)\n \n self.assertEqual(\n 'All input values are the same.',\n str(w.exception)\n )\n\n\nclass TestVariogramArguments(unittest.TestCase):\n def setUp(self):\n # set up default values, whenever c and v are not important\n np.random.seed(42)\n self.c = np.random.gamma(10, 4, (30, 2))\n np.random.seed(42)\n self.v = np.random.normal(10, 4, 30)\n\n def test_binning_method_setting(self):\n V = Variogram(self.c, self.v, n_lags=4)\n\n # lags\n even = [10.58, 21.15, 31.73, 42.3]\n uniform = [10.25, 16.21, 22.71, 42.3]\n\n # test even\n assert_array_almost_equal(even, V.bins, decimal=2)\n\n # set to uniform\n V.set_bin_func('uniform')\n assert_array_almost_equal(uniform, V.bins, decimal=2)\n\n # restore even\n V.bin_func = 'even'\n assert_array_almost_equal(even, V.bins, decimal=2)\n\n def test_binning_method_scott(self):\n V = Variogram(self.c, self.v, bin_func='scott')\n\n # scott should yield 11 bins here\n self.assertTrue(V.n_lags == 11)\n\n assert_array_almost_equal(\n V.bins,\n np.array([4.9, 8.6, 12.4, 16.1, 19.9, 23.6, 27.3, 31.1, 34.8, 38.6, 42.3]),\n decimal=1\n )\n\n def test_binning_method_stable(self):\n V = Variogram(self.c, self.v, bin_func='stable_entropy')\n\n assert_array_almost_equal(\n V.bins,\n np.array([4.3, 8.4, 12.8, 17.1, 21.4, 25.2, 29.9, 33.2, 38.5, 42.8]),\n decimal=1\n )\n\n def test_binning_method_stable_maxiter(self):\n # increase maxiter - the result should stay the same\n V = Variogram(self.c, self.v, bin_func='stable_entropy', binning_maxiter=20000)\n\n assert_array_almost_equal(\n V.bins,\n np.array([4.3, 8.4, 12.8, 17.1, 21.4, 25.2, 29.9, 33.2, 38.5, 42.8]),\n decimal=1\n )\n\n def test_binning_method_stable_fix_bins(self):\n # use 50 bins over the sqrt method - this should change the bins\n V = Variogram(\n self.c,\n self.v,\n bin_func='stable_entropy',\n binning_entropy_bins=50\n )\n\n assert_array_almost_equal(\n V.bins,\n np.array([4.2, 8.6, 12.8, 17.1, 21.2, 25.5, 29.3, 33.2, 37.4, 43.]),\n decimal=1\n )\n\n def test_binning_change_nlags(self):\n V = Variogram(self.c, self.v, n_lags=5)\n\n # 5 lags are awaited\n self.assertTrue(V.n_lags == 5)\n\n # switch to fd rule\n V.bin_func = 'fd'\n\n self.assertTrue(V.n_lags == 13)\n\n def test_set_bins_directly(self):\n V = Variogram(self.c, self.v, n_lags=5)\n\n # set bins by hand\n bins = np.array([4., 20., 21., 25., 40.])\n V.bins = bins\n\n # test setting\n assert_array_almost_equal(bins, V.bins, decimal=8)\n\n # test cov settings\n self.assertIsNone(V.cov)\n self.assertIsNone(V.cof)\n\n def test_binning_non_string_arg(self):\n V = Variogram(self.c, self.v, n_lags=8)\n\n return True\n\n def test_binning_kmeans_method(self):\n V = Variogram(\n self.c,\n self.v,\n n_lags=6,\n bin_func='kmeans',\n binning_random_state=1306\n )\n\n assert_array_almost_equal(\n V.bins,\n np.array([2.5, 7.7, 12.9, 18.1, 23.7, 30.3]),\n decimal=1\n )\n\n def test_binning_ward_method(self):\n V = Variogram(self.c, self.v, n_lags=6, bin_func='ward')\n\n assert_array_almost_equal(\n V.bins,\n np.array([2.5, 7.1, 11.1, 16.2, 23., 30.]),\n decimal=1\n )\n\n\n def test_estimator_method_setting(self):\n \"\"\"\n Only test if the estimator functions are correctly set. The\n estimator functions themselves are tested in a unittest of their own.\n \"\"\"\n V = Variogram(self.c, self.v, n_lags=4)\n\n estimator_list = ('cressie', 'matheron', 'dowd', 'genton', 'minmax',\n 'percentile', 'entropy')\n\n for estimator in estimator_list:\n # set the estimator\n V.estimator = estimator\n imported_estimator = getattr(estimators, estimator)\n self.assertEqual(imported_estimator, V.estimator)\n\n def test_set_estimator_wrong_type(self):\n V = Variogram(self.c, self.v)\n\n with self.assertRaises(ValueError) as e:\n V.set_estimator(45)\n self.assertEqual(\n str(e.exception),\n 'The estimator has to be a string or callable.'\n )\n\n def test_set_unknown_estimator(self):\n V = Variogram(self.c, self.v)\n\n with self.assertRaises(ValueError) as e:\n V.set_estimator('notaestimator')\n\n self.assertEqual(\n str(e.exception),\n 'Variogram estimator notaestimator is not understood, please ' +\n 'provide the function.'\n )\n\n def test_set_dist_func(self):\n V = Variogram([(0, 0), (4, 1), (1, 1)], [1, 2, 3], n_lags=2)\n\n # use Manhattan distance\n V.set_dist_function('cityblock')\n for d, v in zip([5., 2., 3.], V.distance):\n self.assertEqual(d, v)\n\n def test_unknown_dist_func(self):\n V = Variogram(self.c, self.v)\n\n with self.assertRaises(ValueError) as e:\n V.set_dist_function('notadistance')\n \n self.assertEqual(\n str(e.exception),\n 'Unknown Distance Metric: notadistance'\n )\n\n def test_wrong_dist_func_input(self):\n V = Variogram(self.c, self.v)\n\n with self.assertRaises(ValueError) as e:\n V.set_dist_function(55)\n \n self.assertEqual(\n str(e.exception),\n 'Input not supported. Pass a string or callable.'\n )\n\n def test_callable_dist_function(self):\n V = Variogram([(0, 0), (4, 1), (1, 1)], [1, 2, 3], n_lags=2)\n\n def dfunc(u, v):\n return 1\n\n V.set_dist_function(dfunc)\n\n # test\n self.assertEqual(V.dist_function, dfunc)\n self.assertTrue((V.distance==1).all())\n self.assertEqual(V.distance_matrix.shape, (3, 3))\n\n @staticmethod\n def disabled_test_direct_dist_setting():\n # Distance can no longer be explicitly set\n # it would require setting the whole MetricSpace, with a\n # non-sparse diagonal matrix\n \n V = Variogram([(0, 0), (4, 1), (1, 1)], [1, 2, 3], n_lags=2)\n\n V.distance = np.array([0, 0, 100])\n\n assert_array_almost_equal(V.distance, [0, 0, 100], decimal=0)\n\n def test_maxlag_setting_as_max_ratio(self):\n V = Variogram(self.c, self.v)\n\n # set maxlag to 60% of maximum distance\n V.maxlag = 0.6\n self.assertEqual(V.maxlag, np.max(V.distance) * 0.6)\n self.assertAlmostEqual(V.maxlag, 25.38, places=2)\n\n def test_maxlag_custom_value(self):\n V = Variogram(self.c, self.v)\n\n V.maxlag = 33.3\n self.assertAlmostEqual(V.maxlag, 33.3, places=1)\n\n def test_use_nugget_setting(self):\n V = Variogram(self.c, self.v, normalize=True)\n\n # test the property and setter\n self.assertEqual(V.use_nugget, False)\n self.assertEqual(V.describe()['nugget'], 0)\n\n # set the nugget\n V.use_nugget = True\n self.assertEqual(V.use_nugget, True)\n self.assertEqual(V._use_nugget, True)\n self.assertAlmostEqual(\n V.describe()['normalized_nugget'],\n 291.28,\n places=2\n )\n\n def test_use_nugget_exception(self):\n with self.assertRaises(ValueError) as e:\n Variogram(self.c, self.v, use_nugget=42)\n\n self.assertEqual(\n str(e.exception),\n 'use_nugget has to be of type bool.'\n )\n\n def test_n_lags_change(self):\n V = Variogram(self.c, self.v, n_lags=10)\n\n self.assertEqual(len(V.bins), 10)\n V.n_lags = 5\n self.assertEqual(len(V.bins), 5)\n\n def test_n_lags_exception(self):\n for arg in [15.5, -5]:\n with self.assertRaises(ValueError) as e:\n Variogram(self.c, self.v, n_lags=arg)\n\n self.assertEqual(\n str(e.exception),\n 'n_lags has to be a positive integer'\n )\n\n def test_n_lags_not_implemented(self):\n with self.assertRaises(NotImplementedError):\n Variogram(self.c, self.v, n_lags='auto')\n\n def test_set_values(self):\n V = Variogram(self.c, self.v)\n\n # create a new array of same length\n _old_vals = V.values\n new_vals = np.random.normal(10, 2, size=len(_old_vals))\n\n V.values = new_vals\n\n # values.setter will call set_values\n assert_array_almost_equal(V.values, new_vals, decimal=4)\n\n def test_value_matrix(self):\n vals = np.array([1, 2, 3, 4])\n mat = np.asarray([[0, 1, 2, 3], [1, 0, 1, 2],[2, 1, 0, 1], [3, 2, 1, 0]], dtype=int)\n\n V = Variogram(self.c[:4], vals)\n\n assert_array_almost_equal(V.value_matrix, mat, decimal=1)\n\n def _test_normalize_setter(self):\n # TODO: I should fix this behavior\n V = Variogram(self.c, self.v, normalize=False)\n\n # make sure biggest bin larger than 1.0\n self.assertGreater(np.max(V.bins), 1.0)\n\n # normalize\n V.normalize = True\n\n # now, biggest bin should be almost or exactly 1.0\n self.assertLessEqual(np.max(V.bins), 1.0)\n\n def test_distance_matrix(self):\n coor = [[0, 0], [1, 0], [0, 1], [1, 1]]\n vals = [0, 1, 2, 3]\n dist_mat = np.asarray([\n [0, 1, 1, 1.414],\n [1, 0, 1.414, 1],\n [1, 1.414, 0, 1],\n [1.414, 1, 1, 0]\n ])\n\n V = Variogram(coor, vals)\n\n assert_array_almost_equal(V.distance_matrix, dist_mat, decimal=3)\n\n def test_entropy_as_estimator(self):\n \"\"\"\n Note: This unittest will change in future, as soon as the\n bin edges for Entropy calculation can be set on instantiation\n\n \"\"\"\n V = Variogram(self.c, self.v, estimator='entropy', n_lags=10)\n\n assert_array_almost_equal(\n V.experimental,\n [2.97, 3.3, 3.45, 2.95, 3.33, 3.28, 3.31, 3.44, 2.65, 1.01],\n decimal=2\n )\n\n def test_metric_space_property(self):\n \"\"\"\n Test that the MetricSpace is correctly returned\n \"\"\"\n V = Variogram(self.c, self.v)\n\n # get the metric space through property\n mc = V.metric_space\n\n # assert the coords are actually the same\n assert_array_almost_equal(\n mc.coords,\n V.coordinates,\n decimal=5\n )\n\n def test_metric_space_readonly(self):\n \"\"\"\n Verify that metric_space is a read-only property.\n \"\"\"\n V = Variogram(self.c, self.v)\n\n with self.assertRaises(AttributeError) as e:\n V.metric_space = self.c\n\n self.assertTrue('read-only' in str(e.exception))\n\n\nclass TestVariogramFittingProcedure(unittest.TestCase):\n def setUp(self):\n np.random.seed(1337)\n self.c = np.random.gamma(10, 8, (50, 3))\n np.random.seed(1337)\n self.v = np.random.normal(10, 4, 50)\n\n # build a standard variogram to be used\n self.V = Variogram(\n self.c, self.v, n_lags=5, normalize=False, use_nugget=True\n )\n\n def test_fit_sigma_is_None(self):\n self.V.fit_sigma = None\n\n self.assertIsNone(self.V.fit_sigma)\n\n def test_fit_sigma_explicit(self):\n sigs = [.8, .5, 2., 2., 5.]\n self.V.fit_sigma = sigs\n\n for x, y in zip(sigs, self.V.fit_sigma):\n self.assertEqual(x, y)\n\n def test_fit_sigma_raises_AttributeError(self):\n self.V.fit_sigma = (0, 1, 2)\n\n with self.assertRaises(AttributeError) as e:\n self.V.fit_sigma\n \n self.assertTrue(\n 'len(fit_sigma)' in str(e.exception)\n )\n\n def test_fit_sigma_raises_ValueError(self):\n self.V.fit_sigma = 'notAnFunction'\n\n with self.assertRaises(ValueError) as e:\n self.V.fit_sigma\n\n self.assertTrue(\n \"fit_sigma is not understood.\" in str(e.exception)\n )\n\n def test_fit_sigma_linear(self):\n self.V.fit_sigma = 'linear'\n\n # test the sigmas\n sigma = self.V.fit_sigma\n for s, _s in zip(sigma, [.2, .4, .6, .8, 1.]):\n self.assertAlmostEqual(s, _s, places=8)\n\n # test parameters:\n self.V.fit()\n assert_array_almost_equal(\n self.V.parameters, [13., 0.3, 18.], decimal=1\n )\n\n def test_fit_sigma_exp(self):\n self.V.fit_sigma = 'exp'\n\n # test the sigmas\n sigma = self.V.fit_sigma\n for s, _s in zip(sigma, [0.0067, 0.0821, 0.1889, 0.2865, 0.3679]):\n self.assertAlmostEqual(s, _s, places=4)\n\n # test parameters\n assert_array_almost_equal(\n self.V.parameters, [25., 0.2, 18.5], decimal=1\n )\n\n def test_fit_sigma_sqrt(self):\n self.V.fit_sigma = 'sqrt'\n\n # test the sigmas\n assert_array_almost_equal(\n self.V.fit_sigma, [0.447, 0.632, 0.775, 0.894, 1.], decimal=3\n )\n\n # test the parameters\n assert_array_almost_equal(\n self.V.parameters, [19.7, 1.5, 16.4], decimal=1\n )\n\n def test_fit_sigma_sq(self):\n self.V.fit_sigma = 'sq'\n\n # test the sigmas\n assert_array_almost_equal(\n self.V.fit_sigma, [0.04, 0.16, 0.36, 0.64, 1.], decimal=2\n )\n\n # test the parameters\n assert_array_almost_equal(\n self.V.parameters, [5.4, 0.1, 18.5], decimal=1\n )\n\n def test_fit_sigma_entropy(self):\n # load data sample\n data = pd.read_csv(os.path.dirname(__file__) + '/sample.csv')\n V = Variogram(\n data[['x', 'y']].values,\n data.z.values,\n n_lags=12,\n fit_method='ml',\n fit_sigma='entropy'\n )\n\n assert_array_almost_equal(\n V.parameters, [65.9, 1.3, 0], decimal=1\n )\n\n def test_fit_sigma_on_the_fly(self):\n self.V.fit(sigma='sq')\n\n # test the sigmas\n assert_array_almost_equal(\n self.V.fit_sigma, [0.04, 0.16, 0.36, 0.64, 1.], decimal=2\n )\n\n # test the parameters\n assert_array_almost_equal(\n self.V.parameters, [5.4, 0.1, 18.5], decimal=1\n )\n\n def test_fit_lm(self):\n df = pd.read_csv(os.path.dirname(__file__) + '/sample.csv')\n V = Variogram(\n df[['x', 'y']],\n df.z.values,\n use_nugget=True,\n n_lags=8, fit_method='lm'\n )\n\n # test the parameters\n assert_array_almost_equal(\n V.parameters, [162.3, 0.5, 0.8], decimal=1\n )\n\n def test_fitted_model(self):\n self.V._fit_method = 'trf'\n self.V.fit_sigma = None\n fun = self.V.fitted_model\n\n result = np.array([12.48, 17.2, 17.2, 17.2])\n\n assert_array_almost_equal(\n result, list(map(fun, np.arange(0, 20, 5))),\n decimal=2\n )\n\n def test_unavailable_method(self):\n with self.assertRaises(AttributeError) as e:\n self.V.fit(method='unsupported')\n\n self.assertTrue(\n \"fit_method has to be one of\" in str(e.exception)\n )\n\n def test_implicit_run_fit_fitted_model(self):\n self.V.fit_sigma = None\n self.V._fit_method = 'trf'\n result = np.array([12.48, 17.2, 17.2, 17.2])\n\n # remove cof\n self.V.cof = None\n\n # test on fitted model\n fun = self.V.fitted_model\n\n assert_array_almost_equal(\n result, list(map(fun, np.arange(0, 20, 5))), decimal=2\n )\n\n def test_implicit_run_fit_transform(self):\n self.V.fit_sigma = None\n self.V._fit_method = 'trf'\n result = np.array([12.48, 17.2, 17.2, 17.2])\n\n # test on transform\n self.V.cof = None\n res = self.V.transform(np.arange(0, 20, 5))\n\n assert_array_almost_equal(result, res, decimal=2)\n\n def test_harmonize_model(self):\n # load data sample\n data = pd.read_csv(os.path.dirname(__file__) + '/sample.csv')\n V = Variogram(data[['x', 'y']].values, data.z.values)\n\n V.model = 'harmonize'\n x = np.linspace(0, np.max(V.bins), 10)\n\n assert_array_almost_equal(\n V.transform(x),\n [np.NaN, 0.57, 1.01, 1.12, 1.15, 1.15, 1.15, 1.15, 1.21, 1.65],\n decimal=2\n )\n\n def test_ml_default(self):\n # load data sample\n df = pd.read_csv(os.path.dirname(__file__) + '/sample.csv')\n V = Variogram(\n df[['x', 'y']],\n df.z.values,\n use_nugget=True,\n n_lags=15,\n fit_method='ml'\n )\n\n assert_array_almost_equal(\n V.parameters, np.array([41.18, 1.2, 0.]), decimal=2\n )\n\n def test_ml_sq_sigma(self):\n # load data sample\n df = pd.read_csv(os.path.dirname(__file__) + '/sample.csv')\n V = Variogram(\n df[['x', 'y']],\n df.z.values,\n use_nugget=True,\n n_lags=15,\n fit_method='ml',\n fit_sigma='sq'\n )\n\n assert_array_almost_equal(\n V.parameters, np.array([42.72, 1.21, 0.]), decimal=2\n )\n\n def test_manual_fit(self):\n V = Variogram(\n self.c,\n self.v,\n fit_method='manual',\n model='spherical',\n fit_range=10.,\n fit_sill=5.\n )\n\n self.assertEqual(V.parameters, [10., 5., 0.0])\n \n def test_manual_fit_change(self):\n V = Variogram(\n self.c,\n self.v,\n fit_method='trf',\n model='matern',\n )\n\n # switch to manual fit\n V._fit_method = 'manual'\n V.fit(range=10, sill=5, shape=3)\n\n self.assertEqual(V.parameters, [10., 5., 3., 0.0])\n\n def test_manual_raises_missing_params(self):\n with self.assertRaises(AttributeError) as e:\n Variogram(self.c, self.v, fit_method='manual')\n self.assertTrue('For manual fitting' in str(e.exception))\n\n def test_manual_preserve_params(self):\n V = Variogram(self.c, self.v, fit_method='trf', n_lags=8)\n params = V.parameters\n\n # switch fit method\n V._fit_method = 'manual'\n V.fit(sill=14)\n\n # expected output\n params[1] = 14.\n\n assert_array_almost_equal(\n V.parameters,\n params,\n decimal=1\n ) \n\n\nclass TestVariogramQaulityMeasures(unittest.TestCase):\n def setUp(self):\n # set up default values, whenever c and v are not important\n np.random.seed(42)\n self.c = np.random.gamma(10, 4, (30, 2))\n np.random.seed(42)\n self.v = np.random.normal(10, 4, 30)\n\n def test_residuals(self):\n V = Variogram(self.c, self.v)\n assert_array_almost_equal(\n V.residuals,\n np.array(\n [-3.43e-08, -1.33e-01, 2.11e+00, 4.89e+00, 1.37e+00, 1.50e+00,\n -3.83e+00, -6.89e+00, 3.54e+00, -2.55e+00]),\n decimal=2\n )\n\n def test_rmse(self):\n V = Variogram(self.c, self.v)\n\n for model, rmse in zip(\n ['spherical', 'gaussian', 'stable'],\n [3.3705, 3.3707, 3.193]\n ):\n V.set_model(model)\n self.assertAlmostEqual(V.rmse, rmse, places=4)\n\n def test_mean_residual(self):\n V = Variogram(self.c, self.v)\n\n for model, mr in zip(\n ['spherical', 'cubic', 'stable'],\n [2.6803, 2.6803, 2.6966]\n ):\n V.set_model(model)\n self.assertAlmostEqual(V.mean_residual, mr, places=4)\n\n def test_nrmse(self):\n V = Variogram(self.c, self.v, n_lags=15)\n\n for model, nrmse in zip(\n ['spherical', 'gaussian', 'stable', 'exponential'],\n [0.3536, 0.3535, 0.3361, 0.3499]\n ):\n V.set_model(model)\n self.assertAlmostEqual(V.nrmse, nrmse, places=4)\n\n def test_nrmse_r(self):\n V = Variogram(self.c, self.v, estimator='cressie')\n\n self.assertAlmostEqual(V.nrmse_r, 0.63543, places=5)\n\n def test_r(self):\n V = Variogram(self.c, self.v, n_lags=12, normalize=False)\n\n for model, r in zip(\n ('gaussian', 'exponential', 'stable'), \n [0.39, 0.55, 0.60]\n ):\n V.set_model(model)\n self.assertAlmostEqual(V.r, r, places=2)\n\n def test_NS(self):\n V = Variogram(self.c, self.v, n_lags=15, normalize=False)\n\n for estimator, NS in zip(\n ('matheron', 'genton', 'dowd'),\n [0.0206, 0.0206, 0.0206]\n ):\n self.assertAlmostEqual(V.NS, NS, places=4)\n \n def test_mae(self):\n V = Variogram(self.c, self.v, n_lags=15)\n\n self.assertAlmostEqual(V.mae, 3.91, places=2)\n\n def test_mse(self):\n V = Variogram(self.c, self.v, n_lags=15)\n\n self.assertAlmostEqual(np.sqrt(V.mse), V.rmse, places=6)\n\n def test_update_kwargs(self):\n V = Variogram(self.c, self.v, percentile=.3)\n\n self.assertAlmostEqual(\n V._kwargs.get('percentile'), 0.3, places=1\n )\n\n # change the parameter\n V.update_kwargs(percentile=0.7)\n\n self.assertAlmostEqual(\n V._kwargs.get('percentile'), 0.7, places=1\n )\n\n def test_kwargs_setter_in_experimental(self):\n V = Variogram(self.c, self.v, estimator='percentile')\n\n # store with p of 50 == median\n exp = V.experimental\n\n V.update_kwargs(percentile=25)\n\n exp2 = V.experimental\n\n # 25% should be very different from median\n with self.assertRaises(AssertionError):\n assert_array_almost_equal(exp, exp2, decimal=2)\n\n\nclass TestVariogramMethods(unittest.TestCase):\n def setUp(self):\n # set up default values, whenever c and v are not important\n np.random.seed(42)\n self.c = np.random.gamma(10, 4, (30, 2))\n np.random.seed(42)\n self.v = np.random.normal(10, 4, 30)\n\n self.V = Variogram(self.c, self.v, normalize=False, n_lags=10)\n\n def test_get_empirical(self):\n bins = self.V.bins\n exp = self.V.experimental\n\n emp_x, emp_y = self.V.get_empirical()\n\n # test\n assert_array_almost_equal(bins, emp_x)\n assert_array_almost_equal(exp, emp_y)\n \n def test_get_empirical_center(self):\n V = Variogram(self.c, self.v)\n\n # overwrite bins\n V.bins = [4, 8, 9, 12, 15]\n emp_x, emp_y = V.get_empirical(bin_center=True)\n\n assert_array_almost_equal(emp_x, [2., 6., 8.5, 10.5, 13.5])\n\n def test_clone_method(self):\n # copy variogram\n copy = self.V.clone()\n\n # test against bins and experimental\n assert_array_almost_equal(copy.experimental, self.V.experimental)\n assert_array_almost_equal(copy.bins, self.V.bins)\n\n def test_data_no_force(self):\n lags, var = self.V.data(n=10, force=False)\n\n assert_array_almost_equal(\n lags,\n [0., 4.7, 9.4, 14.1, 18.8, 23.5, 28.2, 32.9, 37.6, 42.3], \n decimal=2\n )\n\n assert_array_almost_equal(\n var,\n [0., 11.82, 13.97, 13.97, 13.97, 13.97, 13.97, 13.97, 13.97, 13.97],\n decimal=2\n )\n\n def disabled_test_data_with_force(self):\n # Distance can no longer be explicitly set\n # it would require setting the whole MetricSpace, with a\n # non-sparse diagonal matrix\n \n # should work if _dist is corccupted\n self.V._dist = self.V._dist * 5.\n self.V.cof = None\n lags, var = self.V.data(n=10, force=True)\n\n assert_array_almost_equal(\n lags,\n [0., 4.7, 9.4, 14.1, 18.8, 23.5, 28.2, 32.9, 37.6, 42.3],\n decimal=2\n )\n\n assert_array_almost_equal(\n var,\n [0., 11.82, 13.97, 13.97, 13.97, 13.97, 13.97, 13.97, 13.97, 13.97],\n decimal=2\n )\n\n def test_data_normalized(self):\n V = self.V.clone()\n\n V.normalize = True\n\n lags, var = V.data(n=5, force=True)\n\n assert_array_almost_equal(\n lags,\n [0., 10.58, 21.15, 31.73, 42.3],\n decimal=2\n )\n\n assert_array_almost_equal(\n var,\n [0., 13.97, 13.97, 13.97, 13.97],\n decimal=2\n )\n \n def test_parameter_property_matern(self):\n V = self.V.clone()\n \n # test matern\n param = [42.3, 16.2, 0.1, 0.]\n V.set_model('matern')\n assert_array_almost_equal(V.parameters, param, decimal=2)\n \n def test_parameter_property_stable(self):\n V = self.V.clone()\n\n # test stable\n param = [42.3, 15.79, 0.45, 0.]\n V.set_model('stable')\n assert_array_almost_equal(V.parameters, param, decimal=2)\n\n\nclass TestVariogramPlots(unittest.TestCase):\n def setUp(self):\n # set up default values, whenever c and v are not important\n np.random.seed(42)\n self.c = np.random.gamma(10, 4, (150, 2))\n np.random.seed(42)\n self.v = np.random.normal(10, 4, 150)\n\n def test_main_plot(self):\n V = Variogram(self.c, self.v, n_lags=5, normalize=True)\n\n # build the figure\n fig = V.plot(show=False)\n ax1, ax2 = fig.axes\n\n # test experimental\n assert_array_almost_equal(\n [0.71, 0.83, 1., 0.88, 0.86],\n ax1.get_children()[1].get_data()[1],\n decimal=2\n )\n\n # test theoretical at some locations\n assert_array_almost_equal(\n [0.16, 0.57, 0.88, 0.89],\n ax1.get_children()[2].get_data()[1][[4, 15, 30, 50]],\n decimal=2\n )\n\n def test_main_plot_pass_axes(self):\n V = Variogram(self.c, self.v, n_lags=5, normalize=True)\n\n # build the figure externally\n fig, axes = plt.subplots(1, 2)\n fig = V.plot(axes=axes, show=False)\n ax1, ax2 = fig.axes\n\n # test experimental\n assert_array_almost_equal(\n [0.71, 0.83, 1., 0.88, 0.86],\n ax1.get_children()[1].get_data()[1],\n decimal=2\n )\n\n # test theoretical at some locations\n assert_array_almost_equal(\n [0.16, 0.57, 0.88, 0.89],\n ax1.get_children()[2].get_data()[1][[4, 15, 30, 50]],\n decimal=2\n )\n\n def test_main_plot_not_normalized(self):\n V = Variogram(self.c, self.v, n_lags=5, normalize=False)\n\n # build the figure\n fig = V.plot(show=False)\n ax1, ax2 = fig.axes\n\n # test experimental\n assert_array_almost_equal(\n [12.7 , 15., 17.98, 15.9, 15.39],\n ax1.get_children()[1].get_data()[1],\n decimal=2\n )\n\n # test theoretical at some locations\n assert_array_almost_equal(\n [ 2.9 , 10.18, 15.86, 16.07],\n ax1.get_children()[2].get_data()[1][[4, 15, 30, 50]],\n decimal=2\n ) \n\n def test_main_plot_histogram(self):\n V = Variogram(self.c, self.v, n_lags=5, normalize=True)\n\n # build the figure\n fig = V.plot(show=False)\n childs = fig.axes[1].get_children()\n\n # test histogram\n for i, h in zip(range(1, 6), [5262, 4674, 1047, 142, 49]):\n self.assertEqual(childs[i].get_height(), h)\n\n def test_main_plot_no_histogram(self, normalize=True):\n V = Variogram(self.c, self.v, n_lags=5)\n\n # two axes\n fig = V.plot(show=False)\n self.assertEqual(len(fig.axes), 2)\n\n fig = V.plot(hist=False, show=False)\n self.assertEqual(len(fig.axes), 1)\n \n def test_location_trend(self):\n # test that the correct amount of axes is produced\n V = Variogram(self.c, self.v)\n\n fig = V.location_trend(show=False)\n\n self.assertEqual(len(fig.axes), 2)\n\n def test_location_trend_pass_axes(self):\n V = Variogram(self.c, self.v)\n\n fig, axes = plt.subplots(1, 2)\n V.location_trend(axes=axes, show=False)\n\n # test some random y-values\n assert_array_almost_equal(\n [9.06, 5.95, 4.34, 10.91],\n axes[0].get_children()[0].get_data()[1][[4, 16, 100, 140]],\n decimal=2\n )\n\n def test_location_trend_raises(self):\n V = Variogram(self.c, self.v)\n\n with self.assertRaises(ValueError):\n V.location_trend(axes=[0, 1, 2])\n\n def test_distance_difference_plot(self):\n V = Variogram(self.c, self.v, n_lags=4)\n\n fig = V.distance_difference_plot(show=False)\n ax = fig.axes[0]\n \n # test some scatter positions\n assert_array_almost_equal(\n [[14.77, 4.33], [30.11, 7.87], [11.32, 2.63]],\n ax.get_children()[1].get_offsets()[[5, 112, 1337]],\n decimal=2\n )\n\n def test_distance_difference_pass_ax(self):\n V = Variogram(self.c, self.v, n_lags=4)\n\n fig, ax = plt.subplots(1,1)\n V.distance_difference_plot(ax=ax, show=False)\n\n # test some scatter positions\n assert_array_almost_equal(\n [[14.77, 4.33], [30.11, 7.87], [11.32, 2.63]],\n ax.get_children()[1].get_offsets()[[5, 112, 1337]],\n decimal=2\n )\n\n def test_distance_difference_with_bins(self):\n V = Variogram(self.c, self.v, n_lags=4)\n\n fig1 = V.distance_difference_plot(show=False, plot_bins=False)\n fig2 = V.distance_difference_plot(show=False, plot_bins=True)\n\n # there should be one child less\n self.assertEqual(\n len(fig1.axes[0].get_children()),\n len(fig2.axes[0].get_children()) - 1\n )\n\n def test_variogram_default_describe(self):\n V = Variogram(self.c, self.v)\n\n desc = V.describe()\n self.assertTrue('params' in desc.keys())\n self.assertTrue('kwargs' in desc.keys())\n\n def test_variogram_describe_short(self):\n V = Variogram(self.c, self.v)\n\n desc = V.describe(short=True)\n self.assertFalse('params' in desc.keys())\n self.assertFalse('kwargs' in desc.keys())\n\n\n def test_variogram_describe_flat(self):\n V = Variogram(self.c, self.v)\n\n desc = V.describe(flat=True)\n\n # test there are no nested dicts\n self.assertTrue(all([not isinstance(v, dict) for v in desc.values()]))\n\n\nclass TestVariogramPlotlyPlots(unittest.TestCase):\n def setUp(self):\n # set up default values, whenever c and v are not important\n np.random.seed(42)\n self.c = np.random.gamma(10, 4, (150, 2))\n np.random.seed(42)\n self.v = np.random.normal(10, 4, 150)\n self.V = Variogram(self.c, self.v)\n\n def test_plotly_main_plot(self):\n if PLOTLY_FOUND:\n # switch to plotly\n plotting.backend('plotly')\n\n self.assertTrue(\n isinstance(self.V.plot(show=False), go.Figure)\n )\n\n plotting.backend('matplotlib')\n\n def test_plotly_scattergram(self):\n if PLOTLY_FOUND:\n # switch to plotly\n plotting.backend('plotly')\n\n self.assertTrue(\n isinstance(self.V.scattergram(show=False), go.Figure)\n )\n\n plotting.backend('matplotlib')\n\n def test_plotly_location_trend(self):\n if PLOTLY_FOUND:\n # switch to plotly\n plotting.backend('plotly')\n\n self.assertTrue(\n isinstance(self.V.location_trend(show=False), go.Figure)\n )\n\n plotting.backend('matplotlib')\n\n def test_plotly_dd_plot(self):\n if PLOTLY_FOUND:\n # switch to plotly\n plotting.backend('plotly')\n\n self.assertTrue(\n isinstance(self.V.distance_difference_plot(show=False), go.Figure)\n )\n\n plotting.backend('matplotlib')\n \n def test_undefined_backend(self):\n # force the backend into an undefined state\n import skgstat\n skgstat.__backend__ = 'not-a-backend'\n\n for fname in ('plot', 'scattergram', 'location_trend', 'distance_difference_plot'):\n with self.assertRaises(ValueError) as e:\n self.V.plot()\n\n self.assertEqual(\n str(e.exception),\n 'The plotting backend has an undefined state.'\n )\n \n # make the backend valid again\n skgstat.__backend__ = 'matplotlib'\n\n\nclass TestSampling(unittest.TestCase):\n def setUp(self):\n self.data = pd.read_csv(os.path.dirname(__file__) + '/pan_sample.csv')\n\n def test_full_vs_full_sample(self):\n Vf = Variogram(\n self.data[['x', 'y']].values,\n self.data.z.values,\n binning_random_state=44).describe()\n\n Vs = Variogram(\n self.data[['x', 'y']].values,\n self.data.z.values, samples=len(self.data),\n binning_random_state=44).describe()\n\n self.assertAlmostEqual(Vf[\"normalized_effective_range\"], Vs[\"normalized_effective_range\"], delta = Vf[\"normalized_effective_range\"] / 10)\n self.assertAlmostEqual(Vf[\"effective_range\"], Vs[\"effective_range\"], delta = Vf[\"effective_range\"] / 10)\n self.assertAlmostEqual(Vf[\"sill\"], Vs[\"sill\"], delta = Vf[\"sill\"] / 10)\n\n def test_samples(self):\n Vf = Variogram(\n self.data[['x', 'y']].values,\n self.data.z.values, samples=len(self.data),\n binning_random_state=44).describe()\n\n for sample_size in np.linspace(0.5, 1., 10):\n Vs = Variogram(\n self.data[['x', 'y']].values,\n self.data.z.values, samples=sample_size,\n binning_random_state=44).describe()\n \n self.assertAlmostEqual(Vf[\"normalized_effective_range\"], Vs[\"normalized_effective_range\"], delta = Vf[\"normalized_effective_range\"] / 5)\n self.assertAlmostEqual(Vf[\"effective_range\"], Vs[\"effective_range\"], delta = Vf[\"effective_range\"] / 5)\n self.assertAlmostEqual(Vf[\"sill\"], Vs[\"sill\"], delta = Vf[\"sill\"] / 5)\n\n \nclass TestVariogramPickling(unittest.TestCase):\n def setUp(self):\n # set up default values, whenever c and v are not important\n np.random.seed(42)\n self.c = np.random.gamma(10, 4, (150, 2))\n np.random.seed(42)\n self.v = np.random.normal(10, 4, 150)\n\n self.V = Variogram(self.c, self.v, normalize=False)\n\n def test_save_load_pickle(self):\n \"\"\"\n Only test if loading and saving a pickle works without error\n \"\"\"\n pickle.loads(pickle.dumps(self.V))\n return True\n\n\nif __name__ == '__main__': # pragma: no cover\n import os\n os.environ['SKG_SUPRESS'] = 'TRUE'\n unittest.main()\n"
]
| [
[
"numpy.max",
"numpy.random.normal",
"numpy.array",
"numpy.isnan",
"numpy.asarray",
"numpy.random.seed",
"numpy.random.gamma",
"numpy.random.sample",
"matplotlib.pyplot.subplots",
"numpy.testing.assert_array_almost_equal",
"numpy.arange",
"numpy.sqrt",
"numpy.linspace",
"numpy.random.weibull"
]
]
|
NeonJarbas/OVOS-workshop | [
"f309a4ae30cebf5376e92af2b59f65e49187bf8e"
]
| [
"ovos_workshop/frameworks/canvas/opencv_backend.py"
]
| [
"from ovos_utils.messagebus import Message\nfrom ovos_workshop.frameworks.canvas.base import AbstractCanvas\nimport imutils\nimport cv2\nimport numpy as np\n\n\n# TODO move to opm\nclass OpenCVService(AbstractCanvas):\n \"\"\"\n Display backend for opencv package.\n \"\"\"\n def __init__(self, bus, config, name=\"opencv\"):\n super().__init__(bus, config, name)\n self.bus.on(\"ovos.ccanvas.opencv.display\", self._display)\n self.current_image = None\n\n @staticmethod\n def supported_uris():\n \"\"\"\n Returns: list of supported uri types.\n \"\"\"\n return ['file', 'http', 'https', \"numpy\"]\n\n def _display(self, message=None):\n self._prepare_window()\n self._is_displaying = True\n cv2.imshow(\"OpenCV Display\", self.current_image)\n cv2.waitKey(0)\n\n def _prepare_window(self):\n if self._is_displaying:\n cv2.destroyWindow(\"OpenCV Display\")\n\n cv2.namedWindow(\"OpenCV Display\", cv2.WND_PROP_FULLSCREEN)\n if self.fullscreen:\n cv2.setWindowProperty(\"OpenCV Display\", cv2.WND_PROP_FULLSCREEN,\n cv2.WINDOW_FULLSCREEN)\n else:\n cv2.setWindowProperty(\"OpenCV Display\", cv2.WND_PROP_FULLSCREEN,\n not cv2.WINDOW_FULLSCREEN)\n cv2.resizeWindow(\"OpenCV Display\", self.width, self.height)\n\n def handle_display(self, picture):\n path = picture.replace(\"file://\", \"\")\n image = cv2.imread(path)\n image = imutils.resize(image, self.width, self.height)\n self.current_image = image\n self.bus.emit(Message(\"ovos.ccanvas.opencv.display\"))\n\n def handle_fullscreen(self, new_value, old_value):\n # re-render\n self._display()\n\n def handle_height_change(self, new_value, old_value):\n # re-render\n self._display()\n\n def handle_width_change(self, new_value, old_value):\n # re-render\n self._display()\n\n def handle_clear(self):\n \"\"\"\n Clear Display.\n \"\"\"\n # Create a black image\n image = np.zeros((512, 512, 3), np.uint8)\n if not self.fullscreen:\n image = imutils.resize(image, self.width, self.height)\n self.current_image = image\n self._display()\n\n def handle_close(self):\n cv2.destroyAllWindows()\n self._is_displaying = False\n"
]
| [
[
"numpy.zeros"
]
]
|
fvillena/referral_classifier | [
"57a7d63f91a95a4a1301f9a25b2eee22fd6c870c"
]
| [
"src/models/ges_classifier.py"
]
| [
"import sklearn.linear_model\nimport sklearn.svm\nimport sklearn.ensemble\nimport sklearn.neural_network\nimport sklearn.model_selection\nimport numpy as np\nimport json\nimport joblib\n\nmodels = [\n (\n sklearn.linear_model.LogisticRegression(),\n {\n \"C\":np.logspace(-5,5,11),\n \"penalty\":[\"l1\",\"l2\"]\n }\n ),\n (\n sklearn.svm.SVC(),\n {\n 'C':[1,10,100,1000],\n 'gamma':[1,0.1,0.001,0.0001], \n 'kernel':['linear','rbf']\n }\n ),\n (\n sklearn.ensemble.RandomForestClassifier(),\n {\n 'bootstrap': [True, False],\n 'max_depth': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, None],\n 'max_features': ['auto', 'sqrt'],\n 'min_samples_leaf': [1, 2, 4],\n 'min_samples_split': [2, 5, 10],\n 'n_estimators': [200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000]\n }\n ),\n (\n sklearn.neural_network.MLPClassifier(),\n {\n 'hidden_layer_sizes': [(50,50,50), (50,100,50), (100,)],\n 'activation': ['tanh', 'relu'],\n 'solver': ['sgd', 'adam'],\n 'alpha': [0.0001, 0.05],\n 'learning_rate': ['constant','adaptive'],\n }\n )\n]\n\nbest_estimator = sklearn.ensemble.RandomForestClassifier()\nbest_hp = {\n \"n_estimators\": 1600,\n \"min_samples_split\": 5,\n \"min_samples_leaf\": 4,\n \"max_features\": \"auto\",\n \"max_depth\": 100,\n \"bootstrap\": True\n}\n\nnp.random.seed(11)\n\nclass NpEncoder(json.JSONEncoder):\n def default(self, obj): # pylint: disable=E0202\n if isinstance(obj, np.integer):\n return int(obj)\n elif isinstance(obj, np.floating):\n return float(obj)\n elif isinstance(obj, np.ndarray):\n return obj.tolist()\n else:\n return super(NpEncoder, self).default(obj)\n\nclass GesModelTrainer:\n def __init__(self, train_texts, train_ages, train_labels, models = models):\n self.models = models\n self.train_texts = np.load(train_texts)\n self.train_ages = []\n with open(train_ages, encoding='utf-8') as file:\n for line in file:\n line = line.rstrip()\n self.train_ages.append(float(line))\n self.train_ages = np.asarray([self.train_ages]).T\n self.train_labels = []\n with open(train_labels, encoding='utf-8') as file:\n for line in file:\n line = line.rstrip()\n if line == 'True':\n self.train_labels.append(True)\n else:\n self.train_labels.append(False)\n self.train_labels = np.asarray([self.train_labels]).T\n self.train = np.concatenate([self.train_texts, self.train_ages, self.train_labels], axis=1)\n def grid_search(self,n_jobs=4):\n self.gs_scores = {}\n for model in self.models:\n model_name = model[0].__class__.__name__\n estimator = model[0]\n grid = model[1]\n features = self.train[:,:-1]\n labels = self.train[:,-1]\n grid_search = sklearn.model_selection.RandomizedSearchCV(\n estimator=estimator,\n param_distributions=grid,\n scoring='roc_auc',\n n_jobs=n_jobs,\n verbose=2,\n random_state=11,\n return_train_score=True,\n cv=3\n )\n grid_search.fit(features,labels)\n self.gs_scores[model_name] = [grid_search.cv_results_,grid_search.best_params_,grid_search.best_score_]\n def train_models(self, grid_search_results_location,n_jobs):\n self.cv_scores = {}\n for model in self.models:\n model_name = model[0].__class__.__name__\n estimator = model[0]\n with open(grid_search_results_location + model_name + '.json', \"r\") as read_file:\n data = json.load(read_file)\n best_hp=data[1]\n estimator.set_params(**best_hp)\n features = self.train[:,:-1]\n labels = self.train[:,-1]\n cv_scores = sklearn.model_selection.cross_validate(\n estimator=estimator,\n X=features,\n y=labels,\n cv=10,\n n_jobs=n_jobs,\n scoring=['accuracy','f1_weighted', 'precision_weighted', 'recall_weighted', 'roc_auc'],\n verbose=2,\n return_train_score=True\n )\n self.cv_scores[model_name] = cv_scores\n def train_best_model(self,test_texts, test_ages, test_labels,results_location, serialized_model_location,best_estimator=best_estimator,best_hp=best_hp,n_jobs=-1):\n self.test_texts = np.load(test_texts)\n self.test_ages = []\n with open(test_ages, encoding='utf-8') as file:\n for line in file:\n line = line.rstrip()\n self.test_ages.append(float(line))\n self.test_ages = np.asarray([self.test_ages]).T\n self.test_labels = []\n with open(test_labels, encoding='utf-8') as file:\n for line in file:\n line = line.rstrip()\n if line == 'True':\n self.test_labels.append(True)\n else:\n self.test_labels.append(False)\n self.test_labels = np.asarray([self.test_labels]).T\n self.test = np.concatenate([self.test_texts, self.test_ages, self.test_labels], axis=1)\n features_train = self.train[:,:-1]\n labels_train = self.train[:,-1]\n features_test = self.test[:,:-1]\n labels_test = self.test[:,-1]\n estimator = best_estimator\n estimator.set_params(**best_hp,n_jobs=n_jobs,verbose=2)\n estimator.fit(features_train,labels_train)\n joblib.dump(estimator, serialized_model_location)\n predictions_class = estimator.predict(features_test)\n predictions_probs = estimator.predict_proba(features_test)\n self.best_results = np.column_stack([labels_test,predictions_class,predictions_probs])\n np.savetxt(results_location,self.best_results)\n def generate_report(self,report_location):\n for key,val in self.gs_scores.items():\n with open(report_location + 'grid_search' + key + '.json', 'w', encoding='utf-8') as json_file:\n json.dump(val, json_file, indent=2, ensure_ascii=False, cls=NpEncoder)\n for key,val in self.cv_scores.items():\n with open(report_location + 'cross_val/' + key + '.json', 'w', encoding='utf-8') as json_file:\n json.dump(val, json_file, indent=2, ensure_ascii=False, cls=NpEncoder)\n\n"
]
| [
[
"numpy.concatenate",
"numpy.savetxt",
"numpy.asarray",
"numpy.random.seed",
"numpy.load",
"numpy.column_stack",
"numpy.logspace"
]
]
|
chunbo777/letr-sol-koFISH | [
"293916aec4d77fd5f5158bb5957701cb61dab815"
]
| [
"transfer.py"
]
| [
"from tqdm import tqdm\nimport torch\nimport sys\nsys.path.insert(0, \"/home/tf-dev-01/workspace_sol/style-transfer/NLP_text-style-transfer_yc/\")\nfrom bert_pretrained import bert_tokenizer\nfrom bert_pretrained import get_bert_word_embedding\nfrom model import Encoder, Generator\nfrom options import args\n\n\ndef style_transfer(encoder=None, generator=None, text_path=None, n_samples=100):\n # save result if path is given\n if args.transfer_result_save_path is not None:\n fw = open(args.transfer_result_save_path, 'a')\n else:\n fw = None\n\n # interactive mode\n if text_path is None:\n if fw is not None:\n fw.write('\\n' + \"=\" * 50 + '\\n')\n fw.write(\"Interactive transfer from {} -> {}\\n\".format(\n str(1 - args.transfer_to),\n str(args.transfer_to)\n ))\n fw.write(\"=\" * 50 + '\\n')\n try:\n while True:\n fmt = \"Enter text to transfer to style {} (Ctrl+C to exit): \"\n text = input(fmt.format(args.transfer_to))\n tokens = bert_tokenizer.encode(text, add_special_tokens=False)\n tokens = (\n [bert_tokenizer.bos_token_id]\n + tokens\n + [bert_tokenizer.eos_token_id]\n )\n tokens = torch.LongTensor([tokens]).transpose(0, 1)\n original_label = torch.FloatTensor([1 - args.transfer_to])\n output = generate_text(\n encoder.to(args.device),\n generator.to(args.device),\n original_label.to(args.device),\n tokens.to(args.device)\n )\n print(\"Transfer result:\", output)\n if fw is not None:\n fw.write(text + ' -> ' + output + '\\n')\n\n except KeyboardInterrupt:\n if fw is not None:\n fw.close()\n print(\"\\nEnd interactive transfer\\n\")\n\n # load data from text path\n else:\n if fw is not None:\n fw.write('\\n' + \"=\" * 50 + '\\n')\n fw.write(\"Transfer from file: {}\\n\".format(text_path))\n fw.write(\"Number of samples: {}\\n\".format(n_samples))\n fw.write(\"=\" * 50 + '\\n')\n\n pbar = tqdm(total=n_samples)\n counter = 0\n inputs0, inputs1 = [], []\n outputs0, outputs1 = [], []\n with open(text_path, 'r') as text_file:\n for line in text_file:\n counter += 1\n if counter == 1:\n continue\n # if you use baseline model,\n # _, text, label = line.strip().split('\\t')\n for i in range(0,2):\n text=line.strip().split(\",\")[i+1]\n label=i\n \n tokens = bert_tokenizer.encode(text, add_special_tokens=False)\n tokens = (\n [bert_tokenizer.bos_token_id]\n + tokens\n + [bert_tokenizer.eos_token_id]\n )\n tokens = torch.LongTensor([tokens]).transpose(0, 1)\n original_label = torch.FloatTensor([int(label)])\n output = generate_text(\n encoder.to(args.device),\n generator.to(args.device),\n original_label.to(args.device),\n tokens.to(args.device)\n )\n if int(label) == 0:\n inputs0.append(text)\n outputs0.append(output)\n else:\n inputs1.append(text)\n outputs1.append(output)\n pbar.update()\n if fw is not None:\n fw.write(label + ' > ' + str(1-int(label)) + ': '+ text + ' -> ' + output + '\\n')\n if counter > n_samples:\n break\n\n if fw is not None:\n fw.close()\n return inputs0, inputs1, outputs0, outputs1\n\n\ndef generate_text(encoder, generator, original_label, tokens):\n src_len = [len(tokens)]\n predictions = generator.transfer(\n encoder(original_label, tokens, src_len), # hidden state\n 1 - original_label, # transfer label\n eos_token_id=bert_tokenizer.eos_token_id,\n max_len=args.transfer_max_len\n )\n # change this part to first occurence of ber_tokenizer.eos_token_id\n #if predictions[-1] == bert_tokenizer.eos_token_id:\n # predictions = predictions[:-1]\n\n try:\n eos_idx = predictions.index(bert_tokenizer.eos_token_id)\n predictions = predictions[:eos_idx]\n except ValueError:\n predictions=predictions[:-1]\n return bert_tokenizer.decode(predictions)\n\n\ndef _transfer():\n device = torch.device('cuda:{}'.format(args.cuda_device) if torch.cuda.is_available() else 'cpu')\n \n # 1. get model\n embedding = get_bert_word_embedding().to(device).eval()\n encoder = Encoder(embedding, args.dim_y, args.dim_z).to(device).eval()\n generator = Generator(embedding, args.dim_y, args.dim_z, args.temperature, bert_tokenizer.bos_token_id, use_gumbel=args.use_gumbel).to(device).eval()\n \n # 2. load checkpoint\n ckpt = torch.load(args.ckpt_path, map_location=device)\n # embedding.load_state_dict(ckpt['embedding_state_dict'])\n embedding.load_state_dict(ckpt['embedding'])\n encoder.load_state_dict(ckpt['encoder_state_dict'])\n generator.load_state_dict(ckpt['generator_state_dict'])\n \n # 3. transfer!\n if args.transfer_result_save_path is not None:\n fw = open(args.transfer_result_save_path, 'w')\n else:\n fw = None\n \n if args.test_text_path is None:\n # interactive mode\n while True:\n text = input(\"Enter text to transfer to stye {} (Ctrl+C to exit): \".format(args.transfer_to))\n text_tokens = [bert_tokenizer.bos_token_id] + bert_tokenizer.encode(text, add_special_tokens=False) + [bert_tokenizer.eos_token_id]\n text_tokens_tensor = torch.LongTensor([text_tokens]).transpose(0, 1).to(device)\n src_len = [len(text_tokens)]\n original_label = torch.FloatTensor([1-args.transfer_to]).to(device)\n transfer_label = torch.FloatTensor([args.transfer_to]).to(device)\n \n z = encoder(original_label, text_tokens_tensor, src_len)\n predictions = generator.transfer(z, transfer_label, eos_token_id=bert_tokenizer.eos_token_id, max_len=args.transfer_max_len)\n if predictions[-1] == bert_tokenizer.eos_token_id:\n predictions = predictions[:-1]\n \n result = bert_tokenizer.decode(predictions)\n print(\"Transfer Result:\", result)\n if fw is not None:\n fw.write(text + ' -> ' + result + '\\n')\n \n if args.test_recon:\n recon = generator.transfer(z, original_label, eos_token_id=bert_tokenizer.eos_token_id, max_len=args.transfer_max_len)\n if recon[-1] == bert_tokenizer.eos_token_id:\n recon = recon[:-1]\n print(\"Recon:\", bert_tokenizer.decode(recon))\n \n else:\n\n for line in args.test_text_path:\n line = line.strip()\n text = line\n text_tokens = [bert_tokenizer.bos_token_id] + bert_tokenizer.encode(text, add_special_tokens=False) + [bert_tokenizer.eos_token_id]\n text_tokens_tensor = torch.LongTensor([text_tokens]).transpose(0, 1).to(device)\n src_len = [len(text_tokens)]\n original_label = torch.FloatTensor([1-args.transfer_to]).to(device)\n transfer_label = torch.FloatTensor([args.transfer_to]).to(device)\n \n z = encoder(original_label, text_tokens_tensor, src_len)\n predictions = generator.transfer(z, transfer_label, eos_token_id=bert_tokenizer.eos_token_id, max_len=args.transfer_max_len)\n if predictions[-1] == bert_tokenizer.eos_token_id:\n predictions = predictions[:-1]\n \n result = bert_tokenizer.decode(predictions)\n print(\"Transfer Result:\", result)\n if fw is not None:\n fw.write(text + ' -> ' + result + '\\n')\n \n if args.test_recon:\n recon = generator.transfer(z, original_label, eos_token_id=bert_tokenizer.eos_token_id, max_len=args.transfer_max_len)\n if recon[-1] == bert_tokenizer.eos_token_id:\n recon = recon[:-1]\n print(\"Recon:\", bert_tokenizer.decode(recon))\n \nif __name__ == '__main__':\n _transfer()\n"
]
| [
[
"torch.FloatTensor",
"torch.cuda.is_available",
"torch.LongTensor",
"torch.load"
]
]
|
michaelcolman/Sub_cellular_heterogeneity_TOOLKIT | [
"24c90150429a39159e3ebed654d7ef43260a5aff"
]
| [
"Het Toolkit/HetKit_BETA_June_2020/lib/Config_Functions.py"
]
| [
"import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nimport webbrowser\nfrom PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\nfrom lib.Canvas import *\nfrom lib.CanvasVario import *\nfrom lib.CanvasSRF import *\nfrom lib.SRF import *\nfrom lib.channels import channel_splitter\nfrom lib.cropping import crop_data\nfrom lib.rotation import rotate_data\nfrom lib.downsample import downsample_data\nfrom lib.database import *\n\ndef open_webbrowser_config():\n\twebbrowser.open(\"https://github.com/MaxxHolmes/HetKit\")\n\ndef rotate_button(self, mainUI, canvas):\n\n\t# Get Rotation Value\n\n\tmainUI.showData = np.asarray(mainUI.data)\n\tchannel_radio(self, mainUI, canvas)\n\tdegreesValue = mainUI.spinDegrees.value()\n\tmainUI.showData = rotate_data(mainUI.showData, degreesValue)\t\n\tcanvas.replot_showData(mainUI)\n\ndef channel_radio(self, mainUI, canvas):\n\n\t# Get channel value\n\n\tmainUI.showData = np.asarray(mainUI.data)\n\n\tif mainUI.rbRed.isChecked():\n\t\tmainUI.channelValue = \"Red\"\n\telif mainUI.rbGreen.isChecked():\n\t\tmainUI.channelValue = \"Green\"\n\telif mainUI.rbBlue.isChecked():\n\t\tmainUI.channelValue = \"Blue\"\n\telif mainUI.rbAll.isChecked():\n\t\tmainUI.channelValue = \"None\"\n\telse:\n\t\tmainUI.channelValue = \"None\"\n\n\tmainUI.showData = channel_splitter(mainUI.showData, mainUI.channelValue)\n\tcanvas.replot_showData(mainUI)\n\ndef apply_button(self, mainUI, canvas):\n\n\t# Get Channel Value\n\n\tif mainUI.rbRed.isChecked():\n\t\tmainUI.channelValue = \"Red\"\n\telif mainUI.rbGreen.isChecked():\n\t\tmainUI.channelValue = \"Green\"\n\telif mainUI.rbBlue.isChecked():\n\t\tmainUI.channelValue = \"Blue\"\n\telif mainUI.rbAll.isChecked():\n\t\tmainUI.channelValue = \"None\"\n\telse:\n\t\tmainUI.channelValue = \"None\"\n\n\t# Get Rotation Value\n\n\tdegreesValue = mainUI.spinDegrees.value()\n\n\t# Get Downsampling Values\n\n\ttry:\n\t\tDSImageX = float(mainUI.entryX1.text())\n\t\tDSImageY = float(mainUI.entryY1.text())\n\t\tDSNewX = float(mainUI.entryX2.text())\n\t\tDSNewY = float(mainUI.entryY2.text())\n\n\texcept:\n\t\tDSImageX = 1.0\n\t\tDSImageY = 1.0\n\t\tDSNewX = 1.0\n\t\tDSNewY = 1.0\n\n\t# Get Crop Values\n\ttry:\n\t\tmainUI.X1 = int(canvas.x1)\n\t\tmainUI.X2 = int(canvas.x2)\n\t\tmainUI.Y1 = int(canvas.y1)\n\t\tmainUI.Y2 = int(canvas.y2)\n\texcept:\n\t\tmainUI.X1 = 1.0\n\t\tmainUI.X2 = 1.0\n\t\tmainUI.Y1 = 1.0\n\t\tmainUI.Y2 = 1.0\n\n\tcurrent_data = np.asarray(mainUI.data)\n\tcurrent_data = channel_splitter(current_data, mainUI.channelValue)\n\tcurrent_data = rotate_data(current_data, degreesValue)\n\tcurrent_data = crop_data(current_data, mainUI.X1, mainUI.X2, mainUI.Y1, mainUI.Y2)\n\tcurrent_data = downsample_data(current_data, DSNewX, DSNewY, DSImageX, DSImageY)\n\n\tmainUI.newData = current_data\n\tcanvas.replot_apply(mainUI)\n\tmainUI.labelCoords.setText(\"Co-ordinates:\t({}, {}), ({}, {})\".format(mainUI.X1, mainUI.Y1, mainUI.X2, mainUI.Y2))\n\n\tmainUI.DB[mainUI.ID][\"Channel\"] = mainUI.channelValue\n\tmainUI.DB[mainUI.ID][\"Rotation Angle\"] = mainUI.spinDegrees.value()\n\n\tmainUI.DB[mainUI.ID][\"Crop X1\"] = int(mainUI.X1)\n\tmainUI.DB[mainUI.ID][\"Crop X2\"] = int(mainUI.X2)\n\tmainUI.DB[mainUI.ID][\"Crop Y1\"] = int(mainUI.Y1)\n\tmainUI.DB[mainUI.ID][\"Crop Y2\"] = int(mainUI.Y2)\n\n\ttry:\n\t\tmainUI.DB[mainUI.ID][\"Scale X\"] = float(mainUI.entryX1.text())\n\t\tmainUI.DB[mainUI.ID][\"Scale Y\"] = float(mainUI.entryY1.text())\n\t\tmainUI.DB[mainUI.ID][\"Downsample X\"] = float(mainUI.entryX2.text())\n\t\tmainUI.DB[mainUI.ID][\"Downsample Y\"] = float(mainUI.entryY2.text())\n\texcept:\n\t\tmainUI.DB[mainUI.ID][\"Scale X\"] = 1.0\n\t\tmainUI.DB[mainUI.ID][\"Scale Y\"] = 1.0\n\t\tmainUI.DB[mainUI.ID][\"Downsample X\"] = 1.0\n\t\tmainUI.DB[mainUI.ID][\"Downsample Y\"] = 1.0\n\n\tsave_database(mainUI.DB)\n\n\ndef reset_button(self, mainUI, canvas):\n\n\tcanvas.replot_reset(mainUI)\n\ndef config_continue_button(self, mainUI, canvasVario):\n\n\tmainUI.DB[mainUI.ID][\"Channel\"] = mainUI.channelValue\n\tmainUI.DB[mainUI.ID][\"Rotation Angle\"] = mainUI.spinDegrees.value()\n\tmainUI.DB[mainUI.ID][\"Crop X1\"] = int(mainUI.X1)\n\tmainUI.DB[mainUI.ID][\"Crop X2\"] = int(mainUI.X2)\n\tmainUI.DB[mainUI.ID][\"Crop Y1\"] = int(mainUI.Y1)\n\tmainUI.DB[mainUI.ID][\"Crop Y2\"] = int(mainUI.Y2)\n\tmainUI.DB[mainUI.ID][\"Scale X\"] = float(mainUI.entryX1.text())\n\tmainUI.DB[mainUI.ID][\"Scale Y\"] = float(mainUI.entryY1.text())\n\tmainUI.DB[mainUI.ID][\"Downsample X\"] = float(mainUI.entryX2.text())\n\tmainUI.DB[mainUI.ID][\"Downsample Y\"] = float(mainUI.entryY2.text())\n\tsave_database(mainUI.DB)\n\n\tproduce_preview_graphic_vario(mainUI.newData)\t\n\tcanvasVario.reload_plot()\n\n\tmainUI.tabWidget.setCurrentIndex(2)\n\ndef stack_slider(self, mainUI, canvas):\n\n\tmainUI.labelStack.setText(\"Current Image in Stack: {}\".format(mainUI.sliderStack.value() + 1))\n\timg = Image.open(mainUI.dataPathList[mainUI.sliderStack.value()])\n\timg.load()\n\tmainUI.data = np.asarray(img, dtype = \"int32\")\n\tcanvas.replot_reset(mainUI)\n\n\n"
]
| [
[
"numpy.asarray"
]
]
|
dtsukiyama/SageMaker | [
"962c5ce4e060b59e0042bee2eaac87cd4c18425c"
]
| [
"notebooks/custom_estimator.py"
]
| [
"\nimport numpy as np\nimport os\nimport tensorflow as tf\nfrom tensorflow.python.estimator.export.export import build_raw_serving_input_receiver_fn\nfrom tensorflow.python.estimator.export.export_output import PredictOutput\n\n\nINPUT_TENSOR_NAME = \"inputs\"\nSIGNATURE_NAME = \"serving_default\"\nLEARNING_RATE = 0.001\n\n\ndef model_fn(features, labels, mode, params):\n \n first_hidden_layer = tf.keras.layers.Dense(128, activation='relu', name='first-layer')(features[INPUT_TENSOR_NAME])\n second_hidden_layer = tf.keras.layers.Dense(256, activation='relu')(first_hidden_layer)\n logits = tf.keras.layers.Dense(20)(second_hidden_layer)\n\n predicted_classes = tf.argmax(logits, axis=1)\n\n # Provide an estimator spec for `ModeKeys.PREDICT`.\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(\n mode=mode,\n predictions = {\n 'class_ids': predicted_classes[:, tf.newaxis],\n 'probabilities': tf.nn.softmax(logits),\n 'logits': logits,},\n export_outputs={SIGNATURE_NAME: PredictOutput({\"jobs\": predicted_classes})})\n\n # 2. Define the loss function for training/evaluation using Tensorflow.\n loss = tf.losses.sparse_softmax_cross_entropy(tf.cast(labels, dtype=tf.int32), logits)\n\n # 3. Define the training operation/optimizer using Tensorflow operation/optimizer.\n train_op = tf.contrib.layers.optimize_loss(\n loss=loss,\n global_step=tf.contrib.framework.get_global_step(),\n learning_rate=params[\"learning_rate\"],\n optimizer=\"Adam\")\n\n # 4. Generate predictions as Tensorflow tensors.\n predictions_dict = {\"jobs\": predicted_classes,\n \"classes\": logits}\n\n # 5. Generate necessary evaluation metrics.\n # Calculate root mean squared error as additional eval metric\n eval_metric_ops = {\n \"accuracy\": tf.metrics.accuracy(labels, predicted_classes)\n }\n\n # Provide an estimator spec for `ModeKeys.EVAL` and `ModeKeys.TRAIN` modes.\n return tf.estimator.EstimatorSpec(\n mode=mode,\n loss=loss,\n train_op=train_op,\n eval_metric_ops=eval_metric_ops)\n \n\ndef serving_input_fn(params):\n inputs = {INPUT_TENSOR_NAME: tf.placeholder(tf.float32, [None, 500])}\n return tf.estimator.export.ServingInputReceiver(inputs, inputs)\n\n\nparams = {\"learning_rate\": LEARNING_RATE}\n\n\ndef train_input_fn(training_dir, params):\n return _input_fn(training_dir, 'post_train.csv')\n\n\ndef eval_input_fn(training_dir, params):\n return _input_fn(training_dir, 'post_test.csv')\n\n\ndef _input_fn(training_dir, training_filename):\n training_set = tf.contrib.learn.datasets.base.load_csv_without_header(\n filename=os.path.join(training_dir, training_filename), target_dtype=np.int, features_dtype=np.float32)\n\n return tf.estimator.inputs.numpy_input_fn(\n x={INPUT_TENSOR_NAME: np.array(training_set.data)},\n y=np.array(training_set.target),\n num_epochs=None,\n shuffle=True)()\n"
]
| [
[
"numpy.array",
"tensorflow.estimator.EstimatorSpec",
"tensorflow.argmax",
"tensorflow.keras.layers.Dense",
"tensorflow.estimator.export.ServingInputReceiver",
"tensorflow.python.estimator.export.export_output.PredictOutput",
"tensorflow.metrics.accuracy",
"tensorflow.placeholder",
"tensorflow.nn.softmax",
"tensorflow.cast",
"tensorflow.contrib.framework.get_global_step"
]
]
|
dham/randomgen | [
"27bd211682775964e6ef87f7d3191a24fe8a88dc"
]
| [
"benchmark.py"
]
| [
"import os\nimport struct\nimport timeit\n\nimport numpy as np\nimport pandas as pd\nfrom numpy.random import RandomState\n\nrs = RandomState()\n\nSETUP = '''\nimport numpy as np\nif '{brng}' == 'numpy':\n import numpy.random\n rg = numpy.random.RandomState()\nelse:\n from randomgen import RandomGenerator, {brng}\n rg = RandomGenerator({brng}())\nrg.random_sample()\n'''\n\nscale_32 = scale_64 = 1\nif struct.calcsize('P') == 8 and os.name != 'nt':\n # 64 bit\n scale_32 = 0.5\nelse:\n scale_64 = 2\n\nPRNGS = ['DSFMT', 'PCG64', 'PCG32', 'MT19937', 'Xoroshiro128', 'Xorshift1024',\n 'Xoshiro256StarStar', 'Xoshiro512StarStar', 'Philox', 'ThreeFry',\n 'ThreeFry32', 'numpy']\n\n\ndef timer(code, setup):\n return 1000 * min(timeit.Timer(code, setup=setup).repeat(10, 10)) / 10.0\n\n\ndef print_legend(legend):\n print('\\n' + legend + '\\n' + '*' * max(60, len(legend)))\n\n\ndef run_timer(command, numpy_command=None, setup='', random_type=''):\n print('-' * 80)\n if numpy_command is None:\n numpy_command = command\n\n res = {}\n for brng in PRNGS:\n cmd = numpy_command if brng == 'numpy' else command\n res[brng] = timer(cmd, setup=setup.format(brng=brng))\n\n s = pd.Series(res)\n t = s.apply(lambda x: '{0:0.2f} ms'.format(x))\n print_legend('Time to produce 1,000,000 ' + random_type)\n print(t.sort_index())\n\n p = 1000.0 / s\n p = p.apply(lambda x: '{0:0.2f} million'.format(x))\n print_legend(random_type + ' per second')\n print(p.sort_index())\n\n baseline = [k for k in p.index if 'numpy' in k][0]\n p = 1000.0 / s\n p = p / p[baseline] * 100 - 100\n p = p.drop(baseline, 0)\n p = p.apply(lambda x: '{0:0.1f}%'.format(x))\n print_legend('Speed-up relative to NumPy')\n print(p.sort_index())\n print('-' * 80)\n\n\ndef timer_raw():\n command = 'rg._basicrng.random_raw(size=1000000, output=False)'\n info = np.iinfo(np.int32)\n command_numpy = 'rg.random_integers({max},size=1000000)'\n command_numpy = command_numpy.format(max=info.max)\n run_timer(command, command_numpy, SETUP, 'Raw Values')\n\n\ndef timer_uniform():\n command = 'rg.random_sample(1000000)'\n run_timer(command, None, SETUP, 'Uniforms')\n\n\ndef timer_bounded(bits=8, max=95, use_masked=True):\n \"\"\"\n Timer for 8-bit bounded values.\n\n Parameters\n ----------\n bits : {8, 16, 32, 64}\n Bit width of unsigned output type\n max : int\n Upper bound for range. Lower is always 0. Must be <= 2**bits.\n use_masked: bool\n If True, masking and rejection sampling is used to generate a random\n number in an interval. If False, Lemire's algorithm is used if\n available to generate a random number in an interval.\n\n Notes\n -----\n Lemire's algorithm has improved performance when {max}+1 is not a\n power of two.\n \"\"\"\n if bits not in (8, 16, 32, 64):\n raise ValueError('bits must be one of 8, 16, 32, 64.')\n minimum = 0\n\n if use_masked: # Use masking & rejection.\n command = 'rg.randint({min}, {max}+1, 1000000, dtype=np.uint{bits}, use_masked=True)'\n else: # Use Lemire's algo.\n command = 'rg.randint({min}, {max}+1, 1000000, dtype=np.uint{bits}, use_masked=False)'\n\n command = command.format(min=minimum, max=max, bits=bits)\n\n command_numpy = 'rg.randint({min}, {max}+1, 1000000, dtype=np.uint{bits})'\n command_numpy = command_numpy.format(min=minimum, max=max, bits=bits)\n\n run_timer(command, command_numpy, SETUP,\n '{bits}-bit bounded unsigned integers (max={max}, '\n 'use_masked={use_masked})'.format(max=max, use_masked=use_masked, bits=bits))\n\n\ndef timer_32bit():\n info = np.iinfo(np.uint32)\n minimum, maximum = info.min, info.max\n command = 'rg.randint(2**32, size=1000000, dtype=\\'uint32\\')'\n command_numpy = 'rg.randint({min}, {max}+1, 1000000, dtype=np.uint32)'\n command_numpy = command_numpy.format(min=minimum, max=maximum)\n run_timer(command, command_numpy, SETUP, '32-bit unsigned integers')\n\n\ndef timer_64bit():\n info = np.iinfo(np.uint64)\n minimum, maximum = info.min, info.max\n command = 'rg.randint(2**64, size=1000000, dtype=\\'uint64\\')'\n command_numpy = 'rg.randint({min}, {max}+1, 1000000, dtype=np.uint64)'\n command_numpy = command_numpy.format(min=minimum, max=maximum)\n run_timer(command, command_numpy, SETUP, '64-bit unsigned integers')\n\n\ndef timer_normal_zig():\n command = 'rg.standard_normal(1000000)'\n command_numpy = 'rg.standard_normal(1000000)'\n run_timer(command, command_numpy, SETUP, 'Standard normals (Ziggurat)')\n\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-f', '--full',\n help='Run benchmarks for a wide range of distributions.'\n ' If not provided, only tests the production of '\n 'uniform values.',\n dest='full', action='store_true')\n parser.add_argument('-bi', '--bounded-ints',\n help='Included benchmark coverage of the bounded '\n 'integer generators in a full run.',\n dest='bounded_ints', action='store_true')\n args = parser.parse_args()\n\n timer_uniform()\n if args.full:\n timer_raw()\n if args.bounded_ints:\n timer_bounded(use_masked=True)\n timer_bounded(max=64, use_masked=False) # Worst case for Numpy.\n timer_bounded(max=95, use_masked=False) # Typ. avrg. case for Numpy.\n timer_bounded(max=127, use_masked=False) # Best case for Numpy.\n\n timer_bounded(16, use_masked=True)\n timer_bounded(16, max=1024, use_masked=False) # Worst case for Numpy.\n timer_bounded(16, max=1535, use_masked=False) # Typ. avrg. case for Numpy.\n timer_bounded(16, max=2047, use_masked=False) # Best case for Numpy.\n\n timer_32bit()\n\n if args.bounded_ints:\n timer_bounded(32, use_masked=True)\n timer_bounded(32, max=1024, use_masked=False) # Worst case for Numpy.\n timer_bounded(32, max=1535, use_masked=False) # Typ. avrg. case for Numpy.\n timer_bounded(32, max=2047, use_masked=False) # Best case for Numpy.\n\n timer_64bit()\n\n if args.bounded_ints:\n timer_bounded(64, use_masked=True)\n timer_bounded(64, max=1024, use_masked=False) # Worst case for Numpy.\n timer_bounded(64, max=1535, use_masked=False) # Typ. avrg. case for Numpy.\n timer_bounded(64, max=2047, use_masked=False) # Best case for Numpy.\n\n timer_normal_zig()\n"
]
| [
[
"numpy.iinfo",
"pandas.Series",
"numpy.random.RandomState"
]
]
|
Alex05101997/morpheus | [
"9215e6f5ca498f1cdace6faaef41bc646225cf68"
]
| [
"svm.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 24 00:06:11 2019\n\n@author: Alex\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report, confusion_matrix\n\ndf = pd.read_excel(\"features.xlsx\",sheet_name=\"MFCC\")\n#print(df)\nX = df.drop('Class',axis=1)\n#print(X)\ny = df['Class']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.40)\n\nclf = SVC(C=5000,kernel='linear')\nclf.fit(X_train, y_train)\n\ny_pred = clf.predict(X_test)\n\nprint(confusion_matrix(y_test,y_pred))\nprint(classification_report(y_test,y_pred))\n"
]
| [
[
"sklearn.metrics.confusion_matrix",
"pandas.read_excel",
"sklearn.svm.SVC",
"sklearn.metrics.classification_report",
"sklearn.model_selection.train_test_split"
]
]
|
steinermg/ion-functions | [
"cea532ad9af51e86768572c8deb48547d99567c5"
]
| [
"ion_functions/data/test/test_met_functions.py"
]
| [
"#!/usr/bin/env python\n\"\"\"\n@package ion_functions.test.met_functions\n@file ion_functions/test/met_functions.py\n@author Russell Desiderio, Chris Wingard\n@brief Unit tests for met_functions module\n\"\"\"\n\nfrom nose.plugins.attrib import attr\nfrom ion_functions.test.base_test import BaseUnitTestCase\n\nimport numpy as np\nimport datetime as dt\nimport os\n\nimport ion_functions.data.met_functions as mb\n\n\"\"\"\n List of tests:\n\n L2 on an hour time base (for netsirr see L1)\n test_met_buoyfls\n test_met_buoyflx\n test_met_frshflx\n test_met_heatflx\n test_met_latnflx\n test_met_mommflx\n test_met_netlirr\n test_met_rainflx\n test_met_sensflx\n test_met_sphum2m\n test_met_stablty\n test_met_tempa2m\n test_met_tempskn\n test_met_wind10m\n\n L2 on a minute time base\n test_met_heatflx_minute\n test_met_latnflx_minute\n test_met_netlirr_minute\n test_met_sensflx_minute\n\n L1\n test_met_barpres\n test_met_netsirr\n test_met_netsirr_hourly\n test_met_rainrte\n test_met_salsurf\n test_met_spechum\n\n Current and Wind\n test_met_current_direction\n test_met_current_speed\n test_met_relwind_direction\n test_met_relwind_speed\n test_met_windavg\n\n Time\n test_make_hourly_data\n test_met_timeflx\n test_multiple_days\n test_time_calcs_with_actual_metbk_data\n test_warmlayer_time_keys\n\n Misc\n test_rain_heat_flux\n test_time_vectorized_heights_and_switches\n\"\"\"\n\n\n@attr('UNIT', group='func')\nclass TestMetFunctionsUnit(BaseUnitTestCase):\n\n def setUp(self):\n \"\"\"\n \"SCALAR\" TESTSET of 3-element vector data\n First values are selected for the scalar tests.\n All 3 values are selected for L2 perminute data product tests.\n\n These test values are adapted from array indices 1356, 1357, and\n 1358 from the test dataset Revelle10minutesLeg3_r3.mat, from\n ftp://ftp.etl.noaa.gov/users/cfairall/bulkalg/cor3_5/.\n\n They were chosen because 1357 had significant Solar, IR, and Rainrate\n sensor values. The first time record was changed so that a local time\n (which is a function of longitude) earlier than 6:00 AM would result\n so that the warmlayer code would run and give non-trivial results; time\n records were initially spaced 600 seconds apart, but were changed to\n be 60 seconds apart so that unit tests for the L2 minute data products\n could be easily constructed. The timestamps are not used when scalar\n data are processed.\n\n The vectorized warmlayer tests producing hourly data do NOT use the\n 3-element scalar testset data as inputs.\n\n Sensor heights are changed so that:\n (1) they are not all the same.\n (2) so that wind sensor height is not the same as that specified\n for the derived wind data product reference height (10m).\n (3) ctd temperature sensor depth changed from 0.050 m to what\n would be a more realistic OOI mooring deployment depth.\n (4) 40deg subtracted from longitude (to compare to original matlab\n warmlayer code results; that code had a time artifact in the\n calculation of local time).\n \"\"\"\n tC_sea = np.array([31.125, 31.033, 31.022])\n wnd = np.array([4.805, 3.396, 3.843])\n tC_air = np.array([28.220, 27.961, 27.670])\n relhum = np.array([79.47, 82.30, 82.72])\n timestamp = np.array([2200.0, 2260.0, 2320.0])\n lon = np.array([80.5, 80.6, 80.7]) - 40.0\n ztmpwat = 1.5\n zwindsp = 8.0\n ztmpair = 5.0\n zhumair = 4.0\n lat = np.array([0.1, 1.1, 2.1])\n pr_air = np.array([1005.1, 1006.2, 1007.3])\n Rshort_down = np.array([572.7, 659.0, 634.0])\n Rlong_down = np.array([443.3, 456.0, 441.9])\n rain_rate = np.array([0.0, 17.3, 1.5]) # for scalar test input\n cm_prcp = np.array([0.0, 17.3, 18.8])/60 # for L2 minute product tests\n zinvpbl = 600.0\n\n \"\"\"\n Even though the OOI METBK data products will always be computed with\n jwarm = jcool = 1, the more basic test cases (jwarm=0 especially) need\n to be checked first.\n\n Because jwarm=1 requires at least 2 values to give non-trivial output\n (with respect to the warmlayer calculation), no scalar tests can be\n done to test the warmlayer routine.\n\n Package the input arguments into tuples for convenience in calling\n the routines to be tested.\n \"\"\"\n self.kk = 0 # so that any one of the 3 records can be easily selected\n # NOTE that the correct scalar results for data products involving rain will\n # only be obtained for self.kk=0, because by definition if there is only one\n # value for cumulative precipitation, then the rain rate is 0.\n\n # for scalar unit tests\n self.args_scalar_inputs = (tC_sea[self.kk],\n wnd[self.kk],\n tC_air[self.kk],\n relhum[self.kk],\n timestamp[self.kk],\n lon[self.kk],\n ztmpwat,\n zwindsp,\n ztmpair,\n zhumair,\n lat[self.kk],\n pr_air[self.kk],\n Rshort_down[self.kk],\n Rlong_down[self.kk],\n rain_rate[self.kk],\n zinvpbl)\n\n # for L2 perminute unit tests\n self.args_permin_inputs = (tC_sea,\n wnd,\n tC_air,\n relhum,\n timestamp,\n lon,\n ztmpwat,\n zwindsp,\n ztmpair,\n zhumair,\n lat,\n pr_air,\n Rshort_down,\n Rlong_down,\n cm_prcp,\n zinvpbl)\n\n \"\"\"\n \"VECTOR\" TESTSET for L2 products producing hourly data:\n\n The vector testset was constructed so that when processed into hourly data,\n it will give the scalar testset above. The timestamps were changed to span\n 3 hours of data, such that the first 12 stamps occurred within the first hour,\n the next 8 the second, the last 10 the third. (The make_hourly_data routine was\n written to take into account the sporadic nature of the METBK sensor output,\n which is roughly once a minute but is usually greater than 60 sec with a value\n around 30 sec thrown in once every 5-ish values). The rain_rate data was replaced\n by cumulative precipitation data because this was required on input by the DPAs.\n (If the RAINRTE data product were to be specified as an input, the current CI\n model would broadcast this per hour data product at the timing of the raw inputs\n (per minute-ish); better to calculate rain rate fresh within the DPA itself).\n\n The test for the make_hourly_data routine takes as input the following vector\n testset data and should produce the scalar testset data.\n \"\"\"\n # roughly 6-minute input, to be made into hourly testset.\n # Note that the time points are not evenly spaced; and, there are\n # 12 points in the 1st hour, 8 in the second, and 10 in the last.\n self.tC_sea = np.array([33.162, 30.446, 30.899, 29.540, 32.257,\n 31.351, 33.615, 29.993, 28.635, 31.804,\n 29.088, 32.710, 27.930, 34.136, 28.816,\n 31.476, 29.703, 33.250, 32.363, 30.590,\n 33.194, 30.298, 29.333, 31.746, 32.711,\n 28.850, 32.228, 29.816, 31.263, 30.781])\n\n self.wnd = np.array([5.189, 4.910, 4.421, 4.630, 4.700, 4.840, 4.980, 5.120, 4.490, 4.560,\n 5.050, 4.770, 3.639, 3.056, 3.542, 3.250, 3.347, 3.736, 3.153, 3.445,\n 4.112, 4.052, 3.813, 3.933, 3.634, 3.753, 3.694, 3.873, 3.992, 3.574])\n\n self.tC_air = np.array([26.373, 29.246, 29.657, 28.425, 27.604,\n 30.067, 28.015, 25.962, 27.194, 30.478,\n 26.783, 28.836, 28.360, 27.562, 25.165,\n 29.958, 26.763, 25.964, 30.757, 29.159,\n 26.164, 25.733, 27.455, 27.885, 28.316,\n 29.607, 28.746, 26.594, 29.176, 27.024])\n\n self.relhum = np.array([78.892, 74.268, 75.424, 83.516, 85.828,\n 80.048, 77.736, 82.360, 73.112, 84.672,\n 81.204, 76.580, 83.476, 90.530, 88.179,\n 81.124, 76.421, 85.827, 74.070, 78.773,\n 79.503, 85.937, 80.790, 83.363, 88.510,\n 87.224, 82.077, 84.650, 78.216, 76.930])\n\n self.timestamp = np.array([864400.0, 864760.0, 865120.0, 865300.0, 865840.0,\n 865984.0, 866200.0, 866560.0, 867172.0, 867568.0,\n 867640.0, 867820.0, 868360.0, 868828.0, 869224.0,\n 869728.0, 870160.0, 870520.0, 871204.0, 871312.0,\n 871960.0, 872320.0, 872680.0, 873040.0, 873400.0,\n 873760.0, 874120.0, 874480.0, 874840.0, 875164.0])\n\n self.lon = np.array([40.205, 43.740, 38.438, 43.151, 39.616,\n 41.384, 37.849, 40.795, 42.562, 37.260,\n 41.973, 39.027, 37.700, 42.340, 41.180,\n 44.660, 36.540, 43.500, 38.860, 40.020,\n 39.750, 38.484, 40.383, 41.650, 43.549,\n 42.283, 37.851, 39.117, 42.916, 41.017])\n\n ztmpwat = 1.5\n zwindsp = 8.0\n ztmpair = 5.0\n zhumair = 4.0\n\n self.lat = np.array([0.098, 0.099, 0.095, 0.101, 0.102, 0.104, 0.096, 0.105, 0.107, 0.092,\n 0.093, 0.108, 1.084, 0.990, 1.210, 1.179, 1.116, 1.021, 1.147, 1.053,\n 2.051, 2.116, 1.986, 2.182, 2.018, 2.084, 1.953, 2.214, 2.149, 2.247])\n\n self.pr_air = np.array([1027.029, 968.551, 983.171, 1070.888, 997.790,\n 939.312, 1041.649, 924.692, 1085.508, 1012.410,\n 953.931, 1056.269, 934.329, 1020.574, 1106.820,\n 905.580, 1049.323, 991.826, 1078.071, 963.077,\n 983.796, 1077.811, 1046.473, 1015.135, 999.465,\n 936.789, 1062.142, 952.458, 968.127, 1030.804])\n\n self.Rshort_down = np.array([526.884, 568.535, 618.516, 576.865, 585.195,\n 593.525, 610.186, 535.214, 543.544, 560.205,\n 601.856, 551.875, 668.414, 630.757, 611.929,\n 706.071, 649.586, 593.100, 724.900, 687.243,\n 609.344, 668.518, 619.207, 658.656, 629.069,\n 648.793, 599.482, 589.620, 678.380, 638.931])\n\n self.Rlong_down = np.array([407.836, 465.868, 459.420, 472.316, 433.628,\n 414.284, 446.524, 420.732, 452.972, 478.764,\n 440.076, 427.180, 423.429, 462.514, 436.457,\n 475.543, 449.486, 410.400, 488.571, 501.600,\n 410.967, 445.337, 424.715, 438.463, 459.085,\n 465.959, 431.589, 472.833, 417.841, 452.211])\n\n self.cumu_prcp = np.array([0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00,\n 0.00, 0.00, 16.25, 16.55, 16.85, 17.15, 17.45, 17.75, 18.05, 18.35,\n 18.35, 18.45, 18.55, 18.65, 18.75, 18.85, 18.95, 19.05, 19.15, 19.25])\n\n zinvpbl = 600.0\n\n self.args_vector_inputs = (self.tC_sea,\n self.wnd,\n self.tC_air,\n self.relhum,\n self.timestamp,\n self.lon,\n ztmpwat,\n zwindsp,\n ztmpair,\n zhumair,\n self.lat,\n self.pr_air,\n self.Rshort_down,\n self.Rlong_down,\n self.cumu_prcp,\n zinvpbl)\n\n # construct argument list to test time_vectorization of sensor heights.\n # The DPAs were originally written without time vectorization of sensor\n # heights, nor of the jcool and jwarm switches.\n self.npts = self.lat.shape[0]\n self.args_vector_ztmvec = (self.tC_sea,\n self.wnd,\n self.tC_air,\n self.relhum,\n self.timestamp,\n self.lon,\n np.tile(ztmpwat, self.npts),\n np.tile(zwindsp, self.npts),\n np.tile(ztmpair, self.npts),\n np.tile(zhumair, self.npts),\n self.lat,\n self.pr_air,\n self.Rshort_down,\n self.Rlong_down,\n self.cumu_prcp,\n np.tile(zinvpbl, self.npts))\n\n # construct sets of arguments to test warmlayer_time_keys.py (placement of nans\n # in output when a day's data does not start before sunrise, taken to be 6AM).\n #\n # all 3 days represented by ts_3days do presently start before 6AM;\n # also, do not need to append values for jwarm and jcool\n ts_3days = np.hstack((self.timestamp, self.timestamp+86400.0, self.timestamp+2*86400.0))\n self.args_multiple_days = (np.tile(self.tC_sea, 3),\n np.tile(self.wnd, 3),\n np.tile(self.tC_air, 3),\n np.tile(self.relhum, 3),\n ts_3days,\n np.tile(self.lon, 3),\n ztmpwat,\n zwindsp,\n ztmpair,\n zhumair,\n np.tile(self.lat, 3),\n np.tile(self.pr_air, 3),\n np.tile(self.Rshort_down, 3),\n np.tile(self.Rlong_down, 3),\n np.tile(self.cumu_prcp, 3),\n zinvpbl)\n\n # the next 3 sets of values are not currently used in the unit tests.\n self.relwinddir = np.array([122.5, 118.5, 120.5, 114.5, 119.5, 116.5, 123.5, 124.5, 115.5, 125.5,\n 121.5, 117.5, 206.5, 212.5, 208.5, 213.5, 207.5, 210.5, 209.5, 211.5,\n 296.5, 300.5, 295.5, 303.5, 304.5, 299.5, 298.5, 302.5, 301.5, 297.5])\n\n self.vle_water = np.array([0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2,\n 0.2, 0.2, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3,\n 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4])\n\n self.vln_water = self.vle_water + 0.3\n\n \"\"\"\n Tests for data products requiring coolskin and warmlayer corrections.\n\n Description\n\n Matlab programs were written to generate unit test data for these data products.\n The programs compared values calculated from reference coare version 3.5 matlab code\n and a refactored matlab code. The refactored code calculates two versions of the\n data products: (1) 'old', which are calculated the same as in the reference code;\n and (2) 'new', where the matlab code incorporated the changes to be made in the OOI\n DPA implementation in python (examples: the celsius to kelvin conversion constant was\n corrected from 273.16 to 273.15; more significantly, the rain heat flux calculation\n was corrected). For each of these data products, the reference values generated\n by the original unchanged code were checked against the 'old' values given by the\n refactored code to make sure they were identical. The 'new' values calculated by\n the refactored code were then incorporated as the target test values for the python\n code to calculate.\n\n The coolskin\\warmlayer 'xpctd' arrays are dimensioned as 4 x 3:\n {4 permutations of the [jwarm,jcool] switches} x {3 hourly data points}\n The switch assignments as a function of row are:\n jwarm jcool\n row 1 0 0\n row 2 0 1\n row 3 1 0\n row 4 1 1\n\n Implemented by:\n\n 2014-09-13: Russell Desiderio. Initial Code.\n 2014-09-20: Russell Desiderio. Added tests of DPAs on sub-hourly testdata.\n 2014-10-28: Russell Desiderio. New derivation of rain heat flux coded.\n 2014-10-29: Russell Desiderio. Incorporated new unit test values for all data products\n using warmlayer algorithm (which uses rain heat flux).\n 2014-12-29: Russell Desiderio. Incorporated tests on Irminger METBK data.\n 2015-07-13: Russell Desiderio. Incorporated tests using time-vectorized input for sensor\n heights and algorithm switches; tested only met_latnflx as a proxy for all\n the functions using the coolskin\\warmlayer algorithm.\n 2015-10-26: Russell Desiderio. Expanded tests developed on 7-13 to test all data products\n using the coolskin\\warmlayer algorithm (fixes problem exposed in redmine ticket\n #8592).\n\n Also fixed test_met_mommflx within this test module, which had been named\n met_mommflx, so that up to this time the met_mommflx unit test function had\n never been run. The unit test values turned out to be old values (probably\n before the new rain heat flux code was written). The procedure detailed in\n the Description section above was followed to generate the present unit test\n values from the matlab code, which do agree with the python DPA code results.\n 2017-02-03: Russell Desiderio. Added [jwarm,jcool] switch documentation as a function of row\n in the Description section above.\n Added test_met_netsirr_hourly.\n 2017-02-14: Russell Desiderio. Added tests for the 4 new L2 data products that process\n perminute data. Re-organized test placement, added documentation.\n\n References\n\n OOI (2014). 1341-00370_BULKFLX Artifacts. https://alfresco.oceanobservatories.org/\n (See: Company Home >> OOI >> REFERENCE >> Data Product Specification Artifacts\n >> 1341-00370_BULKFLX\n \"\"\"\n\n def test_met_buoyfls(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[36.10919371, 28.32153986, 33.56844146],\n [31.81003830, 25.38513247, 29.90539752],\n [36.10919371, 28.42887220, 33.68714437],\n [31.81003830, 25.50702812, 30.04173816]])\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_buoyfls(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_vector_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_buoyfls(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES with time-vectorized sensor heights and algorithm switches\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, self.npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, self.npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_buoyfls(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_buoyflx(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[38.41602527, 29.98454817, 35.45099283],\n [33.93646240, 26.92597342, 31.63749229],\n [38.41602527, 30.09636019, 35.57459211],\n [33.93646240, 27.05292615, 31.77941140]])\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_buoyflx(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_vector_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_buoyflx(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES with time-vectorized sensor heights and algorithm switches\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, self.npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, self.npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_buoyflx(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_frshflx(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[0.27428050, -17.10209951, -1.27575685],\n [0.25283019, -17.11663761, -1.29367873],\n [0.27428050, -17.10156642, -1.27517361],\n [0.25283019, -17.11603581, -1.29301424]])\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_frshflx(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_vector_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_frshflx(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES with time-vectorized sensor heights and algorithm switches\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, self.npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, self.npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_frshflx(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_heatflx(self):\n # cases: [jwarm, jcool]\n # total heat flux = latnflx + sensflx + rainflx + netlirr - netsirr\n latnf = np.array([[184.91334211, 133.43175366, 151.19456789],\n [170.45205774, 123.62963458, 139.11084942],\n [184.91334211, 133.78969897, 151.58612581],\n [170.45205774, 124.03365974, 139.55690009]])\n\n sensf = np.array([[24.34435275, 19.84019748, 23.96742950],\n [20.96527540, 17.52684365, 21.07171423],\n [24.34435275, 19.92468342, 24.06116088],\n [20.96527540, 17.62294816, 21.17960462]])\n\n rainf = np.array([[0.00000000, 110.67785202, 9.96157245],\n [0.00000000, 110.67785202, 9.96157245],\n [0.00000000, 110.90622850, 9.98146410],\n [0.00000000, 110.96535859, 9.98688156]])\n\n netli = np.array([[41.43188924, 28.54298163, 42.15187511],\n [39.19850664, 26.60211114, 39.95207621],\n [41.43188924, 28.61328117, 42.22248731],\n [39.19850664, 26.68338061, 40.03470156]])\n\n netsi_down = np.array([541.20150, 622.75500, 599.13000])\n netsi = np.tile(netsi_down, (4, 1))\n\n xpctd = latnf + sensf + rainf + netli - netsi\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_heatflx(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_vector_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_heatflx(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES with time-vectorized sensor heights and algorithm switches\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, self.npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, self.npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_heatflx(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_latnflx(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[184.91334211, 133.43175366, 151.19456789],\n [170.45205774, 123.62963458, 139.11084942],\n [184.91334211, 133.78969897, 151.58612581],\n [170.45205774, 124.03365974, 139.55690009]])\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_latnflx(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_vector_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_latnflx(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES with time-vectorized sensor heights and algorithm switches\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, self.npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, self.npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_latnflx(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_mommflx(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[0.030974330742, 0.016090125876, 0.020303436138],\n [0.030614459503, 0.015910513076, 0.020067006629],\n [0.030974330742, 0.016096471089, 0.020310838724],\n [0.030614459503, 0.015918213926, 0.020076101791]])\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_mommflx(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_vector_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_mommflx(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES with time-vectorized sensor heights and algorithm switches\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, self.npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, self.npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_mommflx(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_netlirr(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[41.43188924, 28.54298163, 42.15187511],\n [39.19850664, 26.60211114, 39.95207621],\n [41.43188924, 28.61328117, 42.22248731],\n [39.19850664, 26.68338061, 40.03470156]])\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_netlirr(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_vector_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_netlirr(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES with time-vectorized sensor heights and algorithm switches\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, self.npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, self.npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_netlirr(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_rainflx(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[0.00000000, 110.67785202, 9.96157245],\n [0.00000000, 110.67785202, 9.96157245],\n [0.00000000, 110.90622850, 9.98146410],\n [0.00000000, 110.96535859, 9.98688156]])\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_rainflx(*args_scalar)\n # for scalar inputs, rain_rate is by definition 0. set xpctd to 0.\n np.testing.assert_allclose(calc, xpctd[0:2, 0], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_vector_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_rainflx(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES with time-vectorized sensor heights and algorithm switches\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, self.npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, self.npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_rainflx(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_sensflx(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[24.34435275, 19.84019748, 23.96742950],\n [20.96527540, 17.52684365, 21.07171423],\n [24.34435275, 19.92468342, 24.06116088],\n [20.96527540, 17.62294816, 21.17960462]])\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_sensflx(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_vector_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_sensflx(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES with time-vectorized sensor heights and algorithm switches\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, self.npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, self.npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_sensflx(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_sphum2m(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[19.42297996, 19.71138107, 19.47478118],\n [19.41394979, 19.70380669, 19.46619271],\n [19.42297996, 19.71166621, 19.47506527],\n [19.41394979, 19.70411212, 19.46650610]])\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_sphum2m(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_vector_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_sphum2m(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES with time-vectorized sensor heights and algorithm switches\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, self.npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, self.npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_sphum2m(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_stablty(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[-0.75134556, -1.53410291, -1.29155675], # [00]\n [-0.67713848, -1.40615623, -1.17706256], # [01]\n [-0.75134556, -1.53871067, -1.29521084], # [10]\n [-0.67713848, -1.41154284, -1.18138703]]) # [11]\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_stablty(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_vector_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_stablty(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES with time-vectorized sensor heights and algorithm switches\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, self.npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, self.npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_stablty(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_tempa2m(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[28.36851533, 28.09024408, 27.81395793],\n [28.35732615, 28.08200008, 27.80462176],\n [28.36851533, 28.09054198, 27.81425524],\n [28.35732615, 28.08234637, 27.80497552]])\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_tempa2m(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_vector_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_tempa2m(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES with time-vectorized sensor heights and algorithm switches\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, self.npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, self.npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_tempa2m(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_tempskn(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[31.12500000, 31.03300000, 31.02200000],\n [30.76398727, 30.71905805, 30.66606321],\n [31.12500000, 31.04435295, 31.03340467],\n [30.76398727, 30.73222317, 30.67945497]])\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_tempskn(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_vector_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_tempskn(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES with time-vectorized sensor heights and algorithm switches\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, self.npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, self.npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_tempskn(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_wind10m(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[4.84933264, 3.42025464, 3.87210524],\n [4.85069650, 3.42094844, 3.87301659],\n [4.84933264, 3.42023139, 3.87207813],\n [4.85069650, 3.42091723, 3.87297987]])\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_wind10m(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_vector_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_wind10m(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES with time-vectorized sensor heights and algorithm switches\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, self.npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, self.npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_wind10m(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n \"\"\"\n Tests for coolskin/warmlayer products on native METBK timebase.\n\n Test values were generated in matlab and implemented by Russell Desiderio.\n Vector cases with time-vectorized sensor heights and algorithm switches\n are not necessary because these data products are produced on the native\n time base of the METBK instrumentation (and the hourly versions have\n already been vetted).\n \"\"\"\n def test_met_heatflx_minute(self):\n # cases: [jwarm, jcool]\n # total heat flux = latnflx + sensflx + rainflx + netlirr - netsirr\n latnf = np.array([[184.91334211, 133.43175366, 151.19456789],\n [170.45205774, 123.62963458, 139.11084942],\n [184.91334211, 133.50681019, 151.24665632],\n [170.45205774, 123.71656274, 139.18576360]])\n\n sensf = np.array([[24.34435275, 19.84019748, 23.96742950],\n [20.96527540, 17.52684365, 21.07171423],\n [24.34435275, 19.85791503, 23.97990023],\n [20.96527540, 17.54752327, 21.08983701]])\n\n rainf = np.array([[0.00000000, 110.67785202, 9.96157245],\n [0.00000000, 110.67785202, 9.96157245],\n [0.00000000, 110.72575756, 9.96421969],\n [0.00000000, 110.73973748, 9.96582507]])\n\n netli = np.array([[41.43188924, 28.54298163, 42.15187511],\n [39.19850664, 26.60211114, 39.95207621],\n [41.43188924, 28.55772741, 42.16127194],\n [39.19850664, 26.61960347, 39.96595888]])\n\n netsi_down = np.array([541.20150, 622.75500, 599.13000])\n netsi = np.tile(netsi_down, (4, 1))\n\n xpctd = latnf + sensf + rainf + netli - netsi\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_heatflx_minute(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_permin_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_heatflx_minute(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_latnflx_minute(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[184.91334211, 133.43175366, 151.19456789],\n [170.45205774, 123.62963458, 139.11084942],\n [184.91334211, 133.50681019, 151.24665632],\n [170.45205774, 123.71656274, 139.18576360]])\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_latnflx_minute(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_permin_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_latnflx_minute(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_netlirr_minute(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[41.43188924, 28.54298163, 42.15187511],\n [39.19850664, 26.60211114, 39.95207621],\n [41.43188924, 28.55772741, 42.16127194],\n [39.19850664, 26.61960347, 39.96595888]])\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_netlirr_minute(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_permin_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_netlirr_minute(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_sensflx_minute(self):\n # cases: [jwarm, jcool]\n xpctd = np.array([[24.34435275, 19.84019748, 23.96742950],\n [20.96527540, 17.52684365, 21.07171423],\n [24.34435275, 19.85791503, 23.97990023],\n [20.96527540, 17.54752327, 21.08983701]])\n\n # SCALAR CASES [00] and [01]:\n calc = np.zeros(2)\n iwarm = 0\n for icool in range(2):\n args_scalar = self.args_scalar_inputs + (iwarm, icool)\n calc[icool] = mb.met_sensflx_minute(*args_scalar)\n np.testing.assert_allclose(calc, xpctd[0:2, self.kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASES\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n for icool in range(2):\n ctr = icool + iwarm * 2\n args_vector = self.args_permin_inputs + (iwarm, icool)\n calc[ctr, :] = mb.met_sensflx_minute(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n \"\"\"\n Tests for products that require neither coolskin nor warmlayer corrections.\n\n Test values were generated in matlab and implemented by Russell Desiderio.\n \"\"\"\n def test_met_barpres(self):\n pr_air_mbar = np.array([1005.1, 1006.2, 1007.3])\n xpctd = pr_air_mbar * 100.0\n\n # SCALAR CASE\n kk = 1\n calc = mb.met_barpres(pr_air_mbar[kk])\n np.testing.assert_allclose(calc, xpctd[kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASE\n calc = mb.met_barpres(pr_air_mbar)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_netsirr(self):\n xpctd = np.array([541.20150, 622.75500, 599.13000])\n Rshort_down = np.array([572.7, 659.0, 634.0])\n\n # SCALAR CASE\n kk = 1\n calc = mb.met_netsirr(Rshort_down[kk])\n np.testing.assert_allclose(calc, xpctd[kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASE\n calc = mb.met_netsirr(Rshort_down)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_netsirr_hourly(self):\n #\n # This Vector Case differs from that for test_met_netsirr in that\n # 30 points of Rshort_down data spanning 3 hours (self.Rshort_down)\n # are input instead of a vector of 3 values (Rshort_down).\n #\n xpctd = np.array([541.20150, 622.75500, 599.13000])\n Rshort_down = np.array([572.7, 659.0, 634.0])\n\n # SCALAR CASE\n kk = 1\n calc = mb.met_netsirr_hourly(Rshort_down[kk], 6540998.0)\n np.testing.assert_allclose(calc, xpctd[kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASE (input data span 3 hours)\n calc = mb.met_netsirr_hourly(self.Rshort_down, self.timestamp)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_rainrte(self):\n # SCALAR CASE\n xpctd_scalar = 0.0\n calc = mb.met_rainrte(42.0, 6540998.0)\n np.testing.assert_allclose(calc, xpctd_scalar, rtol=1.e-8, atol=0.0)\n\n # VECTOR CASE (input data span 3 hours)\n xpctd = np.array([0.0, 17.3, 1.5])\n calc = mb.met_rainrte(self.cumu_prcp, self.timestamp)\n\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_salsurf(self):\n #\n # Test values generated from ctd_functions.ctd_pracsal, using ztmpwat [m]\n # as a proxy for pressure [db].\n #\n xpctd = np.array([20.80589579, 25.51852081, 29.42245514])\n cond_S_m = np.array([3.0, 4.0, 5.0])\n tC_sea = np.array([20.0, 25.0, 30.0])\n ztmpwat = np.array([1.0, 1.5, 2.0])\n\n # SCALAR CASE\n kk = 1\n calc = mb.met_salsurf(cond_S_m[kk], tC_sea[kk], ztmpwat[kk])\n np.testing.assert_allclose(calc, xpctd[kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASE\n calc = mb.met_salsurf(cond_S_m, tC_sea, ztmpwat)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n def test_met_spechum(self):\n xpctd = np.array([19.12588067, 19.49340148, 19.23895340])\n tC_air = np.array([28.220, 27.961, 27.670])\n pr_air = np.array([1005.1, 1006.2, 1007.3])\n relhum = np.array([79.47, 82.30, 82.72])\n\n # SCALAR CASE\n kk = 1\n calc = mb.met_spechum(tC_air[kk], pr_air[kk], relhum[kk])\n np.testing.assert_allclose(calc, xpctd[kk], rtol=1.e-8, atol=0.0)\n\n # VECTOR CASE\n calc = mb.met_spechum(tC_air, pr_air, relhum)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n \"\"\"\n Tests for current and wind products.\n\n Except as noted, test values were generated in matlab and implemented by\n Russell Desiderio.\n \"\"\"\n def test_met_current_direction(self):\n # Desiderio 13-Jul-2015.\n # Revised unit tests to check action of use_velptmn_with_metbk switch\n\n # test data inputs - hit all quadrants.\n hf_rt3 = np.sqrt(3.0)/2.0\n vle = np.array([0.0, hf_rt3, 0.5, 0.0, -0.5, -hf_rt3,\n -1.0, -hf_rt3, -0.5, 0.0, 0.5, hf_rt3])\n vln = np.array([0.0, 0.5, hf_rt3, 1.0, hf_rt3, 0.5,\n 0.0, -0.5, -hf_rt3, -1.0, -hf_rt3, -0.5])\n\n # expected output; 0 = North, 90 = East.\n xpctd = np.array([90.0, 60.0, 30.0, 0.0, 330.0, 300.0,\n 270.0, 240.0, 210.0, 180.0, 150.0, 120.0])\n\n # (0) no switch - calculated = nans\n calc = mb.met_current_direction(vle, vln)\n np.testing.assert_array_almost_equal(calc, xpctd*np.nan, decimal=4)\n\n # (1) scalar switch tests\n # (1a) all good data\n calc = mb.met_current_direction(vle, vln, 1)\n np.testing.assert_array_almost_equal(calc, xpctd, decimal=4)\n # (1b) all bad data\n calc = mb.met_current_direction(vle, vln, 0)\n np.testing.assert_array_almost_equal(calc, xpctd*np.nan, decimal=4)\n\n # (2) vectorized switch tests\n npts = vle.shape[0]\n # (2a) all good data\n calc = mb.met_current_direction(vle, vln, np.ones(npts))\n np.testing.assert_array_almost_equal(calc, xpctd, decimal=4)\n # (2b) all bad data\n calc = mb.met_current_direction(vle, vln, np.zeros(npts))\n np.testing.assert_array_almost_equal(calc, xpctd*np.nan, decimal=4)\n # (2b) mixed data\n use_metbk = np.ones(npts)\n for ii in [1, 6, 9, 10]:\n xpctd[ii] = np.nan\n use_metbk[ii] = 0\n calc = mb.met_current_direction(vle, vln, use_metbk)\n np.testing.assert_array_almost_equal(calc, xpctd, decimal=4)\n\n def test_met_current_speed(self):\n #\"\"\"\n # Test the surface current algorithm using test data generated in Matlab\n # from the compass plot function example:\n #\n # >> rng(0,'twister') % initialize random number generator\n # >> M = randn(15,15);\n # >> Z = eig(M);\n # >> vle = real(Z);\n # >> vln = imag(Z);\n # >> crnt = sqrt(vle.^2 + vln.^2);\n #\n # C. Wingard 2014-07-01\n # R. Desiderio 13-Jul-2015.\n # Revised unit tests to check action of use_velptmn_with_metbk switch\n #\"\"\"\n\n # test data inputs\n vle = np.array([-3.1330, -3.1330, -2.9908, 1.0666, 1.0666,\n 2.1770, 2.1770, -0.8572, -0.8572, -1.4486,\n -1.4486, 0.2149, 0.2149, 1.4811, 0.7050])\n vln = np.array([1.1221, -1.1221, 0.0000, 2.8685, -2.8685,\n 1.6654, -1.6654, 2.2209, -2.2209, 0.9033,\n -0.9033, 1.7152, -1.7152, 0.0000, 0.0000])\n\n # expected output\n crnt = np.array([3.3279, 3.3279, 2.9908, 3.0604, 3.0604,\n 2.7410, 2.7410, 2.3806, 2.3806, 1.7072,\n 1.7072, 1.7286, 1.7286, 1.4811, 0.7050])\n\n # no switch - calculated = nans\n out = mb.met_current_speed(vle, vln)\n np.testing.assert_array_almost_equal(out, crnt*np.nan, decimal=4)\n\n # compute the surface current - all good data\n out = mb.met_current_speed(vle, vln, 1)\n # and compare the expected to the calculated\n np.testing.assert_array_almost_equal(out, crnt, decimal=4)\n\n # compute the surface current - all bad data\n out = mb.met_current_speed(vle, vln, 0)\n # and compare the expected to the calculated\n np.testing.assert_array_almost_equal(out, crnt*np.nan, decimal=4)\n\n # vectorized switch tests\n npts = vle.shape[0]\n # all good data\n out = mb.met_current_speed(vle, vln, np.ones(npts))\n np.testing.assert_array_almost_equal(out, crnt, decimal=4)\n # all bad data\n out = mb.met_current_speed(vle, vln, np.zeros(npts))\n np.testing.assert_array_almost_equal(out, crnt*np.nan, decimal=4)\n # time vectorized, mixed good and bad data\n use_metbk = np.ones(vle.shape[0])\n for ii in [1, 6, 9, 10]:\n crnt[ii] = np.nan\n use_metbk[ii] = 0\n out = mb.met_current_speed(vle, vln, use_metbk)\n np.testing.assert_array_almost_equal(out, crnt, decimal=4)\n\n def test_met_relwind_direction(self):\n #\n # 2015-07-14. Russell Desiderio. Revised unit tests to check action of\n # use_velptmn_with_metbk switch\n #\n hf_rt3 = np.sqrt(3.0)/2.0\n wind_vle = np.array([0.0, hf_rt3, 0.5, 0.0, -0.5, -hf_rt3,\n -1.0, -hf_rt3, -0.5, 0.0, 0.5, hf_rt3]) * 3.0\n wind_vln = np.array([0.0, 0.5, hf_rt3, 1.0, hf_rt3, 0.5,\n 0.0, -0.5, -hf_rt3, -1.0, -hf_rt3, -0.5]) * 3.0\n npts = wind_vle.shape[0]\n current_vle = np.tile(-0.5 * 2.0, npts)\n current_vln = np.tile(-hf_rt3 * 2.0, npts)\n\n # to calculate expected values, use met_current_direction, which has already\n # been checked (and not called by met_relwind_direction).\n xpctd = mb.met_current_direction(wind_vle-current_vle, wind_vln-current_vln, 1)\n\n # no current data and no switch - current data to be considered all bad, by default\n # expected result is xpctd*np.nan\n calc = mb.met_relwind_direction(wind_vle, wind_vln)\n np.testing.assert_array_almost_equal(calc, xpctd*np.nan, decimal=5)\n\n # no switch - current data to be considered all bad, by default\n # expected result is xpctd*np.nan\n calc = mb.met_relwind_direction(wind_vle, wind_vln, current_vle, current_vln)\n np.testing.assert_array_almost_equal(calc, xpctd*np.nan, decimal=5)\n\n # all good data: set the use_velptmn switch to 1 in the calling argument list.\n calc = mb.met_relwind_direction(wind_vle, wind_vln, current_vle, current_vln, 1)\n np.testing.assert_array_almost_equal(calc, xpctd, decimal=5)\n\n # all bad data: set the use_velptmn switch to 0 in the calling argument list.\n # expected result is xpctd*np.nan\n calc = mb.met_relwind_direction(wind_vle, wind_vln, current_vle, current_vln, 0)\n np.testing.assert_array_almost_equal(calc, xpctd*np.nan, decimal=5)\n\n # time-vectorized switch cases\n # all good\n use_metbk = np.ones(npts)\n calc = mb.met_relwind_direction(wind_vle, wind_vln, current_vle, current_vln, use_metbk)\n np.testing.assert_array_almost_equal(calc, xpctd, decimal=5)\n # all bad\n use_metbk = np.zeros(npts)\n calc = mb.met_relwind_direction(wind_vle, wind_vln, current_vle, current_vln, use_metbk)\n np.testing.assert_array_almost_equal(calc, xpctd*np.nan, decimal=5)\n # mixed good and bad data\n use_metbk = np.ones(npts)\n for ii in [1, 6, 9, 10]:\n xpctd[ii] = np.nan\n use_metbk[ii] = 0\n calc = mb.met_relwind_direction(wind_vle, wind_vln, current_vle, current_vln, use_metbk)\n np.testing.assert_array_almost_equal(calc, xpctd, decimal=5)\n\n def test_met_relwind_speed(self):\n #\n #2015-07-14. Russell Desiderio. Revised unit tests to check action of\n # use_velptmn_with_metbk switch.\n #\n\n # These tests differ from those for relwind_direction, current_speed, and current_direction\n # in that bad current data should not result in nans for the relative windspeed; rather, the\n # windspeed itself should be calculated as the data product as if the current velocities are 0.\n\n hf_rt3 = np.sqrt(3.0)/2.0\n wind_vle = np.array([0.0, hf_rt3, 0.5, 0.0, -0.5, -hf_rt3,\n -1.0, -hf_rt3, -0.5, 0.0, 0.5, hf_rt3]) * 3.0\n wind_vln = np.array([0.0, 0.5, hf_rt3, 1.0, hf_rt3, 0.5,\n 0.0, -0.5, -hf_rt3, -1.0, -hf_rt3, -0.5]) * 3.0\n npts = wind_vle.shape[0]\n current_vle = np.tile(-0.5 * 2.0, npts)\n current_vln = np.tile(-hf_rt3 * 2.0, npts)\n\n xpctd_goodcurrent = np.array([2.000000, 4.836559, 5.000000, 4.836559, 4.358899, 3.605551,\n 2.645751, 1.614836, 1.000000, 1.614836, 2.645751, 3.605551])\n\n xpctd_badcurrent = np.hstack((0.0, np.tile(3.0, npts-1)))\n\n # no current data and no switch - current data to be considered all bad, by default\n # expected result is xpctd_badcurrent\n calc = mb.met_relwind_speed(wind_vle, wind_vln)\n np.testing.assert_array_almost_equal(calc, xpctd_badcurrent, decimal=5)\n\n # all bad current data: no switch\n calc = mb.met_relwind_speed(wind_vle, wind_vln, current_vle, current_vln)\n np.testing.assert_array_almost_equal(calc, xpctd_badcurrent, decimal=5)\n # all good current data: set the use_velptmn switch to 1 in the calling argument list.\n calc = mb.met_relwind_speed(wind_vle, wind_vln, current_vle, current_vln, 1)\n np.testing.assert_array_almost_equal(calc, xpctd_goodcurrent, decimal=5)\n # all bad current data: set the use_velptmn switch to 0 in the calling argument list.\n calc = mb.met_relwind_speed(wind_vle, wind_vln, current_vle, current_vln, 0)\n np.testing.assert_array_almost_equal(calc, xpctd_badcurrent, decimal=5)\n\n # time-vectorized switch cases\n # all good\n use_metbk = np.ones(npts)\n calc = mb.met_relwind_speed(wind_vle, wind_vln, current_vle, current_vln, use_metbk)\n np.testing.assert_array_almost_equal(calc, xpctd_goodcurrent, decimal=5)\n # all bad\n use_metbk = np.zeros(npts)\n calc = mb.met_relwind_speed(wind_vle, wind_vln, current_vle, current_vln, use_metbk)\n np.testing.assert_array_almost_equal(calc, xpctd_badcurrent, decimal=5)\n # mixed good and bad\n use_metbk = np.ones(npts)\n xpctd = np.copy(xpctd_goodcurrent)\n for ii in [1, 6, 9, 10]:\n xpctd[ii] = xpctd_badcurrent[ii]\n use_metbk[ii] = 0\n calc = mb.met_relwind_speed(wind_vle, wind_vln, current_vle, current_vln, use_metbk)\n np.testing.assert_array_almost_equal(calc, xpctd, decimal=5)\n\n def test_met_windavg(self):\n #\"\"\"\n # Date, lat, and lon provided approximately equal magnetic\n # declinations of -17 and +17 degrees\n #\n # have to convert these dates to ntp timestamp (seconds since\n # 1900-01-01)\n #\n # C. Wingard 2014-07-01\n #\"\"\"\n\n date_str = np.array([\n '5/30/2013', '5/30/2013', '5/30/2013', '5/30/2013', '5/30/2013',\n '5/30/2013', '5/30/2013', '5/30/2013'])\n convert_to_ntp = lambda x: (\n dt.datetime.strptime(x, '%m/%d/%Y') -\n dt.datetime(1900, 1, 1)).total_seconds()\n date_ts = map(convert_to_ntp, date_str)\n\n lat = np.array([\n 43.34, 43.34, 43.34, 43.34,\n 47.767, 47.767, 47.767, 47.767])\n lon = np.array([\n -66, -66, -66, -66,\n -126, -126, -126, -126])\n\n ve = np.array([\n 2.47, -2.47, -2.47, 2.47,\n 2.47, -2.47, -2.47, 2.47])\n vn = np.array([\n 6.52, 6.52, -6.52, -6.52,\n 6.52, 6.52, -6.52, -6.52])\n\n ve_expected = np.array([\n 0.46, -4.27, -0.46, 4.27,\n 4.27, -0.46, -4.27, 0.46])\n vn_expected = np.array([\n 6.96, 5.51, -6.96, -5.51,\n 5.51, 6.96, -5.51, -6.96])\n\n ve_cor = mb.met_windavg_mag_corr_east(ve, vn, lat, lon, date_ts)\n vn_cor = mb.met_windavg_mag_corr_north(ve, vn, lat, lon, date_ts)\n\n # test data was only given to 2 decimals (despite that the\n # function can calculate to better accuracy based on comparison\n # of this function to the DPS Matlab function). So here the test\n # data is only tested to 2 decimal places\n np.testing.assert_array_almost_equal(ve_cor, ve_expected, decimal=2)\n np.testing.assert_array_almost_equal(vn_cor, vn_expected, decimal=2)\n\n \"\"\"\n Tests involving time.\n \"\"\"\n def test_make_hourly_data(self):\n #\"\"\"\n # Note that except for the first two elements, the expected values are the\n # same as those given above in the \"scalar testset\".\n # The first element contains the hourly averages of the cumulative\n # precipitation; when differenced, this will give the expected\n # rain rate array [0.0, 17.3, 1,5].\n # The second element contains the hourly timestamps which have been\n # coded to be at the midpoint of the bins.\n # Note also that the output of make_hourly_data is a list of np.arrays.\n #\n # Initial code: 2014-09-20, Russell Desiderio.\n #\"\"\"\n xpctd = [np.array([0., 17.3, 18.8]),\n np.array([866200., 869800., 873400.]),\n np.array([40.5, 40.6, 40.7]),\n np.array([31.125, 31.033, 31.022]),\n np.array([4.805, 3.396, 3.843]),\n np.array([28.22, 27.961, 27.67]),\n np.array([79.47, 82.3, 82.72]),\n np.array([1005.1, 1006.2, 1007.3]),\n np.array([572.7, 659., 634.]),\n np.array([443.3, 456., 441.9]),\n np.array([0.1, 1.1, 2.1])]\n\n args = [self.cumu_prcp, self.timestamp, self.lon, self.tC_sea, self.wnd, self.tC_air,\n self.relhum, self.pr_air, self.Rshort_down, self.Rlong_down, self.lat]\n\n args = mb.condition_data(*args)\n\n calc = mb.make_hourly_data(*args)\n\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=1.e-8)\n\n def test_met_timeflx(self):\n \"\"\"\n Uses the timestamp data as in test_make_hourly_data.\n\n Initial code: 2014-10-22, Russell Desiderio.\n \"\"\"\n xpctd = np.array([866200., 869800., 873400.])\n\n calc = mb.met_timeflx(self.timestamp)\n\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=1.e-8)\n\n def test_multiple_days(self):\n \"\"\"\n Written to test nan results when a day's data does not start before 6AM.\n Use latent heat flux calculation as the test product to monitor.\n\n Initial code: 2014-10-27, Russell Desiderio.\n \"\"\"\n # this test originally generated runtime warnings whenever logical indexing or\n # np.where were used on arrays containing nan values; the calculations however\n # gave the expected and desired results. these warnings can be turned off by\n # executing: np.seterr(invalid='ignore'); however, instead i directly trapped\n # out these instances in the code.\n\n # jwarm=jcool=1 for latent heat flux product\n xpctd_1day = np.array([170.45205774, 124.03365974, 139.55690009])\n xpctd_3day = np.tile(xpctd_1day, 3)\n\n # first check that a run of 3 consecutive days of good data gives the expected result.\n xpctd = np.copy(xpctd_3day)\n calc = mb.met_latnflx(*self.args_multiple_days)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=1.e-8)\n #timeflx = mb.met_timeflx(self.args_multiple_days[4])\n #print timeflx\n\n # now check to see what happens if a day of data does not start before 6AM;\n # 3 tests, one each for adding 5 hours to one of the day's timestamps.\n #\n # note that the test values will change and also a different number of\n # binned points can result if a non-integral number of hours is used.\n for ii in range(3):\n # if the np.copy operations are not used, then the tests pass, but for the\n # 'wrong' reasons; for example, in the last iteration all xpctd values become\n # nans and all local times will be later than 6AM (instead of only the 3rd day's\n # times shifting to later than 6AM).\n xpctd = np.copy(xpctd_3day)\n # set ii_th day's values to nans\n xpctd[ii*3:ii*3+3] = np.nan\n alt_time = np.copy(self.args_multiple_days[4])\n # add 5 hours to ii_th day's times\n alt_time[ii*30:ii*30+30] = alt_time[ii*30:ii*30+30] + 5 * 3600.0\n args = self.args_multiple_days[0:4] + (alt_time,) + self.args_multiple_days[5:]\n calc = mb.met_latnflx(*args)\n #timeflx = mb.met_timeflx(alt_time) # make sure python is creating copies\n #print timeflx, xpctd\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=1.e-8)\n\n def test_time_calcs_with_actual_metbk_data(self):\n \"\"\"\n Test manipulation of date and time by running a flux algorithm with actual\n raw (each_minute) METBK data (from Irminger Sea deployment).\n\n This code also provides a template on how to calculate L2 METBK data products\n requiring the warmlayer and coolskin algorithms.\n\n NOTE: These PRECIPM_L0 data exhibit systematic spiking. The repeating cycle\n is a spike of 3 points followed by 12 points of unaliased data. This pattern\n is evident when plots of these precipm data v. time are zoomed in.\n\n 2014-12-19: Russell Desiderio. Initial code.\n 2014-12-29: Russell Desiderio. Extended tests.\n \"\"\"\n # read in the input L0 test data ...\n file = os.path.join(os.getcwd(),\n 'ion_functions/data/matlab_scripts/metbk/metbk_test_dat.txt')\n with open(file, 'r') as f:\n lines = f.readlines()\n\n # ... parse it into a data array\n txtdata = []\n for ii in lines:\n txtdata.append((ii.strip().split(\",\")))\n data = np.array(txtdata, dtype=float)\n\n # to ensure no loss of precision, the OOI CI timestamps were broken up into a\n # more significant and a less significant field; a timestamp of 3619382459.096\n # is represented by the fields 3619382 and 459.096.\n #\n # reconstitute OOI CI timestamps [sec since 1900-01-01; UT]\n timstmp = data[:, 0] * 1000 + data[:, 1]\n\n # document input L0 data by assigning DPS variable names to the data columns\n barpres = data[:, 2]\n relhumi = data[:, 3]\n tempair = data[:, 4]\n longirr = data[:, 5]\n precipm = data[:, 6]\n tempsrf = data[:, 7]\n condsrf = data[:, 8] # not used in any METBK DPA algorithms\n shrtirr = data[:, 9]\n wndrawE = data[:, 10]\n wndrawN = data[:, 11]\n\n # the test data came from the Irminger Sea deployment, so\n lon = np.copy(barpres)\n lon[:] = -39.\n lat = np.copy(barpres)\n lat[:] = 60.\n\n # sensor heights\n ztmpwat = 1.5\n zwindsp = 8.0\n ztmpair = 5.0\n zhumair = 4.0\n\n # correct wind components for magnetic variation; this is necessary in the\n # general case because the L1 VELPT current data product values, required for\n # the relative wind calculation, have themselves been magnetically corrected.\n ve_cor = mb.met_windavg_mag_corr_east(wndrawE, wndrawN, lat, lon, timstmp)\n vn_cor = mb.met_windavg_mag_corr_north(wndrawE, wndrawN, lat, lon, timstmp)\n # for this test, however, assume there is no current.\n zero_1D = np.array([0.0])\n rel_wnd_spd = mb.met_relwind_speed(ve_cor, vn_cor, zero_1D, zero_1D)\n\n # construct argument tuple for flux data products\n args = (tempsrf, rel_wnd_spd, tempair, relhumi, timstmp, lon, ztmpwat, zwindsp,\n ztmpair, zhumair, lat, barpres, shrtirr, longirr, precipm)\n\n # latent heat flux, an hourly data product\n latnflx = mb.met_latnflx(*args)\n # calculate time base for latnflx (and all hourly data products)\n hourly_time_base = mb.met_timeflx(timstmp)\n\n # TESTS:\n # (1) verify that the first and last ooici timestamps correlate with\n # the datetimes in the raw METBK text files.\n #\n # to convert ooi ci timestamps to readable datetime strings, first\n # convert them to posix (unix) time by subtracting the difference in\n # epochs, then use a function from the datetime module.\n epoch_offset = 2208988800 # number of seconds between 1900 and 1970 epochs\n utc_rawdata_first = dt.datetime.utcfromtimestamp(timstmp[0] - epoch_offset)\n xpctd_first = '2014-09-11 00:00:59.096000'\n np.testing.assert_equal(utc_rawdata_first.isoformat(' '), xpctd_first)\n\n utc_rawdata_last = dt.datetime.utcfromtimestamp(timstmp[-1] - epoch_offset)\n xpctd_last = '2014-09-17 23:59:38.992000'\n np.testing.assert_equal(utc_rawdata_last.isoformat(' '), xpctd_last)\n\n # (2) there should be 168 hourly timestamps, because the rawdata spans 7 complete days.\n np.testing.assert_equal(hourly_time_base.shape[0], 168)\n\n # (3a) the 1st hourly timestamp will be 30 minutes later than the first rawstamp.\n utc_hourly_first = dt.datetime.utcfromtimestamp(hourly_time_base[0] - epoch_offset)\n xpctd_first = '2014-09-11 00:30:59.096000'\n np.testing.assert_equal(utc_hourly_first.isoformat(' '), xpctd_first)\n\n # (3b) the last hourly timestamp will be (168-1) hours later than the first hourly stamp.\n utc_hourly_last = dt.datetime.utcfromtimestamp(hourly_time_base[-1] - epoch_offset)\n xpctd_last = '2014-09-17 23:30:59.096000'\n np.testing.assert_equal(utc_hourly_last.isoformat(' '), xpctd_last)\n\n # (4) Local time check: because the longitude is 39 West, Irminger local time\n # is 39 * 240 seconds = 156 minutes earlier than UTC. Therefore, the\n # first 4 hourly timestamps are:\n #\n # UTC local\n # 00:30:59.096 21:54:59.096\n # 01:30:59.096 22:54:59.096\n # 02:30:59.096 23:54:59.096\n # 03:30:59.096 00:54:59.096\n #\n # The test is that the first non-NaN data value should be the 4th, because the\n # previous day's data did not start before 6:00 AM local as required by the\n # warmlayer algorithm.\n calc = np.isnan(latnflx[0:4])\n xpctd = np.array([True, True, True, False])\n np.testing.assert_equal(calc, xpctd)\n\n def test_warmlayer_time_keys(self):\n \"\"\"\n idx_warm, newday, nanmask = warmlayer_time_keys(localdate)\n\n where\n\n idx_warm = indices of data records to be processed by the warmlayer routine;\n these are data for days for which there are data before a threshold\n time value early in the morning (usually set to equatorial sunrise).\n newday = boolean array: true for the first record of a day, false otherwise.\n nanmask = boolean array: true for indices of data records not to be processed\n by the warmlayer routine.\n localdate = local (not UTC) date and time [sec since 01-01-1900]\n\n Initial code: 2014-10-27, Russell Desiderio.\n \"\"\"\n # test data: set local date and times for each day\n # no times before 6AM (21600 seconds)\n day1 = np.array([30000.0, 34000.0, 40000.0]) + 3 * 86400.0\n # 1st time before 6AM\n day2 = np.array([20000.0, 25000.0, 30000.0, 36000.0]) + 4 * 86400.0\n day3 = np.array([50000.0, 60000.0]) + 7 * 86400.0\n day4 = np.array([10000.0, 15000.0, 20000.0, 26000.0]) + 9 * 86400.0\n # entire test time record\n localdate = np.hstack((day1, day2, day3, day4))\n\n # expected\n xpctd_idx = np.array([3, 4, 5, 6, 9, 10, 11, 12])\n xpctd_new = np.array([1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0], dtype=bool)\n xpctd_nan = np.array([1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0], dtype=bool)\n xpctd = (xpctd_idx, xpctd_new, xpctd_nan)\n\n # calculated\n calc = mb.warmlayer_time_keys(localdate)\n\n np.testing.assert_equal(calc, xpctd)\n\n \"\"\"\n Miscellaneous tests.\n \"\"\"\n def test_rain_heat_flux(self):\n \"\"\"\n Tests new formulation of rain heat flux, independent of coare bulk algorithms.\n \"\"\"\n Tsea = 25.0\n Tair = 23.5\n RH = 80.0 # relative humidity [%]\n rainrate = 1.0 # [mm/hour]\n Pr = 1015.0 # atmospheric pressure [mbar]\n\n # check value is from the matlab code test_rain_heat_flux.m\n xpctd = 4.663360812871\n calc = mb.rain_heat_flux(rainrate, Tsea, Tair, RH, Pr)\n np.testing.assert_allclose(calc, xpctd, rtol=0, atol=1.e-12)\n\n def test_time_vectorized_heights_and_switches(self):\n \"\"\"\n Description:\n\n Time-vectorization of the sensor heights (ztmpwat, ztmpair, zhumair, zwindsp,\n and zinvpbl) and algorithm switches (jwarm, jcool) are tested using the DPAs\n met_latnflx and met_wind10m. The check values are identical to the corresponding\n vector case values.\n\n Implemented by:\n\n 2014-07-14: Russell Desiderio. Initial Code.\n 2015-10-26: Russell Desiderio. Added test using met_wind10m. Minor DPA mods were\n made to several DPAs involving binning the invariant\n sensor heights as a fix for redmine ticket #8592 (pull\n request 232). This documentation added 2017-02-14.\n \"\"\"\n xpctd = np.array([[184.91334211, 133.43175366, 151.19456789],\n [170.45205774, 123.62963458, 139.11084942],\n [184.91334211, 133.78969897, 151.58612581],\n [170.45205774, 124.03365974, 139.55690009]])\n\n # latnflx: Time-vectorized cases only\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n npts = self.args_vector_ztmvec[0].shape # number of time points\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_latnflx(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n xpctd = np.array([[4.84933264, 3.42025464, 3.87210524],\n [4.85069650, 3.42094844, 3.87301659],\n [4.84933264, 3.42023139, 3.87207813],\n [4.85069650, 3.42091723, 3.87297987]])\n\n # wind10m: Time-vectorized cases only\n # sensor height arrays in self.args_vector_ztmvec have already been time-vectorized\n npts = self.args_vector_ztmvec[0].shape # number of time points\n calc = np.zeros((4, 3))\n for iwarm in range(2):\n jwarm_tmvec = np.tile(iwarm, npts) # time vectorize jwarm\n for icool in range(2):\n ctr = icool + iwarm * 2\n jcool_tmvec = np.tile(icool, npts) # time vectorize jcool\n args_vector = self.args_vector_ztmvec + (jwarm_tmvec, jcool_tmvec)\n calc[ctr, :] = mb.met_wind10m(*args_vector)\n np.testing.assert_allclose(calc, xpctd, rtol=1.e-8, atol=0.0)\n\n"
]
| [
[
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.isnan",
"numpy.zeros",
"numpy.testing.assert_equal",
"numpy.copy",
"numpy.ones",
"numpy.tile",
"numpy.testing.assert_array_almost_equal",
"numpy.sqrt",
"numpy.hstack"
]
]
|
PanteraCapital/catalyst | [
"90d9e4e2def79b49c32607ce7da349598a117021"
]
| [
"catalyst/__main__.py"
]
| [
"import errno\nimport os\nfrom functools import wraps\nimport re\n\nimport click\nimport sys\nimport logbook\nimport pandas as pd\nfrom catalyst.marketplace.marketplace import Marketplace\nfrom six import text_type\n\nfrom catalyst.data import bundles as bundles_module\nfrom catalyst.exchange.exchange_bundle import ExchangeBundle\nfrom catalyst.exchange.utils.exchange_utils import delete_algo_folder\nfrom catalyst.utils.cli import Date, Timestamp\nfrom catalyst.utils.run_algo import _run, load_extensions\nfrom catalyst.exchange.utils.bundle_utils import EXCHANGE_NAMES\nfrom catalyst.utils.remote import remote_backtest, get_remote_status\n\ntry:\n __IPYTHON__\nexcept NameError:\n __IPYTHON__ = False\n\n\[email protected]()\[email protected](\n '-e',\n '--extension',\n multiple=True,\n help='File or module path to a catalyst extension to load.',\n)\[email protected](\n '--strict-extensions/--non-strict-extensions',\n is_flag=True,\n help='If --strict-extensions is passed then catalyst will not run '\n 'if it cannot load all of the specified extensions. If this is '\n 'not passed or --non-strict-extensions is passed then the '\n 'failure will be logged but execution will continue.',\n)\[email protected](\n '--default-extension/--no-default-extension',\n is_flag=True,\n default=True,\n help=\"Don't load the default catalyst extension.py file \"\n \"in $CATALYST_HOME.\",\n)\[email protected]_option()\ndef main(extension, strict_extensions, default_extension):\n \"\"\"Top level catalyst entry point.\n \"\"\"\n # install a logbook handler before performing any other operations\n logbook.StderrHandler().push_application()\n load_extensions(\n default_extension,\n extension,\n strict_extensions,\n os.environ,\n )\n\n\ndef extract_option_object(option):\n \"\"\"Convert a click.option call into a click.Option object.\n\n Parameters\n ----------\n option : decorator\n A click.option decorator.\n\n Returns\n -------\n option_object : click.Option\n The option object that this decorator will create.\n \"\"\"\n\n @option\n def opt():\n pass\n\n return opt.__click_params__[0]\n\n\ndef ipython_only(option):\n \"\"\"Mark that an option should only be exposed in IPython.\n\n Parameters\n ----------\n option : decorator\n A click.option decorator.\n\n Returns\n -------\n ipython_only_dec : decorator\n A decorator that correctly applies the argument even when not\n using IPython mode.\n \"\"\"\n if __IPYTHON__:\n return option\n\n argname = extract_option_object(option).name\n\n def d(f):\n @wraps(f)\n def _(*args, **kwargs):\n kwargs[argname] = None\n return f(*args, **kwargs)\n\n return _\n\n return d\n\n\[email protected]()\[email protected](\n '-f',\n '--algofile',\n default=None,\n type=click.File('r'),\n help='The file that contains the algorithm to run.',\n)\[email protected](\n '-t',\n '--algotext',\n help='The algorithm script to run.',\n)\[email protected](\n '-D',\n '--define',\n multiple=True,\n help=\"Define a name to be bound in the namespace before executing\"\n \" the algotext. For example '-Dname=value'. The value may be\"\n \" any python expression. These are evaluated in order so they\"\n \" may refer to previously defined names.\",\n)\[email protected](\n '--data-frequency',\n type=click.Choice({'daily', 'minute'}),\n default='daily',\n show_default=True,\n help='The data frequency of the simulation.',\n)\[email protected](\n '--capital-base',\n type=float,\n show_default=True,\n help='The starting capital for the simulation.',\n)\[email protected](\n '-b',\n '--bundle',\n default='poloniex',\n metavar='BUNDLE-NAME',\n show_default=True,\n help='The data bundle to use for the simulation.',\n)\[email protected](\n '--bundle-timestamp',\n type=Timestamp(),\n default=pd.Timestamp.utcnow(),\n show_default=False,\n help='The date to lookup data on or before.\\n'\n '[default: <current-time>]'\n)\[email protected](\n '-s',\n '--start',\n type=Date(tz='utc', as_timestamp=True),\n help='The start date of the simulation.',\n)\[email protected](\n '-e',\n '--end',\n type=Date(tz='utc', as_timestamp=True),\n help='The end date of the simulation.',\n)\[email protected](\n '-o',\n '--output',\n default='-',\n metavar='FILENAME',\n show_default=True,\n help=\"The location to write the perf data. If this is '-' the perf\"\n \" will be written to stdout.\",\n)\[email protected](\n '--print-algo/--no-print-algo',\n is_flag=True,\n default=False,\n help='Print the algorithm to stdout.',\n)\n@ipython_only(click.option(\n '--local-namespace/--no-local-namespace',\n is_flag=True,\n default=None,\n help='Should the algorithm methods be resolved in the local namespace.'\n))\[email protected](\n '-x',\n '--exchange-name',\n help='The name of the targeted exchange.',\n)\[email protected](\n '-n',\n '--algo-namespace',\n help='A label assigned to the algorithm for data storage purposes.'\n)\[email protected](\n '-c',\n '--quote-currency',\n help='The quote currency used to calculate statistics '\n '(e.g. usd, btc, eth).',\n)\[email protected]_context\ndef run(ctx,\n algofile,\n algotext,\n define,\n data_frequency,\n capital_base,\n bundle,\n bundle_timestamp,\n start,\n end,\n output,\n print_algo,\n local_namespace,\n exchange_name,\n algo_namespace,\n quote_currency):\n \"\"\"Run a backtest for the given algorithm.\n \"\"\"\n\n if (algotext is not None) == (algofile is not None):\n ctx.fail(\n \"must specify exactly one of '-f' / '--algofile' or\"\n \" '-t' / '--algotext'\",\n )\n\n # check that the start and end dates are passed correctly\n if start is None and end is None:\n # check both at the same time to avoid the case where a user\n # does not pass either of these and then passes the first only\n # to be told they need to pass the second argument also\n ctx.fail(\n \"must specify dates with '-s' / '--start' and '-e' / '--end'\"\n \" in backtest mode\",\n )\n if start is None:\n ctx.fail(\"must specify a start date with '-s' / '--start'\"\n \" in backtest mode\")\n if end is None:\n ctx.fail(\"must specify an end date with '-e' / '--end'\"\n \" in backtest mode\")\n\n if exchange_name is None:\n ctx.fail(\"must specify an exchange name '-x'\")\n\n if quote_currency is None:\n ctx.fail(\"must specify a quote currency with '-c' in backtest mode\")\n\n if capital_base is None:\n ctx.fail(\"must specify a capital base with '--capital-base'\")\n\n click.echo('Running in backtesting mode.', sys.stdout)\n\n perf = _run(\n initialize=None,\n handle_data=None,\n before_trading_start=None,\n analyze=None,\n algofile=algofile,\n algotext=algotext,\n defines=define,\n data_frequency=data_frequency,\n capital_base=capital_base,\n data=None,\n bundle=bundle,\n bundle_timestamp=bundle_timestamp,\n start=start,\n end=end,\n output=output,\n print_algo=print_algo,\n local_namespace=local_namespace,\n environ=os.environ,\n live=False,\n exchange=exchange_name,\n algo_namespace=algo_namespace,\n quote_currency=quote_currency,\n analyze_live=None,\n live_graph=False,\n simulate_orders=True,\n auth_aliases=None,\n stats_output=None,\n )\n\n if output == '--':\n pass\n elif output == '-':\n click.echo(str(perf), sys.stdout)\n elif output != os.devnull: # make the catalyst magic not write any data\n perf.to_pickle(output)\n\n return perf\n\n\ndef catalyst_magic(line, cell=None):\n \"\"\"The catalyst IPython cell magic.\n \"\"\"\n load_extensions(\n default=True,\n extensions=[],\n strict=True,\n environ=os.environ,\n )\n try:\n return run.main(\n # put our overrides at the start of the parameter list so that\n # users may pass values with higher precedence\n [\n '--algotext', cell,\n '--output', os.devnull, # don't write the results by default\n ] + ([\n # these options are set when running in line magic mode\n # set a non None algo text to use the ipython user_ns\n '--algotext', '',\n '--local-namespace',\n ] if cell is None else []) + line.split(),\n '%s%%catalyst' % ((cell or '') and '%'),\n # don't use system exit and propogate errors to the caller\n standalone_mode=False,\n )\n except SystemExit as e:\n # https://github.com/mitsuhiko/click/pull/533\n # even in standalone_mode=False `--help` really wants to kill us ;_;\n if e.code:\n raise ValueError('main returned non-zero status code: %d' % e.code)\n\n\[email protected]()\[email protected](\n '-f',\n '--algofile',\n default=None,\n type=click.File('r'),\n help='The file that contains the algorithm to run.',\n)\[email protected](\n '--capital-base',\n type=float,\n show_default=True,\n help='The amount of capital (in quote_currency) allocated to trading.',\n)\[email protected](\n '-t',\n '--algotext',\n help='The algorithm script to run.',\n)\[email protected](\n '-D',\n '--define',\n multiple=True,\n help=\"Define a name to be bound in the namespace before executing\"\n \" the algotext. For example '-Dname=value'. The value may be\"\n \" any python expression. These are evaluated in order so they\"\n \" may refer to previously defined names.\",\n)\[email protected](\n '-o',\n '--output',\n default='-',\n metavar='FILENAME',\n show_default=True,\n help=\"The location to write the perf data. If this is '-' the perf will\"\n \" be written to stdout.\",\n)\[email protected](\n '--print-algo/--no-print-algo',\n is_flag=True,\n default=False,\n help='Print the algorithm to stdout.',\n)\n@ipython_only(click.option(\n '--local-namespace/--no-local-namespace',\n is_flag=True,\n default=None,\n help='Should the algorithm methods be resolved in the local namespace.'\n))\[email protected](\n '-x',\n '--exchange-name',\n help='The name of the targeted exchange.',\n)\[email protected](\n '-n',\n '--algo-namespace',\n help='A label assigned to the algorithm for data storage purposes.'\n)\[email protected](\n '-c',\n '--quote-currency',\n help='The quote currency used to calculate statistics '\n '(e.g. usd, btc, eth).',\n)\[email protected](\n '-s',\n '--start',\n type=Date(tz='utc', as_timestamp=False),\n help='An optional future start date at '\n 'which the algorithm will start at live',\n)\[email protected](\n '-e',\n '--end',\n type=Date(tz='utc', as_timestamp=False),\n help='An optional end date at which to stop the execution.',\n)\[email protected](\n '--live-graph/--no-live-graph',\n is_flag=True,\n default=False,\n help='Display live graph.',\n)\[email protected](\n '--simulate-orders/--no-simulate-orders',\n is_flag=True,\n default=True,\n help='Simulating orders enable the paper trading mode. No orders will be '\n 'sent to the exchange unless set to false.',\n)\[email protected](\n '--auth-aliases',\n default=None,\n help='Authentication file aliases for the specified exchanges. By default,'\n 'each exchange uses the \"auth.json\" file in the exchange folder. '\n 'Specifying an \"auth2\" alias would use \"auth2.json\". It should be '\n 'specified like this: \"[exchange_name],[alias],...\" For example, '\n '\"binance,auth2\" or \"binance,auth2,bittrex,auth2\".',\n)\[email protected]_context\ndef live(ctx,\n algofile,\n capital_base,\n algotext,\n define,\n output,\n print_algo,\n local_namespace,\n exchange_name,\n algo_namespace,\n quote_currency,\n start,\n end,\n live_graph,\n auth_aliases,\n simulate_orders):\n \"\"\"Trade live with the given algorithm.\n \"\"\"\n if (algotext is not None) == (algofile is not None):\n ctx.fail(\n \"must specify exactly one of '-f' / '--algofile' or\"\n \" '-t' / '--algotext'\",\n )\n\n if exchange_name is None:\n ctx.fail(\"must specify an exchange name '-x'\")\n\n if algo_namespace is None:\n ctx.fail(\"must specify an algorithm name '-n' in live execution mode\")\n\n if quote_currency is None:\n ctx.fail(\"must specify a quote currency '-c' in live execution mode\")\n\n if capital_base is None:\n ctx.fail(\"must specify a capital base with '--capital-base'\")\n\n if simulate_orders:\n click.echo('Running in paper trading mode.', sys.stdout)\n\n else:\n click.echo('Running in live trading mode.', sys.stdout)\n\n perf = _run(\n initialize=None,\n handle_data=None,\n before_trading_start=None,\n analyze=None,\n algofile=algofile,\n algotext=algotext,\n defines=define,\n data_frequency=None,\n capital_base=capital_base,\n data=None,\n bundle=None,\n bundle_timestamp=None,\n start=start,\n end=end,\n output=output,\n print_algo=print_algo,\n local_namespace=local_namespace,\n environ=os.environ,\n live=True,\n exchange=exchange_name,\n algo_namespace=algo_namespace,\n quote_currency=quote_currency,\n live_graph=live_graph,\n analyze_live=None,\n simulate_orders=simulate_orders,\n auth_aliases=auth_aliases,\n stats_output=None,\n )\n\n if output == '-':\n click.echo(str(perf), sys.stdout)\n elif output != os.devnull: # make the catalyst magic not write any data\n perf.to_pickle(output)\n\n return perf\n\n\[email protected](name='remote-run')\[email protected](\n '-f',\n '--algofile',\n default=None,\n type=click.File('r'),\n help='The file that contains the algorithm to run.',\n)\[email protected](\n '-t',\n '--algotext',\n help='The algorithm script to run.',\n)\[email protected](\n '-D',\n '--define',\n multiple=True,\n help=\"Define a name to be bound in the namespace before executing\"\n \" the algotext. For example '-Dname=value'. The value may be\"\n \" any python expression. These are evaluated in order so they\"\n \" may refer to previously defined names.\",\n)\[email protected](\n '--data-frequency',\n type=click.Choice({'daily', 'minute'}),\n default='daily',\n show_default=True,\n help='The data frequency of the simulation.',\n)\[email protected](\n '--capital-base',\n type=float,\n show_default=True,\n help='The starting capital for the simulation.',\n)\[email protected](\n '-b',\n '--bundle',\n default='poloniex',\n metavar='BUNDLE-NAME',\n show_default=True,\n help='The data bundle to use for the simulation.',\n)\[email protected](\n '--bundle-timestamp',\n type=Timestamp(),\n default=pd.Timestamp.utcnow(),\n show_default=False,\n help='The date to lookup data on or before.\\n'\n '[default: <current-time>]'\n)\[email protected](\n '-s',\n '--start',\n type=Date(tz='utc', as_timestamp=True),\n help='The start date of the simulation.',\n)\[email protected](\n '-e',\n '--end',\n type=Date(tz='utc', as_timestamp=True),\n help='The end date of the simulation.',\n)\[email protected](\n '-m',\n '--mail',\n show_default=True,\n help='an E-mail address to send the results to',\n)\[email protected](\n '-o',\n '--output',\n default='-',\n metavar='FILENAME',\n show_default=True,\n help=\"The location to write the perf data. If this is '-' the perf\"\n \" will be written to stdout.\",\n)\[email protected](\n '--print-algo/--no-print-algo',\n is_flag=True,\n default=False,\n help='Print the algorithm to stdout.',\n)\n@ipython_only(click.option(\n '--local-namespace/--no-local-namespace',\n is_flag=True,\n default=None,\n help='Should the algorithm methods be resolved in the local namespace.'\n))\[email protected](\n '-x',\n '--exchange-name',\n help='The name of the targeted exchange.',\n)\[email protected](\n '-n',\n '--algo-namespace',\n help='A label assigned to the algorithm for data storage purposes.'\n)\[email protected](\n '-c',\n '--quote-currency',\n help='The quote currency used to calculate statistics '\n '(e.g. usd, btc, eth).',\n)\[email protected]_context\ndef remote_run(ctx,\n algofile,\n algotext,\n define,\n data_frequency,\n capital_base,\n bundle,\n bundle_timestamp,\n start,\n end,\n mail,\n output,\n print_algo,\n local_namespace,\n exchange_name,\n algo_namespace,\n quote_currency):\n \"\"\"Run a backtest for the given algorithm on the cloud.\n \"\"\"\n\n if (algotext is not None) == (algofile is not None):\n ctx.fail(\n \"must specify exactly one of '-f' / '--algofile' or\"\n \" '-t' / '--algotext'\",\n )\n\n # check that the start and end dates are passed correctly\n if start is None and end is None:\n # check both at the same time to avoid the case where a user\n # does not pass either of these and then passes the first only\n # to be told they need to pass the second argument also\n ctx.fail(\n \"must specify dates with '-s' / '--start' and '-e' / '--end'\"\n \" in backtest mode\",\n )\n if start is None:\n ctx.fail(\"must specify a start date with '-s' / '--start'\"\n \" in backtest mode\")\n if end is None:\n ctx.fail(\"must specify an end date with '-e' / '--end'\"\n \" in backtest mode\")\n\n if exchange_name is None:\n ctx.fail(\"must specify an exchange name '-x'\")\n\n if quote_currency is None:\n ctx.fail(\"must specify a quote currency with '-c' in backtest mode\")\n\n if capital_base is None:\n ctx.fail(\"must specify a capital base with '--capital-base'\")\n\n if mail is None or not re.match(r\"[^@]+@[^@]+\\.[^@]+\", mail):\n ctx.fail(\"must specify a valid email with '--mail'\")\n\n algo_id = remote_backtest(\n initialize=None,\n handle_data=None,\n before_trading_start=None,\n analyze=None,\n algofile=algofile,\n algotext=algotext,\n defines=define,\n data_frequency=data_frequency,\n capital_base=capital_base,\n data=None,\n bundle=bundle,\n bundle_timestamp=bundle_timestamp,\n start=start,\n end=end,\n output='--',\n print_algo=print_algo,\n local_namespace=local_namespace,\n environ=os.environ,\n live=False,\n exchange=exchange_name,\n algo_namespace=algo_namespace,\n quote_currency=quote_currency,\n analyze_live=None,\n live_graph=False,\n simulate_orders=True,\n auth_aliases=None,\n stats_output=None,\n mail=mail,\n )\n print(algo_id)\n return algo_id\n\n\[email protected](name='remote-status')\[email protected](\n '-i',\n '--algo-id',\n show_default=True,\n help='The algo id of your running algorithm on the cloud',\n)\[email protected](\n '-d',\n '--data-output',\n default='-',\n metavar='FILENAME',\n show_default=True,\n help=\"The location to write the perf data, if it exists. If this is '-' \"\n \"the perf will be written to stdout.\",\n)\[email protected](\n '-l',\n '--log-output',\n default='-',\n metavar='FILENAME',\n show_default=True,\n help=\"The location to write the current logging. \"\n \"If this is '-' the log will be written to stdout.\",\n)\[email protected]_context\ndef remote_status(ctx, algo_id, data_output, log_output):\n \"\"\"\n Get the status of a running algorithm on the cloud\n \"\"\"\n if algo_id is None:\n ctx.fail(\"must specify an id of your running algorithm with '--id'\")\n\n status_response = get_remote_status(\n algo_id=algo_id\n )\n if isinstance(status_response, tuple):\n status, perf, log = status_response\n\n if log_output == '-':\n click.echo(str(log), sys.stderr)\n elif log_output != os.devnull:\n with open(log_output, 'w') as file:\n file.write(log)\n\n if perf is not None:\n if data_output == '-':\n click.echo('the performance data is:\\n' +\n str(perf), sys.stdout)\n elif data_output != os.devnull:\n # make the catalyst magic not write any data\n perf.to_pickle(data_output)\n print(status)\n return status, perf\n else:\n print(status_response)\n return status_response\n\n\[email protected](name='ingest-exchange')\[email protected](\n '-x',\n '--exchange-name',\n help='The name of the exchange bundle to ingest.',\n)\[email protected](\n '-f',\n '--data-frequency',\n type=click.Choice({'daily', 'minute', 'daily,minute', 'minute,daily'}),\n default='daily',\n show_default=True,\n help='The data frequency of the desired OHLCV bars.',\n)\[email protected](\n '-s',\n '--start',\n default=None,\n type=Date(tz='utc', as_timestamp=True),\n help='The start date of the data range. (default: one year from end date)',\n)\[email protected](\n '-e',\n '--end',\n default=None,\n type=Date(tz='utc', as_timestamp=True),\n help='The end date of the data range. (default: today)',\n)\[email protected](\n '-i',\n '--include-symbols',\n default=None,\n help='A list of symbols to ingest (optional comma separated list)',\n)\[email protected](\n '--exclude-symbols',\n default=None,\n help='A list of symbols to exclude from the ingestion '\n '(optional comma separated list)',\n)\[email protected](\n '--csv',\n default=None,\n help='The path of a CSV file containing the data. If specified, start, '\n 'end, include-symbols and exclude-symbols will be ignored. Instead,'\n 'all data in the file will be ingested.',\n)\[email protected](\n '--show-progress/--no-show-progress',\n default=True,\n help='Print progress information to the terminal.'\n)\[email protected](\n '--verbose/--no-verbose`',\n default=False,\n help='Show a progress indicator for every currency pair.'\n)\[email protected](\n '--validate/--no-validate`',\n default=False,\n help='Report potential anomalies found in data bundles.'\n)\[email protected]_context\ndef ingest_exchange(ctx, exchange_name, data_frequency, start, end,\n include_symbols, exclude_symbols, csv, show_progress,\n verbose, validate):\n \"\"\"\n Ingest data for the given exchange.\n \"\"\"\n\n if exchange_name is None:\n ctx.fail(\"must specify an exchange name '-x'\")\n if not csv and exchange_name not in EXCHANGE_NAMES:\n ctx.fail(\n \"ingest-exchange does not support {}, \"\n \"please choose exchange from: {}\".format(\n exchange_name,\n EXCHANGE_NAMES))\n\n exchange_bundle = ExchangeBundle(exchange_name)\n\n click.echo('Trying to ingest exchange bundle {}...'.format(exchange_name),\n sys.stdout)\n exchange_bundle.ingest(\n data_frequency=data_frequency,\n include_symbols=include_symbols,\n exclude_symbols=exclude_symbols,\n start=start,\n end=end,\n show_progress=show_progress,\n show_breakdown=verbose,\n show_report=validate,\n csv=csv\n )\n\n\[email protected](name='clean-algo')\[email protected](\n '-n',\n '--algo-namespace',\n help='The label of the algorithm to for which to clean the state.'\n)\[email protected]_context\ndef clean_algo(ctx, algo_namespace):\n click.echo(\n 'Cleaning algo state: {}'.format(algo_namespace),\n sys.stdout\n )\n delete_algo_folder(algo_namespace)\n click.echo('Done', sys.stdout)\n\n\[email protected](name='clean-exchange')\[email protected](\n '-x',\n '--exchange-name',\n help='The name of the exchange bundle to ingest.',\n)\[email protected](\n '-f',\n '--data-frequency',\n type=click.Choice({'daily', 'minute'}),\n default=None,\n help='The bundle data frequency to remove. If not specified, it will '\n 'remove both daily and minute bundles.',\n)\[email protected]_context\ndef clean_exchange(ctx, exchange_name, data_frequency):\n \"\"\"Clean up bundles from 'ingest-exchange'.\n \"\"\"\n\n if exchange_name is None:\n ctx.fail(\"must specify an exchange name '-x'\")\n\n exchange_bundle = ExchangeBundle(exchange_name)\n\n click.echo('Cleaning exchange bundle {}...'.format(exchange_name),\n sys.stdout)\n exchange_bundle.clean(\n data_frequency=data_frequency,\n )\n click.echo('Done', sys.stdout)\n\n\[email protected]()\[email protected](\n '-b',\n '--bundle',\n metavar='BUNDLE-NAME',\n default=None,\n show_default=False,\n help='The data bundle to ingest.',\n)\[email protected](\n '-x',\n '--exchange-name',\n help='The name of the exchange bundle to ingest.',\n)\[email protected](\n '-c',\n '--compile-locally',\n is_flag=True,\n default=False,\n help='Download dataset from source and compile bundle locally.',\n)\[email protected](\n '--assets-version',\n type=int,\n multiple=True,\n help='Version of the assets db to which to downgrade.',\n)\[email protected](\n '--show-progress/--no-show-progress',\n default=True,\n help='Print progress information to the terminal.'\n)\[email protected]_context\ndef ingest(ctx, bundle, exchange_name, compile_locally, assets_version,\n show_progress):\n \"\"\"Ingest the data for the given bundle.\n \"\"\"\n\n bundles_module.ingest(\n bundle,\n os.environ,\n pd.Timestamp.utcnow(),\n assets_version,\n show_progress,\n compile_locally,\n )\n\n\[email protected]()\[email protected](\n '-b',\n '--bundle',\n default='poloniex',\n metavar='BUNDLE-NAME',\n show_default=True,\n help='The data bundle to clean.',\n)\[email protected](\n '-x',\n '--exchange_name',\n metavar='EXCHANGE-NAME',\n show_default=True,\n help='The exchange bundle name to clean.',\n)\[email protected](\n '-e',\n '--before',\n type=Timestamp(),\n help='Clear all data before TIMESTAMP.'\n ' This may not be passed with -k / --keep-last',\n)\[email protected](\n '-a',\n '--after',\n type=Timestamp(),\n help='Clear all data after TIMESTAMP'\n ' This may not be passed with -k / --keep-last',\n)\[email protected](\n '-k',\n '--keep-last',\n type=int,\n metavar='N',\n help='Clear all but the last N downloads.'\n ' This may not be passed with -e / --before or -a / --after',\n)\ndef clean(bundle, before, after, keep_last):\n \"\"\"Clean up bundles from 'ingest'.\n \"\"\"\n bundles_module.clean(\n bundle,\n before,\n after,\n keep_last,\n )\n\n\[email protected]()\ndef bundles():\n \"\"\"List all of the available data bundles.\n \"\"\"\n for bundle in sorted(bundles_module.bundles.keys()):\n if bundle.startswith('.'):\n # hide the test data\n continue\n try:\n ingestions = list(\n map(text_type, bundles_module.ingestions_for_bundle(bundle))\n )\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise\n ingestions = []\n\n # If we got no ingestions, either because the directory didn't exist or\n # because there were no entries, print a single message indicating that\n # no ingestions have yet been made.\n for timestamp in ingestions or [\"<no ingestions>\"]:\n click.echo(\"%s %s\" % (bundle, timestamp), sys.stdout)\n\n\[email protected]()\[email protected]_context\ndef marketplace(ctx):\n \"\"\"Access the Enigma Data Marketplace to:\\n\n - Register and Publish new datasets (seller-side)\\n\n - Subscribe and Ingest premium datasets (buyer-side)\\n\n \"\"\"\n pass\n\n\[email protected]()\[email protected]_context\ndef ls(ctx):\n \"\"\"List all available datasets.\n \"\"\"\n click.echo('Listing of available data sources on the marketplace:',\n sys.stdout)\n marketplace = Marketplace()\n marketplace.list()\n\n\[email protected]()\[email protected](\n '--dataset',\n default=None,\n help='The name of the dataset to ingest from the Data Marketplace.',\n)\[email protected]_context\ndef subscribe(ctx, dataset):\n \"\"\"Subscribe to an existing dataset.\n \"\"\"\n marketplace = Marketplace()\n marketplace.subscribe(dataset)\n\n\[email protected]() # noqa: F811\[email protected](\n '--dataset',\n default=None,\n help='The name of the dataset to ingest from the Data Marketplace.',\n)\[email protected](\n '-f',\n '--data-frequency',\n type=click.Choice({'daily', 'minute', 'daily,minute', 'minute,daily'}),\n default='daily',\n show_default=True,\n help='The data frequency of the desired OHLCV bars.',\n)\[email protected](\n '-s',\n '--start',\n default=None,\n type=Date(tz='utc', as_timestamp=True),\n help='The start date of the data range. (default: one year from end date)',\n)\[email protected](\n '-e',\n '--end',\n default=None,\n type=Date(tz='utc', as_timestamp=True),\n help='The end date of the data range. (default: today)',\n)\[email protected]_context\ndef ingest(ctx, dataset, data_frequency, start, end):\n \"\"\"Ingest a dataset (requires subscription).\n \"\"\"\n marketplace = Marketplace()\n marketplace.ingest(dataset, data_frequency, start, end)\n\n\[email protected]() # noqa: F811\[email protected](\n '--dataset',\n default=None,\n help='The name of the dataset to ingest from the Data Marketplace.',\n)\[email protected]_context\ndef clean(ctx, dataset):\n \"\"\"Clean/Remove local data for a given dataset.\n \"\"\"\n marketplace = Marketplace()\n marketplace.clean(dataset)\n\n\[email protected]()\[email protected]_context\ndef register(ctx):\n \"\"\"Register a new dataset.\n \"\"\"\n marketplace = Marketplace()\n marketplace.register()\n\n\[email protected]()\[email protected](\n '--dataset',\n default=None,\n help='The name of the dataset to ingest from the Data Marketplace.',\n)\[email protected]_context\ndef get_withdraw_amount(ctx, dataset):\n \"\"\"Get withdraw amount owner is entitled to.\n \"\"\"\n marketplace = Marketplace()\n marketplace.get_withdraw_amount(dataset)\n\n\[email protected]()\[email protected](\n '--dataset',\n default=None,\n help='The name of the dataset to ingest from the Data Marketplace.',\n)\[email protected]_context\ndef withdraw(ctx, dataset):\n \"\"\"Withdraw amount you are entitled to.\n \"\"\"\n marketplace = Marketplace()\n marketplace.withdraw(dataset)\n\n\[email protected]()\[email protected](\n '--dataset',\n default=None,\n help='The name of the Marketplace dataset to publish data for.',\n)\[email protected](\n '--datadir',\n default=None,\n help='The folder that contains the CSV data files to publish.',\n)\[email protected](\n '--watch/--no-watch',\n is_flag=True,\n default=False,\n help='Whether to watch the datadir for live data.',\n)\[email protected]_context\ndef publish(ctx, dataset, datadir, watch):\n \"\"\"Publish data for a registered dataset.\n \"\"\"\n marketplace = Marketplace()\n if dataset is None:\n ctx.fail(\"must specify a dataset to publish data for \"\n \" with '--dataset'\\n\")\n if datadir is None:\n ctx.fail(\"must specify a datadir where to find the files to publish \"\n \" with '--datadir'\\n\")\n marketplace.publish(dataset, datadir, watch)\n\n\nif __name__ == '__main__':\n main()\n"
]
| [
[
"pandas.Timestamp.utcnow"
]
]
|
piyushg9794/lux | [
"f5be470f5a4837db2746c950bebe2694665c25dc"
]
| [
"tests/test_compiler.py"
]
| [
"# Copyright 2019-2020 The Lux 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 .context import lux\nimport pytest\nimport pandas as pd\nfrom lux.vis.Vis import Vis\nfrom lux.vis.VisList import VisList\n\n\ndef test_underspecified_no_vis(test_recs):\n no_vis_actions = [\"Correlation\", \"Distribution\", \"Occurrence\", \"Temporal\"]\n df = pd.read_csv(\"lux/data/car.csv\")\n test_recs(df, no_vis_actions)\n assert len(df.current_vis) == 0\n\n # test only one filter context case.\n df.set_intent([lux.Clause(attribute=\"Origin\", filter_op=\"=\", value=\"USA\")])\n test_recs(df, no_vis_actions)\n assert len(df.current_vis) == 0\n\n\ndef test_underspecified_single_vis(test_recs):\n one_vis_actions = [\"Enhance\", \"Filter\", \"Generalize\"]\n df = pd.read_csv(\"lux/data/car.csv\")\n df.set_intent([lux.Clause(attribute=\"MilesPerGal\"), lux.Clause(attribute=\"Weight\")])\n test_recs(df, one_vis_actions)\n assert len(df.current_vis) == 1\n assert df.current_vis[0].mark == \"scatter\"\n for attr in df.current_vis[0]._inferred_intent:\n assert attr.data_model == \"measure\"\n for attr in df.current_vis[0]._inferred_intent:\n assert attr.data_type == \"quantitative\"\n\n\n# def test_underspecified_vis_collection(test_recs):\n# \tmultiple_vis_actions = [\"Current viss\"]\n\n# \tdf = pd.read_csv(\"lux/data/car.csv\")\n# \tdf[\"Year\"] = pd.to_datetime(df[\"Year\"], format='%Y') # change pandas dtype for the column \"Year\" to datetype\n\n# \tdf.set_intent([lux.Clause(attribute = [\"Horsepower\", \"Weight\", \"Acceleration\"]), lux.Clause(attribute =\"Year\", channel=\"x\")])\n# \tassert len(df.current_vis) == 3\n# \tassert df.current_vis[0].mark == \"line\"\n# \tfor vlist in df.current_vis:\n# \t\tassert (vlist.get_attr_by_channel(\"x\")[0].attribute == \"Year\")\n# \ttest_recs(df, multiple_vis_actions)\n\n# \tdf.set_intent([lux.Clause(attribute =\"?\"), lux.Clause(attribute =\"Year\", channel=\"x\")])\n# \tassert len(df.current_vis) == len(list(df.columns)) - 1 # we remove year by year so its 8 vis instead of 9\n# \tfor vlist in df.current_vis:\n# \t\tassert (vlist.get_attr_by_channel(\"x\")[0].attribute == \"Year\")\n# \ttest_recs(df, multiple_vis_actions)\n\n# \tdf.set_intent([lux.Clause(attribute =\"?\", data_type=\"quantitative\"), lux.Clause(attribute =\"Year\")])\n# \tassert len(df.current_vis) == len([vis.get_attr_by_data_type(\"quantitative\") for vis in df.current_vis]) # should be 5\n# \ttest_recs(df, multiple_vis_actions)\n\n# \tdf.set_intent([lux.Clause(attribute =\"?\", data_model=\"measure\"), lux.Clause(attribute=\"MilesPerGal\", channel=\"y\")])\n# \tfor vlist in df.current_vis:\n# \t\tprint (vlist.get_attr_by_channel(\"y\")[0].attribute == \"MilesPerGal\")\n# \ttest_recs(df, multiple_vis_actions)\n\n# \tdf.set_intent([lux.Clause(attribute =\"?\", data_model=\"measure\"), lux.Clause(attribute =\"?\", data_model=\"measure\")])\n# \tassert len(df.current_vis) == len([vis.get_attr_by_data_model(\"measure\") for vis in df.current_vis]) #should be 25\n# \ttest_recs(df, multiple_vis_actions)\ndef test_set_intent_as_vis(test_recs):\n df = pd.read_csv(\"lux/data/car.csv\")\n df._repr_html_()\n vis = df.recommendation[\"Correlation\"][0]\n df.intent = vis\n df._repr_html_()\n test_recs(df, [\"Enhance\", \"Filter\", \"Generalize\"])\n\n\[email protected]\ndef test_recs():\n def test_recs_function(df, actions):\n df._repr_html_()\n assert len(df.recommendation) > 0\n recKeys = list(df.recommendation.keys())\n list_equal(recKeys, actions)\n\n return test_recs_function\n\n\ndef test_parse():\n df = pd.read_csv(\"lux/data/car.csv\")\n vlst = VisList([lux.Clause(\"Origin=?\"), lux.Clause(attribute=\"MilesPerGal\")], df)\n assert len(vlst) == 3\n\n df = pd.read_csv(\"lux/data/car.csv\")\n vlst = VisList([lux.Clause(\"Origin=?\"), lux.Clause(\"MilesPerGal\")], df)\n assert len(vlst) == 3\n\n\ndef test_underspecified_vis_collection_zval():\n # check if the number of charts is correct\n df = pd.read_csv(\"lux/data/car.csv\")\n vlst = VisList(\n [\n lux.Clause(attribute=\"Origin\", filter_op=\"=\", value=\"?\"),\n lux.Clause(attribute=\"MilesPerGal\"),\n ],\n df,\n )\n assert len(vlst) == 3\n\n # does not work\n # df = pd.read_csv(\"lux/data/car.csv\")\n # vlst = VisList([lux.Clause(attribute = [\"Origin\",\"Cylinders\"], filter_op=\"=\",value=\"?\"),lux.Clause(attribute = [\"Horsepower\"]),lux.Clause(attribute = \"Weight\")],df)\n # assert len(vlst) == 8\n\n\ndef test_sort_bar():\n from lux.processor.Compiler import Compiler\n from lux.vis.Vis import Vis\n\n df = pd.read_csv(\"lux/data/car.csv\")\n vis = Vis(\n [\n lux.Clause(attribute=\"Acceleration\", data_model=\"measure\", data_type=\"quantitative\"),\n lux.Clause(attribute=\"Origin\", data_model=\"dimension\", data_type=\"nominal\"),\n ],\n df,\n )\n assert vis.mark == \"bar\"\n assert vis._inferred_intent[1].sort == \"\"\n\n df = pd.read_csv(\"lux/data/car.csv\")\n vis = Vis(\n [\n lux.Clause(attribute=\"Acceleration\", data_model=\"measure\", data_type=\"quantitative\"),\n lux.Clause(attribute=\"Name\", data_model=\"dimension\", data_type=\"nominal\"),\n ],\n df,\n )\n assert vis.mark == \"bar\"\n assert vis._inferred_intent[1].sort == \"ascending\"\n\n\ndef test_specified_vis_collection():\n df = pd.read_csv(\"lux/data/car.csv\")\n # change pandas dtype for the column \"Year\" to datetype\n df[\"Year\"] = pd.to_datetime(df[\"Year\"], format=\"%Y\")\n\n vlst = VisList(\n [\n lux.Clause(attribute=\"Horsepower\"),\n lux.Clause(attribute=\"Brand\"),\n lux.Clause(attribute=\"Origin\", value=[\"Japan\", \"USA\"]),\n ],\n df,\n )\n assert len(vlst) == 2\n\n vlst = VisList(\n [\n lux.Clause(attribute=[\"Horsepower\", \"Weight\"]),\n lux.Clause(attribute=\"Brand\"),\n lux.Clause(attribute=\"Origin\", value=[\"Japan\", \"USA\"]),\n ],\n df,\n )\n assert len(vlst) == 4\n\n # test if z axis has been filtered correctly\n chart_titles = [vis.title for vis in vlst]\n assert \"Origin = USA\" and \"Origin = Japan\" in chart_titles\n assert \"Origin = Europe\" not in chart_titles\n\n\ndef test_specified_channel_enforced_vis_collection():\n df = pd.read_csv(\"lux/data/car.csv\")\n # change pandas dtype for the column \"Year\" to datetype\n df[\"Year\"] = pd.to_datetime(df[\"Year\"], format=\"%Y\")\n visList = VisList(\n [lux.Clause(attribute=\"?\"), lux.Clause(attribute=\"MilesPerGal\", channel=\"x\")],\n df,\n )\n for vis in visList:\n check_attribute_on_channel(vis, \"MilesPerGal\", \"x\")\n\n\ndef test_autoencoding_scatter():\n # No channel specified\n df = pd.read_csv(\"lux/data/car.csv\")\n # change pandas dtype for the column \"Year\" to datetype\n df[\"Year\"] = pd.to_datetime(df[\"Year\"], format=\"%Y\")\n vis = Vis([lux.Clause(attribute=\"MilesPerGal\"), lux.Clause(attribute=\"Weight\")], df)\n check_attribute_on_channel(vis, \"MilesPerGal\", \"x\")\n check_attribute_on_channel(vis, \"Weight\", \"y\")\n\n # Partial channel specified\n vis = Vis(\n [\n lux.Clause(attribute=\"MilesPerGal\", channel=\"y\"),\n lux.Clause(attribute=\"Weight\"),\n ],\n df,\n )\n check_attribute_on_channel(vis, \"MilesPerGal\", \"y\")\n check_attribute_on_channel(vis, \"Weight\", \"x\")\n\n # Full channel specified\n vis = Vis(\n [\n lux.Clause(attribute=\"MilesPerGal\", channel=\"y\"),\n lux.Clause(attribute=\"Weight\", channel=\"x\"),\n ],\n df,\n )\n check_attribute_on_channel(vis, \"MilesPerGal\", \"y\")\n check_attribute_on_channel(vis, \"Weight\", \"x\")\n # Duplicate channel specified\n with pytest.raises(ValueError):\n # Should throw error because there should not be columns with the same channel specified\n df.set_intent(\n [\n lux.Clause(attribute=\"MilesPerGal\", channel=\"x\"),\n lux.Clause(attribute=\"Weight\", channel=\"x\"),\n ]\n )\n\n\ndef test_autoencoding_histogram():\n # No channel specified\n df = pd.read_csv(\"lux/data/car.csv\")\n # change pandas dtype for the column \"Year\" to datetype\n df[\"Year\"] = pd.to_datetime(df[\"Year\"], format=\"%Y\")\n vis = Vis([lux.Clause(attribute=\"MilesPerGal\", channel=\"y\")], df)\n check_attribute_on_channel(vis, \"MilesPerGal\", \"y\")\n\n vis = Vis([lux.Clause(attribute=\"MilesPerGal\", channel=\"x\")], df)\n assert vis.get_attr_by_channel(\"x\")[0].attribute == \"MilesPerGal\"\n assert vis.get_attr_by_channel(\"y\")[0].attribute == \"Record\"\n\n\ndef test_autoencoding_line_chart():\n df = pd.read_csv(\"lux/data/car.csv\")\n # change pandas dtype for the column \"Year\" to datetype\n df[\"Year\"] = pd.to_datetime(df[\"Year\"], format=\"%Y\")\n vis = Vis([lux.Clause(attribute=\"Year\"), lux.Clause(attribute=\"Acceleration\")], df)\n check_attribute_on_channel(vis, \"Year\", \"x\")\n check_attribute_on_channel(vis, \"Acceleration\", \"y\")\n\n # Partial channel specified\n vis = Vis(\n [\n lux.Clause(attribute=\"Year\", channel=\"y\"),\n lux.Clause(attribute=\"Acceleration\"),\n ],\n df,\n )\n check_attribute_on_channel(vis, \"Year\", \"y\")\n check_attribute_on_channel(vis, \"Acceleration\", \"x\")\n\n # Full channel specified\n vis = Vis(\n [\n lux.Clause(attribute=\"Year\", channel=\"y\"),\n lux.Clause(attribute=\"Acceleration\", channel=\"x\"),\n ],\n df,\n )\n check_attribute_on_channel(vis, \"Year\", \"y\")\n check_attribute_on_channel(vis, \"Acceleration\", \"x\")\n\n with pytest.raises(ValueError):\n # Should throw error because there should not be columns with the same channel specified\n df.set_intent(\n [\n lux.Clause(attribute=\"Year\", channel=\"x\"),\n lux.Clause(attribute=\"Acceleration\", channel=\"x\"),\n ]\n )\n\n\ndef test_autoencoding_color_line_chart():\n df = pd.read_csv(\"lux/data/car.csv\")\n # change pandas dtype for the column \"Year\" to datetype\n df[\"Year\"] = pd.to_datetime(df[\"Year\"], format=\"%Y\")\n intent = [\n lux.Clause(attribute=\"Year\"),\n lux.Clause(attribute=\"Acceleration\"),\n lux.Clause(attribute=\"Origin\"),\n ]\n vis = Vis(intent, df)\n check_attribute_on_channel(vis, \"Year\", \"x\")\n check_attribute_on_channel(vis, \"Acceleration\", \"y\")\n check_attribute_on_channel(vis, \"Origin\", \"color\")\n\n\ndef test_autoencoding_color_scatter_chart():\n df = pd.read_csv(\"lux/data/car.csv\")\n # change pandas dtype for the column \"Year\" to datetype\n df[\"Year\"] = pd.to_datetime(df[\"Year\"], format=\"%Y\")\n vis = Vis(\n [\n lux.Clause(attribute=\"Horsepower\"),\n lux.Clause(attribute=\"Acceleration\"),\n lux.Clause(attribute=\"Origin\"),\n ],\n df,\n )\n check_attribute_on_channel(vis, \"Origin\", \"color\")\n\n vis = Vis(\n [\n lux.Clause(attribute=\"Horsepower\"),\n lux.Clause(attribute=\"Acceleration\", channel=\"color\"),\n lux.Clause(attribute=\"Origin\"),\n ],\n df,\n )\n check_attribute_on_channel(vis, \"Acceleration\", \"color\")\n\n\ndef test_populate_options():\n from lux.processor.Compiler import Compiler\n\n df = pd.read_csv(\"lux/data/car.csv\")\n df.set_intent([lux.Clause(attribute=\"?\"), lux.Clause(attribute=\"MilesPerGal\")])\n col_set = set()\n for specOptions in Compiler.populate_wildcard_options(df._intent, df)[\"attributes\"]:\n for clause in specOptions:\n col_set.add(clause.attribute)\n assert list_equal(list(col_set), list(df.columns))\n\n df.set_intent(\n [\n lux.Clause(attribute=\"?\", data_model=\"measure\"),\n lux.Clause(attribute=\"MilesPerGal\"),\n ]\n )\n df._repr_html_()\n col_set = set()\n for specOptions in Compiler.populate_wildcard_options(df._intent, df)[\"attributes\"]:\n for clause in specOptions:\n col_set.add(clause.attribute)\n assert list_equal(\n list(col_set),\n [\"Acceleration\", \"Weight\", \"Horsepower\", \"MilesPerGal\", \"Displacement\"],\n )\n\n\ndef test_remove_all_invalid():\n df = pd.read_csv(\"lux/data/car.csv\")\n df[\"Year\"] = pd.to_datetime(df[\"Year\"], format=\"%Y\")\n # with pytest.warns(UserWarning,match=\"duplicate attribute specified in the intent\"):\n df.set_intent(\n [\n lux.Clause(attribute=\"Origin\", filter_op=\"=\", value=\"USA\"),\n lux.Clause(attribute=\"Origin\"),\n ]\n )\n df._repr_html_()\n assert len(df.current_vis) == 0\n\n\ndef list_equal(l1, l2):\n l1.sort()\n l2.sort()\n return l1 == l2\n\n\ndef check_attribute_on_channel(vis, attr_name, channelName):\n assert vis.get_attr_by_channel(channelName)[0].attribute == attr_name\n"
]
| [
[
"pandas.to_datetime",
"pandas.read_csv"
]
]
|
AlexGabourie/thermo | [
"6df7a1b119d09c76f37e86dc2935f12931a5d71b"
]
| [
"thermo/lammps/calc.py"
]
| [
"import numpy as np\nimport os\nfrom scipy import integrate\nfrom math import floor\nimport scipy.io as sio\nfrom thermo.math.correlate import autocorr\n\n__author__ = \"Alexander Gabourie\"\n__email__ = \"[email protected]\"\n\n\ndef __metal_to_SI(vol, T):\n \"\"\"\n Converts LAMMPS metal units to SI units for thermal conductivity calculations.\n\n Args:\n vol (float):\n Volume in angstroms^3\n\n T (float):\n Temperature in K\n\n Returns:\n float: Converted value\n \"\"\"\n kb = 1.38064852e-23 # m3*kg/(s2*K)\n vol = vol/(1.0e10)**3 # to m3\n # eV2*ns/(ps2*A4) to J2/(s*m4)\n to_SI = (1.602e-19)**2.*1.0e12*(1.0e10)**4.0*1000.\n return vol*to_SI/(kb*T**2)\n\n\ndef get_heat_flux(directory='.', heatflux_file='heat_out.heatflux', mat_file='heat_flux.mat'):\n \"\"\"\n Gets the heat flux from a LAMMPS EMD simulation. Creates a compressed .mat\n file if only in text form. Loads .mat form if exists.\n\n Args:\n directory (str):\n Directory of simulation results\n\n heatflux_file (str):\n Filename of heatflux output\n\n mat_file (str):\n MATLAB file to load, if exists, or save to, if does not exist.\n Default save name of 'heat_flux.mat'\n\n Returns:\n dict: Dictionary with heat flux data\n\n .. csv-table:: Output dictionary (metal units)\n :stub-columns: 1\n\n **key**,jx,jy,jz,rate\n **units**,|j1|,|j1|,|j1|,timestep\n\n .. |j1| replace:: eV ps\\ :sup:`-1` A\\ :sup:`-2`\n \"\"\"\n heatflux_file = os.path.join(directory, heatflux_file)\n mat_file = os.path.join(directory, mat_file)\n\n # Check that directory exists\n if not os.path.isdir(directory):\n raise IOError('The path: {} is not a directory.'.format(directory))\n\n # Go to directory and see if imported .mat file already exists\n if os.path.isfile(mat_file) and mat_file.endswith('.mat'):\n return sio.loadmat(mat_file)\n\n # Continue with the import since .mat file\n if not os.path.isfile(heatflux_file):\n raise IOError('The file: \\'{}{}\\' is not found.'.format(directory,heatflux_file))\n\n # Read the file\n with open(heatflux_file, 'r') as hf_file:\n lines = hf_file.readlines()[2:]\n\n num_elem = len(lines)\n\n # Get timestep\n rate = int(lines[0].split()[0])\n\n # read all data\n jx = np.zeros(num_elem)\n jy = np.zeros(num_elem)\n jz = np.zeros(num_elem)\n for i,line in enumerate(lines):\n vals = line.split()\n jx[i] = float(vals[1])\n jy[i] = float(vals[2])\n jz[i] = float(vals[3])\n\n output = {'jx':jx, 'jy':jy, 'jz':jz, 'rate':rate}\n sio.savemat(mat_file, output)\n return output\n\n\ndef get_GKTC(directory='.', T=300, vol=1, dt=None, rate=None, tau=None,\n heatflux_file='heat_out.heatflux',mat_file='heat_flux.mat'):\n \"\"\"\n Calculates the thermal conductivity (TC) using the Green-Kubo (GK) formalism.\n The 'metal' units in LAMMPS must be used.\n\n Args:\n directory (string):\n Directory of simulation\n\n T (float):\n Temperature of simulation. Units of K\n\n vol (float):\n Volume of the simulation cell. Units of A^3\n\n dt (float):\n Timestep of the of simulation. Units are fs\n\n rate (int):\n Rate at which the heat flux is sampled in number of timesteps. Default of rate=dt\n\n tau (int):\n max lag time to integrate over. Units of ns and default of tau=total time\n\n heatflux_file (str):\n Heatflux output filename.\n\n mat_file (str):\n MATLAB file to load, if exists, or save to, if does not exist.\n Default save name of 'heat_flux.mat'\n\n Returns:\n dict: Dictionary with Green-Kubo thermal conductivity data\n\n .. csv-table:: Output dictionary\n :stub-columns: 1\n\n **key**,kx,ky,kz,t,dt,T,V,jxjx,jyjy,jzjz,tot_time,tau,srate,directory\n **units**,|gk1|,|gk1|,|gk1|,ns,fs,K,|gk2|,|gk3|,|gk3|,|gk3|,ns,ns,ns,N/A\n\n .. |gk1| replace:: Wm\\ :sup:`-1` K\\ :sup:`-1`\n .. |gk2| replace:: A\\ :sup:`3`\n .. |gk3| replace:: (eV ps\\ :sup:`-1` A\\ :sup:`-2`)\\ :sup:`2`\n \"\"\"\n # Check that directory exists\n if not os.path.isdir(directory):\n raise IOError('The path: {} is not a directory.'.format(directory))\n\n # get heat flux, pass args\n hf = get_heat_flux(directory, heatflux_file,mat_file)\n jx = np.squeeze(hf['jx'])\n jy = np.squeeze(hf['jy'])\n jz = np.squeeze(hf['jz'])\n\n scale = __metal_to_SI(vol, T)\n\n # Set timestep if not set\n if dt is None:\n dt = 1.0e-6 # [ns]\n else:\n dt = dt*1.0e-6 # [fs] -> [ns]\n\n # set the heat flux sampling rate: rate*timestep*scaling\n srate = rate*dt # [ns]\n\n # Calculate total time\n tot_time = srate*(len(jx)-1) # [ns]\n\n # set the integration limit (i.e. tau)\n if tau is None:\n tau = tot_time # [ns]\n\n max_lag = int(floor(tau/(srate)))\n t = np.squeeze(np.linspace(0, (max_lag)*srate, max_lag+1)) # [ns]\n\n jxjx = autocorr(np.squeeze(jx).astype(np.complex128), max_lag)\n jyjy = autocorr(np.squeeze(jy).astype(np.complex128), max_lag)\n jzjz = autocorr(np.squeeze(jz).astype(np.complex128), max_lag)\n\n kx = integrate.cumtrapz(jxjx, t, initial=0)*scale\n ky = integrate.cumtrapz(jyjy, t, initial=0)*scale\n kz = integrate.cumtrapz(jzjz, t, initial=0)*scale\n\n dt /= 1e6 # [ns] -> [fs]\n\n return {'kx':kx, 'ky':ky, 'kz':kz, 't':t, 'directory':directory,\n 'dt':dt, 'tot_time':tot_time,'tau':tau, 'T':T,\n 'V':vol, 'srate':srate, 'jxjx':jxjx, 'jyjy':jyjy, 'jzjz':jzjz}\n"
]
| [
[
"numpy.zeros",
"scipy.io.loadmat",
"scipy.integrate.cumtrapz",
"scipy.io.savemat",
"numpy.linspace",
"numpy.squeeze"
]
]
|
prosello/rllab | [
"8677356874d41eb9354785500b554eaf635ece2e"
]
| [
"rllab/spaces/product.py"
]
| [
"from rllab.spaces.base import Space\nimport numpy as np\nfrom rllab.misc import ext\n\n\nclass Product(Space):\n\n def __init__(self, *components):\n if isinstance(components[0], (list, tuple)):\n assert len(components) == 1\n components = components[0]\n self._components = tuple(components)\n dtypes = [c.new_tensor_variable(\"tmp\", extra_dims=0).dtype for c in components]\n self._common_dtype = np.core.numerictypes.find_common_type([], dtypes)\n\n def sample(self):\n return tuple(x.sample() for x in self._components)\n\n @property\n def components(self):\n return self._components\n\n def contains(self, x):\n return isinstance(x, tuple) and all(c.contains(xi) for c, xi in zip(self._components, x))\n\n def new_tensor_variable(self, name, extra_dims):\n return ext.new_tensor(\n name=name,\n ndim=extra_dims+1,\n dtype=self._common_dtype,\n )\n\n @property\n def flat_dim(self):\n return np.sum([c.flat_dim for c in self._components])\n\n def flatten(self, x):\n return np.concatenate([c.flatten(xi) for c, xi in zip(self._components, x)])\n\n def flatten_n(self, xs):\n xs_regrouped = [[x[i] for x in xs] for i in xrange(len(xs[0]))]\n flat_regrouped = [c.flatten_n(xi) for c, xi in zip(self.components, xs_regrouped)]\n return np.concatenate(flat_regrouped, axis=-1)\n\n def unflatten(self, x):\n dims = [c.flat_dim for c in self._components]\n flat_xs = np.split(x, np.cumsum(dims)[:-1])\n return tuple(c.unflatten(xi) for c, xi in zip(self._components, flat_xs))\n\n def unflatten_n(self, xs):\n dims = [c.flat_dim for c in self._components]\n flat_xs = np.split(xs, np.cumsum(dims)[:-1], axis=-1)\n unflat_xs = [c.unflatten_n(xi) for c, xi in zip(self.components, flat_xs)]\n unflat_xs_grouped = zip(*unflat_xs)\n return unflat_xs_grouped\n\n def __eq__(self, other):\n if not isinstance(other, Product):\n return False\n return tuple(self.components) == tuple(other.components)\n\n def __hash__(self):\n return hash(tuple(self.components))\n"
]
| [
[
"numpy.concatenate",
"numpy.core.numerictypes.find_common_type",
"numpy.sum",
"numpy.cumsum"
]
]
|
Pratik325/seaborn | [
"f123d9b9f46caea4942f392e8f8d1805c121fe01"
]
| [
"seaborn/tests/test_palettes.py"
]
| [
"import colorsys\nimport numpy as np\nimport matplotlib as mpl\n\nimport pytest\nimport nose.tools as nt\nimport numpy.testing as npt\n\nfrom .. import palettes, utils, rcmod\nfrom ..external import husl\nfrom ..colors import xkcd_rgb, crayons\n\n\nclass TestColorPalettes(object):\n\n def test_current_palette(self):\n\n pal = palettes.color_palette([\"red\", \"blue\", \"green\"])\n rcmod.set_palette(pal)\n assert pal == utils.get_color_cycle()\n rcmod.set()\n\n def test_palette_context(self):\n\n default_pal = palettes.color_palette()\n context_pal = palettes.color_palette(\"muted\")\n\n with palettes.color_palette(context_pal):\n nt.assert_equal(utils.get_color_cycle(), context_pal)\n\n nt.assert_equal(utils.get_color_cycle(), default_pal)\n\n def test_big_palette_context(self):\n\n original_pal = palettes.color_palette(\"deep\", n_colors=8)\n context_pal = palettes.color_palette(\"husl\", 10)\n\n rcmod.set_palette(original_pal)\n with palettes.color_palette(context_pal, 10):\n nt.assert_equal(utils.get_color_cycle(), context_pal)\n\n nt.assert_equal(utils.get_color_cycle(), original_pal)\n\n # Reset default\n rcmod.set()\n\n def test_palette_size(self):\n\n pal = palettes.color_palette(\"deep\")\n assert len(pal) == palettes.QUAL_PALETTE_SIZES[\"deep\"]\n\n pal = palettes.color_palette(\"pastel6\")\n assert len(pal) == palettes.QUAL_PALETTE_SIZES[\"pastel6\"]\n\n pal = palettes.color_palette(\"Set3\")\n assert len(pal) == palettes.QUAL_PALETTE_SIZES[\"Set3\"]\n\n pal = palettes.color_palette(\"husl\")\n assert len(pal) == 6\n\n pal = palettes.color_palette(\"Greens\")\n assert len(pal) == 6\n\n def test_seaborn_palettes(self):\n\n pals = \"deep\", \"muted\", \"pastel\", \"bright\", \"dark\", \"colorblind\"\n for name in pals:\n full = palettes.color_palette(name, 10).as_hex()\n short = palettes.color_palette(name + \"6\", 6).as_hex()\n b, _, g, r, m, _, _, _, y, c = full\n assert [b, g, r, m, y, c] == list(short)\n\n def test_hls_palette(self):\n\n pal1 = palettes.hls_palette()\n pal2 = palettes.color_palette(\"hls\")\n npt.assert_array_equal(pal1, pal2)\n\n cmap1 = palettes.hls_palette(as_cmap=True)\n cmap2 = palettes.color_palette(\"hls\", as_cmap=True)\n npt.assert_array_equal(cmap1([.2, .8]), cmap2([.2, .8]))\n\n def test_husl_palette(self):\n\n pal1 = palettes.husl_palette()\n pal2 = palettes.color_palette(\"husl\")\n npt.assert_array_equal(pal1, pal2)\n\n cmap1 = palettes.husl_palette(as_cmap=True)\n cmap2 = palettes.color_palette(\"husl\", as_cmap=True)\n npt.assert_array_equal(cmap1([.2, .8]), cmap2([.2, .8]))\n\n def test_mpl_palette(self):\n\n pal1 = palettes.mpl_palette(\"Reds\")\n pal2 = palettes.color_palette(\"Reds\")\n npt.assert_array_equal(pal1, pal2)\n\n cmap1 = mpl.cm.get_cmap(\"Reds\")\n cmap2 = palettes.mpl_palette(\"Reds\", as_cmap=True)\n cmap3 = palettes.color_palette(\"Reds\", as_cmap=True)\n npt.assert_array_equal(cmap1, cmap2)\n npt.assert_array_equal(cmap1, cmap3)\n\n def test_mpl_dark_palette(self):\n\n mpl_pal1 = palettes.mpl_palette(\"Blues_d\")\n mpl_pal2 = palettes.color_palette(\"Blues_d\")\n npt.assert_array_equal(mpl_pal1, mpl_pal2)\n\n mpl_pal1 = palettes.mpl_palette(\"Blues_r_d\")\n mpl_pal2 = palettes.color_palette(\"Blues_r_d\")\n npt.assert_array_equal(mpl_pal1, mpl_pal2)\n\n def test_bad_palette_name(self):\n\n with nt.assert_raises(ValueError):\n palettes.color_palette(\"IAmNotAPalette\")\n\n def test_terrible_palette_name(self):\n\n with nt.assert_raises(ValueError):\n palettes.color_palette(\"jet\")\n\n def test_bad_palette_colors(self):\n\n pal = [\"red\", \"blue\", \"iamnotacolor\"]\n with nt.assert_raises(ValueError):\n palettes.color_palette(pal)\n\n def test_palette_desat(self):\n\n pal1 = palettes.husl_palette(6)\n pal1 = [utils.desaturate(c, .5) for c in pal1]\n pal2 = palettes.color_palette(\"husl\", desat=.5)\n npt.assert_array_equal(pal1, pal2)\n\n def test_palette_is_list_of_tuples(self):\n\n pal_in = np.array([\"red\", \"blue\", \"green\"])\n pal_out = palettes.color_palette(pal_in, 3)\n\n nt.assert_is_instance(pal_out, list)\n nt.assert_is_instance(pal_out[0], tuple)\n nt.assert_is_instance(pal_out[0][0], float)\n nt.assert_equal(len(pal_out[0]), 3)\n\n def test_palette_cycles(self):\n\n deep = palettes.color_palette(\"deep6\")\n double_deep = palettes.color_palette(\"deep6\", 12)\n nt.assert_equal(double_deep, deep + deep)\n\n def test_hls_values(self):\n\n pal1 = palettes.hls_palette(6, h=0)\n pal2 = palettes.hls_palette(6, h=.5)\n pal2 = pal2[3:] + pal2[:3]\n npt.assert_array_almost_equal(pal1, pal2)\n\n pal_dark = palettes.hls_palette(5, l=.2) # noqa\n pal_bright = palettes.hls_palette(5, l=.8) # noqa\n npt.assert_array_less(list(map(sum, pal_dark)),\n list(map(sum, pal_bright)))\n\n pal_flat = palettes.hls_palette(5, s=.1)\n pal_bold = palettes.hls_palette(5, s=.9)\n npt.assert_array_less(list(map(np.std, pal_flat)),\n list(map(np.std, pal_bold)))\n\n def test_husl_values(self):\n\n pal1 = palettes.husl_palette(6, h=0)\n pal2 = palettes.husl_palette(6, h=.5)\n pal2 = pal2[3:] + pal2[:3]\n npt.assert_array_almost_equal(pal1, pal2)\n\n pal_dark = palettes.husl_palette(5, l=.2) # noqa\n pal_bright = palettes.husl_palette(5, l=.8) # noqa\n npt.assert_array_less(list(map(sum, pal_dark)),\n list(map(sum, pal_bright)))\n\n pal_flat = palettes.husl_palette(5, s=.1)\n pal_bold = palettes.husl_palette(5, s=.9)\n npt.assert_array_less(list(map(np.std, pal_flat)),\n list(map(np.std, pal_bold)))\n\n def test_cbrewer_qual(self):\n\n pal_short = palettes.mpl_palette(\"Set1\", 4)\n pal_long = palettes.mpl_palette(\"Set1\", 6)\n nt.assert_equal(pal_short, pal_long[:4])\n\n pal_full = palettes.mpl_palette(\"Set2\", 8)\n pal_long = palettes.mpl_palette(\"Set2\", 10)\n nt.assert_equal(pal_full, pal_long[:8])\n\n def test_mpl_reversal(self):\n\n pal_forward = palettes.mpl_palette(\"BuPu\", 6)\n pal_reverse = palettes.mpl_palette(\"BuPu_r\", 6)\n npt.assert_array_almost_equal(pal_forward, pal_reverse[::-1])\n\n def test_rgb_from_hls(self):\n\n color = .5, .8, .4\n rgb_got = palettes._color_to_rgb(color, \"hls\")\n rgb_want = colorsys.hls_to_rgb(*color)\n nt.assert_equal(rgb_got, rgb_want)\n\n def test_rgb_from_husl(self):\n\n color = 120, 50, 40\n rgb_got = palettes._color_to_rgb(color, \"husl\")\n rgb_want = tuple(husl.husl_to_rgb(*color))\n assert rgb_got == rgb_want\n\n for h in range(0, 360):\n color = h, 100, 100\n rgb = palettes._color_to_rgb(color, \"husl\")\n assert min(rgb) >= 0\n assert max(rgb) <= 1\n\n def test_rgb_from_xkcd(self):\n\n color = \"dull red\"\n rgb_got = palettes._color_to_rgb(color, \"xkcd\")\n rgb_want = mpl.colors.to_rgb(xkcd_rgb[color])\n nt.assert_equal(rgb_got, rgb_want)\n\n def test_light_palette(self):\n\n pal_forward = palettes.light_palette(\"red\")\n pal_reverse = palettes.light_palette(\"red\", reverse=True)\n assert np.allclose(pal_forward, pal_reverse[::-1])\n\n red = mpl.colors.colorConverter.to_rgb(\"red\")\n assert pal_forward[-1] == red\n\n pal_cmap = palettes.light_palette(\"blue\", as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)\n\n pal_cmap_from_string = palettes.color_palette(\"light:blue\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)\n\n pal_cmap = palettes.light_palette(\"blue\", as_cmap=True, reverse=True)\n pal_cmap_from_string = palettes.color_palette(\"light:blue_r\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)\n\n def test_dark_palette(self):\n\n pal_forward = palettes.dark_palette(\"red\")\n pal_reverse = palettes.dark_palette(\"red\", reverse=True)\n assert np.allclose(pal_forward, pal_reverse[::-1])\n\n red = mpl.colors.colorConverter.to_rgb(\"red\")\n assert pal_forward[-1] == red\n\n pal_cmap = palettes.dark_palette(\"blue\", as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)\n\n pal_cmap_from_string = palettes.color_palette(\"dark:blue\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)\n\n pal_cmap = palettes.dark_palette(\"blue\", as_cmap=True, reverse=True)\n pal_cmap_from_string = palettes.color_palette(\"dark:blue_r\", as_cmap=True)\n assert pal_cmap(.8) == pal_cmap_from_string(.8)\n\n def test_diverging_palette(self):\n\n h_neg, h_pos = 100, 200\n sat, lum = 70, 50\n args = h_neg, h_pos, sat, lum\n\n n = 12\n pal = palettes.diverging_palette(*args, n=n)\n neg_pal = palettes.light_palette((h_neg, sat, lum), int(n // 2),\n input=\"husl\")\n pos_pal = palettes.light_palette((h_pos, sat, lum), int(n // 2),\n input=\"husl\")\n assert len(pal) == n\n assert pal[0] == neg_pal[-1]\n assert pal[-1] == pos_pal[-1]\n\n pal_dark = palettes.diverging_palette(*args, n=n, center=\"dark\")\n assert np.mean(pal[int(n / 2)]) > np.mean(pal_dark[int(n / 2)])\n\n pal_cmap = palettes.diverging_palette(*args, as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)\n\n def test_blend_palette(self):\n\n colors = [\"red\", \"yellow\", \"white\"]\n pal_cmap = palettes.blend_palette(colors, as_cmap=True)\n assert isinstance(pal_cmap, mpl.colors.LinearSegmentedColormap)\n\n colors = [\"red\", \"blue\"]\n pal = palettes.blend_palette(colors)\n pal_str = \"blend:\" + \",\".join(colors)\n pal_from_str = palettes.color_palette(pal_str)\n assert pal == pal_from_str\n\n def test_cubehelix_against_matplotlib(self):\n\n x = np.linspace(0, 1, 8)\n mpl_pal = mpl.cm.cubehelix(x)[:, :3].tolist()\n\n sns_pal = palettes.cubehelix_palette(8, start=0.5, rot=-1.5, hue=1,\n dark=0, light=1, reverse=True)\n\n nt.assert_list_equal(sns_pal, mpl_pal)\n\n def test_cubehelix_n_colors(self):\n\n for n in [3, 5, 8]:\n pal = palettes.cubehelix_palette(n)\n nt.assert_equal(len(pal), n)\n\n def test_cubehelix_reverse(self):\n\n pal_forward = palettes.cubehelix_palette()\n pal_reverse = palettes.cubehelix_palette(reverse=True)\n nt.assert_list_equal(pal_forward, pal_reverse[::-1])\n\n def test_cubehelix_cmap(self):\n\n cmap = palettes.cubehelix_palette(as_cmap=True)\n nt.assert_is_instance(cmap, mpl.colors.ListedColormap)\n pal = palettes.cubehelix_palette()\n x = np.linspace(0, 1, 6)\n npt.assert_array_equal(cmap(x)[:, :3], pal)\n\n cmap_rev = palettes.cubehelix_palette(as_cmap=True, reverse=True)\n x = np.linspace(0, 1, 6)\n pal_forward = cmap(x).tolist()\n pal_reverse = cmap_rev(x[::-1]).tolist()\n nt.assert_list_equal(pal_forward, pal_reverse)\n\n def test_cubehelix_code(self):\n\n color_palette = palettes.color_palette\n cubehelix_palette = palettes.cubehelix_palette\n\n pal1 = color_palette(\"ch:\", 8)\n pal2 = color_palette(cubehelix_palette(8))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:.5, -.25,hue = .5,light=.75\", 8)\n pal2 = color_palette(cubehelix_palette(8, .5, -.25, hue=.5, light=.75))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:h=1,r=.5\", 9)\n pal2 = color_palette(cubehelix_palette(9, hue=1, rot=.5))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:_r\", 6)\n pal2 = color_palette(cubehelix_palette(6, reverse=True))\n assert pal1 == pal2\n\n pal1 = color_palette(\"ch:_r\", as_cmap=True)\n pal2 = cubehelix_palette(6, reverse=True, as_cmap=True)\n assert pal1(.5) == pal2(.5)\n\n def test_xkcd_palette(self):\n\n names = list(xkcd_rgb.keys())[10:15]\n colors = palettes.xkcd_palette(names)\n for name, color in zip(names, colors):\n as_hex = mpl.colors.rgb2hex(color)\n nt.assert_equal(as_hex, xkcd_rgb[name])\n\n def test_crayon_palette(self):\n\n names = list(crayons.keys())[10:15]\n colors = palettes.crayon_palette(names)\n for name, color in zip(names, colors):\n as_hex = mpl.colors.rgb2hex(color)\n nt.assert_equal(as_hex, crayons[name].lower())\n\n def test_color_codes(self):\n\n palettes.set_color_codes(\"deep\")\n colors = palettes.color_palette(\"deep6\") + [\".1\"]\n for code, color in zip(\"bgrmyck\", colors):\n rgb_want = mpl.colors.colorConverter.to_rgb(color)\n rgb_got = mpl.colors.colorConverter.to_rgb(code)\n nt.assert_equal(rgb_want, rgb_got)\n palettes.set_color_codes(\"reset\")\n\n with pytest.raises(ValueError):\n palettes.set_color_codes(\"Set1\")\n\n def test_as_hex(self):\n\n pal = palettes.color_palette(\"deep\")\n for rgb, hex in zip(pal, pal.as_hex()):\n nt.assert_equal(mpl.colors.rgb2hex(rgb), hex)\n\n def test_preserved_palette_length(self):\n\n pal_in = palettes.color_palette(\"Set1\", 10)\n pal_out = palettes.color_palette(pal_in)\n nt.assert_equal(pal_in, pal_out)\n\n def test_html_rep(self):\n\n pal = palettes.color_palette()\n html = pal._repr_html_()\n for color in pal.as_hex():\n assert color in html\n"
]
| [
[
"numpy.array",
"matplotlib.cm.get_cmap",
"numpy.testing.assert_array_equal",
"matplotlib.colors.rgb2hex",
"matplotlib.colors.colorConverter.to_rgb",
"numpy.testing.assert_array_almost_equal",
"numpy.allclose",
"matplotlib.colors.to_rgb",
"numpy.linspace",
"matplotlib.cm.cubehelix"
]
]
|
zfar-/baselines | [
"a565e28b4d12f18f6784e3db402e0f27f5e09fd6"
]
| [
"baselines/common/distributions.py"
]
| [
"import tensorflow as tf\nimport numpy as np\nimport baselines.common.tf_util as U\nfrom baselines.a2c.utils import fc, fcNoisy\nfrom tensorflow.python.ops import math_ops\n\nclass Pd(object):\n \"\"\"\n A particular probability distribution\n \"\"\"\n def flatparam(self):\n raise NotImplementedError\n def mode(self):\n raise NotImplementedError\n def neglogp(self, x):\n # Usually it's easier to define the negative logprob\n raise NotImplementedError\n def kl(self, other):\n raise NotImplementedError\n def entropy(self):\n raise NotImplementedError\n def sample(self):\n raise NotImplementedError\n def logp(self, x):\n return - self.neglogp(x)\n def get_shape(self):\n return self.flatparam().shape\n @property\n def shape(self):\n return self.get_shape()\n def __getitem__(self, idx):\n return self.__class__(self.flatparam()[idx])\n\nclass PdType(object):\n \"\"\"\n Parametrized family of probability distributions\n \"\"\"\n def pdclass(self):\n raise NotImplementedError\n def pdfromflat(self, flat):\n return self.pdclass()(flat)\n def pdfromlatent(self, latent_vector, init_scale, init_bias):\n raise NotImplementedError\n def param_shape(self):\n raise NotImplementedError\n def sample_shape(self):\n raise NotImplementedError\n def sample_dtype(self):\n raise NotImplementedError\n\n def param_placeholder(self, prepend_shape, name=None):\n return tf.placeholder(dtype=tf.float32, shape=prepend_shape+self.param_shape(), name=name)\n def sample_placeholder(self, prepend_shape, name=None):\n return tf.placeholder(dtype=self.sample_dtype(), shape=prepend_shape+self.sample_shape(), name=name)\n\n def __eq__(self, other):\n return (type(self) == type(other)) and (self.__dict__ == other.__dict__)\n\nclass CategoricalPdType(PdType):\n def __init__(self, ncat):\n self.ncat = ncat\n def pdclass(self):\n return CategoricalPd\n \n # > correct version of action noise\n def pdfromlatent(self, latent_vector, init_scale=1.0, init_bias=0.0,Newbie=1.0,Noise=0.0,sigma=0.0):\n pdparam,fakepdparm = fcNoisy(latent_vector, 'pi', self.ncat, init_scale=init_scale, init_bias=init_bias,newbie=Newbie,noise=Noise,sigma=sigma)\n # pi , pi'\n return self.pdfromflat(fakepdparm), fakepdparm, self.pdfromflat(pdparam) ,pdparam \n # a_t' , a_t , pi' , pi \n\n # > correct version of action noise\n\n # def pdfromlatent(self, latent_vector, init_scale=1.0, init_bias=0.0):\n # # > action noise fc layer\n # pdparam = fcNoisy(latent_vector, 'pi', self.ncat, init_scale=init_scale, init_bias=init_bias,newbie=Newbie,noise=Noise,sigma=sigma)\n # # pdparam = _matching_fc(latent_vector, 'pi', self.ncat, init_scale=init_scale, init_bias=init_bias)\n # return self.pdfromflat(pdparam), pdparam\n\n def param_shape(self):\n return [self.ncat]\n def sample_shape(self):\n return []\n def sample_dtype(self):\n return tf.int32\n\n\nclass MultiCategoricalPdType(PdType):\n def __init__(self, nvec):\n self.ncats = nvec\n def pdclass(self):\n return MultiCategoricalPd\n def pdfromflat(self, flat):\n return MultiCategoricalPd(self.ncats, flat)\n\n def pdfromlatent(self, latent, init_scale=1.0, init_bias=0.0):\n pdparam = _matching_fc(latent, 'pi', self.ncats.sum(), init_scale=init_scale, init_bias=init_bias)\n return self.pdfromflat(pdparam), pdparam\n\n def param_shape(self):\n return [sum(self.ncats)]\n def sample_shape(self):\n return [len(self.ncats)]\n def sample_dtype(self):\n return tf.int32\n\nclass DiagGaussianPdType(PdType):\n def __init__(self, size):\n self.size = size\n def pdclass(self):\n return DiagGaussianPd\n\n def pdfromlatent(self, latent_vector, init_scale=1.0, init_bias=0.0):\n mean = _matching_fc(latent_vector, 'pi', self.size, init_scale=init_scale, init_bias=init_bias)\n logstd = tf.get_variable(name='pi/logstd', shape=[1, self.size], initializer=tf.zeros_initializer())\n pdparam = tf.concat([mean, mean * 0.0 + logstd], axis=1)\n return self.pdfromflat(pdparam), mean\n\n def param_shape(self):\n return [2*self.size]\n def sample_shape(self):\n return [self.size]\n def sample_dtype(self):\n return tf.float32\n\nclass BernoulliPdType(PdType):\n def __init__(self, size):\n self.size = size\n def pdclass(self):\n return BernoulliPd\n def param_shape(self):\n return [self.size]\n def sample_shape(self):\n return [self.size]\n def sample_dtype(self):\n return tf.int32\n def pdfromlatent(self, latent_vector, init_scale=1.0, init_bias=0.0):\n pdparam = _matching_fc(latent_vector, 'pi', self.size, init_scale=init_scale, init_bias=init_bias)\n return self.pdfromflat(pdparam), pdparam\n\n# WRONG SECOND DERIVATIVES\n# class CategoricalPd(Pd):\n# def __init__(self, logits):\n# self.logits = logits\n# self.ps = tf.nn.softmax(logits)\n# @classmethod\n# def fromflat(cls, flat):\n# return cls(flat)\n# def flatparam(self):\n# return self.logits\n# def mode(self):\n# return U.argmax(self.logits, axis=-1)\n# def logp(self, x):\n# return -tf.nn.sparse_softmax_cross_entropy_with_logits(self.logits, x)\n# def kl(self, other):\n# return tf.nn.softmax_cross_entropy_with_logits(other.logits, self.ps) \\\n# - tf.nn.softmax_cross_entropy_with_logits(self.logits, self.ps)\n# def entropy(self):\n# return tf.nn.softmax_cross_entropy_with_logits(self.logits, self.ps)\n# def sample(self):\n# u = tf.random_uniform(tf.shape(self.logits))\n# return U.argmax(self.logits - tf.log(-tf.log(u)), axis=-1)\n\n\n\ndef guassian_noise_layer(input_layer ,mean=0.0, std=2.0):\n print(\"Enterted teh guassian_noise_layer\")\n noise = tf.random_normal(shape=tf.shape(input_layer), mean=mean , stddev=std , dtype=tf.float32)\n return input_layer + noise \n\nclass CategoricalPd(Pd):\n def __init__(self, logits):\n self.logits = logits\n def flatparam(self):\n return self.logits\n def mode(self):\n return tf.argmax(self.logits, axis=-1)\n\n @property\n def mean(self):\n return tf.nn.softmax(self.logits)\n def neglogp(self, x):\n # return tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.logits, labels=x)\n # Note: we can't use sparse_softmax_cross_entropy_with_logits because\n # the implementation does not allow second-order derivatives...\n if x.dtype in {tf.uint8, tf.int32, tf.int64}:\n # one-hot encoding\n x_shape_list = x.shape.as_list()\n logits_shape_list = self.logits.get_shape().as_list()[:-1]\n for xs, ls in zip(x_shape_list, logits_shape_list):\n if xs is not None and ls is not None:\n assert xs == ls, 'shape mismatch: {} in x vs {} in logits'.format(xs, ls)\n\n x = tf.one_hot(x, self.logits.get_shape().as_list()[-1])\n else:\n # already encoded\n assert x.shape.as_list() == self.logits.shape.as_list()\n\n # self.logits = guassian_noise_layer(self.logits)\n\n return tf.nn.softmax_cross_entropy_with_logits_v2(\n logits=self.logits,\n labels=x)\n def kl(self, other):\n a0 = self.logits - tf.reduce_max(self.logits, axis=-1, keepdims=True)\n a1 = other.logits - tf.reduce_max(other.logits, axis=-1, keepdims=True)\n ea0 = tf.exp(a0)\n ea1 = tf.exp(a1)\n z0 = tf.reduce_sum(ea0, axis=-1, keepdims=True)\n z1 = tf.reduce_sum(ea1, axis=-1, keepdims=True)\n p0 = ea0 / z0\n return tf.reduce_sum(p0 * (a0 - tf.log(z0) - a1 + tf.log(z1)), axis=-1)\n def entropy(self):\n a0 = self.logits - tf.reduce_max(self.logits, axis=-1, keepdims=True)\n ea0 = tf.exp(a0)\n z0 = tf.reduce_sum(ea0, axis=-1, keepdims=True)\n p0 = ea0 / z0\n return tf.reduce_sum(p0 * (tf.log(z0) - a0), axis=-1)\n def sample(self):\n u = tf.random_uniform(tf.shape(self.logits), dtype=self.logits.dtype)\n return tf.argmax(self.logits - tf.log(-tf.log(u)), axis=-1)\n @classmethod\n def fromflat(cls, flat):\n return cls(flat)\n\nclass MultiCategoricalPd(Pd):\n def __init__(self, nvec, flat):\n self.flat = flat\n self.categoricals = list(map(CategoricalPd, tf.split(flat, nvec, axis=-1)))\n def flatparam(self):\n return self.flat\n def mode(self):\n return tf.cast(tf.stack([p.mode() for p in self.categoricals], axis=-1), tf.int32)\n def neglogp(self, x):\n return tf.add_n([p.neglogp(px) for p, px in zip(self.categoricals, tf.unstack(x, axis=-1))])\n def kl(self, other):\n return tf.add_n([p.kl(q) for p, q in zip(self.categoricals, other.categoricals)])\n def entropy(self):\n return tf.add_n([p.entropy() for p in self.categoricals])\n def sample(self):\n return tf.cast(tf.stack([p.sample() for p in self.categoricals], axis=-1), tf.int32)\n @classmethod\n def fromflat(cls, flat):\n raise NotImplementedError\n\nclass DiagGaussianPd(Pd):\n def __init__(self, flat):\n self.flat = flat\n mean, logstd = tf.split(axis=len(flat.shape)-1, num_or_size_splits=2, value=flat)\n self.mean = mean\n self.logstd = logstd\n self.std = tf.exp(logstd)\n def flatparam(self):\n return self.flat\n def mode(self):\n return self.mean\n def neglogp(self, x):\n return 0.5 * tf.reduce_sum(tf.square((x - self.mean) / self.std), axis=-1) \\\n + 0.5 * np.log(2.0 * np.pi) * tf.to_float(tf.shape(x)[-1]) \\\n + tf.reduce_sum(self.logstd, axis=-1)\n def kl(self, other):\n assert isinstance(other, DiagGaussianPd)\n return tf.reduce_sum(other.logstd - self.logstd + (tf.square(self.std) + tf.square(self.mean - other.mean)) / (2.0 * tf.square(other.std)) - 0.5, axis=-1)\n def entropy(self):\n return tf.reduce_sum(self.logstd + .5 * np.log(2.0 * np.pi * np.e), axis=-1)\n def sample(self):\n return self.mean + self.std * tf.random_normal(tf.shape(self.mean))\n @classmethod\n def fromflat(cls, flat):\n return cls(flat)\n\n\nclass BernoulliPd(Pd):\n def __init__(self, logits):\n self.logits = logits\n self.ps = tf.sigmoid(logits)\n def flatparam(self):\n return self.logits\n @property\n def mean(self):\n return self.ps\n def mode(self):\n return tf.round(self.ps)\n def neglogp(self, x):\n return tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.logits, labels=tf.to_float(x)), axis=-1)\n def kl(self, other):\n return tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(logits=other.logits, labels=self.ps), axis=-1) - tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.logits, labels=self.ps), axis=-1)\n def entropy(self):\n return tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.logits, labels=self.ps), axis=-1)\n def sample(self):\n u = tf.random_uniform(tf.shape(self.ps))\n return tf.to_float(math_ops.less(u, self.ps))\n @classmethod\n def fromflat(cls, flat):\n return cls(flat)\n\ndef make_pdtype(ac_space):\n from gym import spaces\n if isinstance(ac_space, spaces.Box):\n assert len(ac_space.shape) == 1\n return DiagGaussianPdType(ac_space.shape[0])\n elif isinstance(ac_space, spaces.Discrete):\n return CategoricalPdType(ac_space.n)\n elif isinstance(ac_space, spaces.MultiDiscrete):\n return MultiCategoricalPdType(ac_space.nvec)\n elif isinstance(ac_space, spaces.MultiBinary):\n return BernoulliPdType(ac_space.n)\n else:\n raise NotImplementedError\n\ndef shape_el(v, i):\n maybe = v.get_shape()[i]\n if maybe is not None:\n return maybe\n else:\n return tf.shape(v)[i]\n\[email protected]_session\ndef test_probtypes():\n np.random.seed(0)\n\n pdparam_diag_gauss = np.array([-.2, .3, .4, -.5, .1, -.5, .1, 0.8])\n diag_gauss = DiagGaussianPdType(pdparam_diag_gauss.size // 2) #pylint: disable=E1101\n validate_probtype(diag_gauss, pdparam_diag_gauss)\n\n pdparam_categorical = np.array([-.2, .3, .5])\n categorical = CategoricalPdType(pdparam_categorical.size) #pylint: disable=E1101\n validate_probtype(categorical, pdparam_categorical)\n\n nvec = [1,2,3]\n pdparam_multicategorical = np.array([-.2, .3, .5, .1, 1, -.1])\n multicategorical = MultiCategoricalPdType(nvec) #pylint: disable=E1101\n validate_probtype(multicategorical, pdparam_multicategorical)\n\n pdparam_bernoulli = np.array([-.2, .3, .5])\n bernoulli = BernoulliPdType(pdparam_bernoulli.size) #pylint: disable=E1101\n validate_probtype(bernoulli, pdparam_bernoulli)\n\n\ndef validate_probtype(probtype, pdparam):\n N = 100000\n # Check to see if mean negative log likelihood == differential entropy\n Mval = np.repeat(pdparam[None, :], N, axis=0)\n M = probtype.param_placeholder([N])\n X = probtype.sample_placeholder([N])\n pd = probtype.pdfromflat(M)\n calcloglik = U.function([X, M], pd.logp(X))\n calcent = U.function([M], pd.entropy())\n Xval = tf.get_default_session().run(pd.sample(), feed_dict={M:Mval})\n logliks = calcloglik(Xval, Mval)\n entval_ll = - logliks.mean() #pylint: disable=E1101\n entval_ll_stderr = logliks.std() / np.sqrt(N) #pylint: disable=E1101\n entval = calcent(Mval).mean() #pylint: disable=E1101\n assert np.abs(entval - entval_ll) < 3 * entval_ll_stderr # within 3 sigmas\n\n # Check to see if kldiv[p,q] = - ent[p] - E_p[log q]\n M2 = probtype.param_placeholder([N])\n pd2 = probtype.pdfromflat(M2)\n q = pdparam + np.random.randn(pdparam.size) * 0.1\n Mval2 = np.repeat(q[None, :], N, axis=0)\n calckl = U.function([M, M2], pd.kl(pd2))\n klval = calckl(Mval, Mval2).mean() #pylint: disable=E1101\n logliks = calcloglik(Xval, Mval2)\n klval_ll = - entval - logliks.mean() #pylint: disable=E1101\n klval_ll_stderr = logliks.std() / np.sqrt(N) #pylint: disable=E1101\n assert np.abs(klval - klval_ll) < 3 * klval_ll_stderr # within 3 sigmas\n print('ok on', probtype, pdparam)\n\n\ndef _matching_fc(tensor, name, size, init_scale, init_bias):\n if tensor.shape[-1] == size:\n return tensor\n else:\n return fc(tensor, name, size, init_scale=init_scale, init_bias=init_bias)"
]
| [
[
"tensorflow.exp",
"tensorflow.get_default_session",
"tensorflow.python.ops.math_ops.less",
"tensorflow.to_float",
"tensorflow.nn.softmax",
"tensorflow.nn.softmax_cross_entropy_with_logits_v2",
"tensorflow.shape",
"tensorflow.concat",
"numpy.log",
"tensorflow.sigmoid",
"tensorflow.argmax",
"numpy.sqrt",
"tensorflow.split",
"numpy.array",
"tensorflow.round",
"numpy.random.randn",
"tensorflow.log",
"tensorflow.reduce_sum",
"tensorflow.unstack",
"tensorflow.zeros_initializer",
"numpy.random.seed",
"tensorflow.nn.sigmoid_cross_entropy_with_logits",
"tensorflow.reduce_max",
"numpy.abs",
"numpy.repeat",
"tensorflow.square"
]
]
|
JDBumgardner/stone_ground_hearth_battles | [
"9fe095651fab60e8ddbf563f0b9b7f3e723d5f4f"
]
| [
"hearthstone/training/pytorch/networks/feedforward_net.py"
]
| [
"import torch\nimport torch.nn.functional as F\nfrom torch import nn\n\nfrom hearthstone.training.pytorch.encoding.default_encoder import EncodedActionSet\nfrom hearthstone.training.common.state_encoding import State, Encoder\n\n\nclass HearthstoneFFNet(nn.Module):\n def __init__(self, encoding: Encoder, hidden_layers=1, hidden_size=1024, shared=False, activation_function=\"gelu\"):\n ''' This is a generic, fully connected feed-forward neural net.\n\n This is a pytorch module: https://pytorch.org/docs/master/generated/torch.nn.Module.html#torch.nn.Module\n\n Args:\n encoding (Encoder): [link to doc]\n hidden_layers (int): The number of hidden layers.\n hidden_size (int): The width of the hidden layers.\n shared (bool): Whether the policy and value NNs share the same weights in the hidden layers.\n activation_function (string): The activation function between layers.\n '''\n super().__init__()\n input_size = encoding.player_encoding().flattened_size() + encoding.cards_encoding().flattened_size()\n if hidden_layers == 0:\n # If there are no hidden layers, just connect directly to output layers.\n hidden_size = input_size\n self.activation_function = activation_function\n self.shared = shared\n self.hidden_layers = hidden_layers\n self.policy_hidden_layers = []\n self.value_hidden_layers = []\n for i in range(hidden_layers):\n self.policy_hidden_layers.append(nn.Linear(input_size if i == 0 else hidden_size, hidden_size))\n nn.init.orthogonal_(self.policy_hidden_layers[-1].weight)\n if shared:\n self.value_hidden_layers.append(self.policy_hidden_layers[-1])\n else:\n # Create new hidden layers for the value network.\n self.value_hidden_layers.append(nn.Linear(input_size if i == 0 else hidden_size, hidden_size))\n nn.init.orthogonal_(self.value_hidden_layers[-1].weight)\n\n # Output layers\n self.fc_policy = nn.Linear(hidden_size, encoding.action_encoding_size())\n nn.init.constant_(self.fc_policy.weight, 0)\n nn.init.constant_(self.fc_policy.bias, 0)\n self.fc_value = nn.Linear(hidden_size, 1)\n\n def activation(self, x):\n if self.activation_function == \"relu\":\n return F.relu(x)\n elif self.activation_function == \"gelu\":\n return F.gelu(x)\n elif self.activation_function == \"sigmoid\":\n return torch.sigmoid(x)\n elif self.activation_function == \"tanh\":\n return torch.tanh(x)\n\n def forward(self, state: State, valid_actions: EncodedActionSet):\n # Because we have a fully connected NN, we can just flatten the input tensors.\n x_policy = torch.cat((state.player_tensor.flatten(1), state.cards_tensor.flatten(1)), dim=1)\n # The value network shares the input layer (for now)\n x_value = x_policy\n\n for i in range(self.hidden_layers):\n x_policy = self.activation(self.policy_hidden_layers[i](x_policy))\n if self.shared:\n x_value = x_policy\n else:\n x_value = self.activation(self.value_hidden_layers[i](x_value))\n policy = self.fc_policy(x_policy)\n # Disable invalid actions with a \"masked\" softmax\n valid_action_tensor = torch.cat(\n (valid_actions.player_action_tensor.flatten(1), valid_actions.card_action_tensor.flatten(1)), dim=1)\n policy = policy.masked_fill(valid_action_tensor.logical_not(), -1e30)\n\n # The policy network outputs an array of the log probability of each action.\n policy = F.log_softmax(policy, dim=1)\n # The value network outputs the linear combination of the last hidden layer. The value layer predicts the total reward at the end of the game,\n # which will be between -3.5 (8th place) at the minimum and 3.5 (1st place) at the max. \n value = self.fc_value(x_value).squeeze(1)\n return policy, value\n"
]
| [
[
"torch.nn.Linear",
"torch.sigmoid",
"torch.nn.init.constant_",
"torch.tanh",
"torch.nn.functional.gelu",
"torch.nn.functional.relu",
"torch.nn.functional.log_softmax",
"torch.nn.init.orthogonal_"
]
]
|
UCI-CubeSat/pyLMS7002Soapy | [
"4f828eb9282c302dc6b187d91df5e77c8a6f2d61"
]
| [
"examples/calculateVNA.py"
]
| [
"import numpy\nimport os, sys\n\nif len(sys.argv) != 2 and len(sys.argv) != 3:\n print(\"Usage: python calculateVNA_900M.py measurementName [plotFigures]\")\n print(\"plotFigures is optional and can have values plot for plotting figures or save to plot and save the figures\")\n exit(1)\n\nstartFreq = 2.3e9\nendFreq = 2.6e9\nnPoints = 101\nmeasName = sys.argv[1]\n\nsaveFig = False\nplotFig = False\nsmithFig = False\nif len(sys.argv) == 3:\n if sys.argv[2] == \"plot\":\n plotFig = True\n if sys.argv[2] == \"save\":\n plotFig = True\n saveFig = True\n\nif plotFig:\n from matplotlib.pyplot import *\n import warnings\n try:\n import smithplot\n from smithplot import SmithAxes\n smithFig = True\n except:\n print(\"pySmithPlot not found, smith chart will be not displayed\")\n\n\n warnings.filterwarnings(\"ignore\", module=\"matplotlib\")\n\nfMin = int(startFreq)\nfMax = int(endFreq)\n\n#############################################################################\n# Auxiliary functions\n\ndef readFile(fileName, fMin=0, fMax=1e20):\n inFile = open(fileName, 'r')\n res = [[], [], []]\n for line in inFile:\n if line[0] == \"#\":\n continue\n line = line.strip()\n if line == \"\":\n continue\n tmp = line.split()\n if float(tmp[0]) < fMin or float(tmp[0]) > fMax:\n continue\n res[0].append(float(tmp[0]))\n res[1].append(float(tmp[1]))\n res[2].append(float(tmp[2]))\n inFile.close()\n return [numpy.array(res[0]), numpy.array(res[1]), numpy.array(res[2])]\n\ndef filterData(f, data, fMin=0, fMax=1e20):\n res = []\n for i in range(0, len(f)):\n if fMin < f[i] < fMax:\n res.append(data[i])\n return numpy.array(res)\n\ndef unwrap(phase):\n # Unwrap the phase\n phase_unwrap = []\n intAng = 0\n for i in range(0, len(phase) - 1):\n phase_unwrap.append(phase[i] + intAng)\n dph = phase[i + 1] - phase[i]\n\n if abs(dph) > 150:\n if dph > 0:\n intAng += -180\n else:\n intAng += 180\n phase_unwrap.append(phase[-1] + intAng)\n phase_unwrap = numpy.array(phase_unwrap)\n\n # Second pass\n phase_unwrap2 = []\n intAng = 0\n for i in range(0, len(phase_unwrap) - 1):\n phase_unwrap2.append(phase_unwrap[i] + intAng)\n dph = phase_unwrap[i + 1] - phase_unwrap[i]\n if dph < -150:\n phase_unwrap[i + 1] += 180\n\n if 10 < dph < 45:\n intAng += -45\n if 45 < dph < 135:\n intAng += -90\n if 135 < dph < 180:\n intAng += -180\n if dph > 180:\n intAng += -360\n phase_unwrap2.append(phase_unwrap[-1] + intAng)\n phase_unwrap2 = numpy.array(phase_unwrap2)\n return phase_unwrap2\n\n#############################################################################\n\n# Read the measurement resutls\ndutFileName = 'vna_' + measName + '_DUT_' + str(startFreq) + '_' + str(endFreq) + '_' + str(nPoints) + '.txt'\nshortFileName = 'vna_' + measName + '_short_' + str(startFreq) + '_' + str(endFreq) + '_' + str(nPoints) + '.txt'\n\ndutData = readFile(dutFileName)\nshortData = readFile(shortFileName)\n\nfreq = dutData[0]\nf = freq\n\ndutPhase = unwrap(dutData[2]) * numpy.pi / 180\nshortPhase = unwrap(shortData[2]) * numpy.pi / 180\n\nif plotFig:\n plot(numpy.array(f) / 1e9, shortPhase)\n xlabel('f [GHz]')\n ylabel('Short Phase')\n grid()\n show()\n plot(numpy.array(f) / 1e9, dutPhase, linewidth=1.5, aa=True)\n xlabel('f [GHz]')\n ylabel('DUT Phase')\n grid()\n show()\n\ndutData[1] = 20.0 * numpy.log10(dutData[1])\nshortData[1] = 20.0 * numpy.log10(shortData[1])\n\nmeasGammaDut = numpy.power(10.0, dutData[1] / 20) * numpy.exp(1j * dutPhase) # /2)\nmeasGammaShort = numpy.power(10.0, shortData[1] / 20) * numpy.exp(1j * shortPhase) # /2)\n\nGammaShort = numpy.array([-1.0] * len(f)) # assume ideal short\n\nreturnLoss = dutData[1] - shortData[1]\n\nvswr = (10 ** (-returnLoss / 20) + 1) / (10 ** (-returnLoss / 20) - 1)\nif plotFig:\n plot(numpy.array(f) / 1e9, vswr)\n title('VSWR')\n xlabel('f [GHz]')\n ylabel('VSWR')\n grid()\n show()\n\ngammaMag = numpy.power(10.0, returnLoss / 20.0)\ndutPhase = dutPhase - shortPhase + numpy.pi\nGammaDut = gammaMag * numpy.exp(1j * dutPhase)\nZDut = (1.0 + GammaDut) / (1.0 - GammaDut)\n\nif plotFig:\n plot(numpy.array(f) / 1e9, 20 * numpy.log10(numpy.abs(GammaDut)), color='b', linewidth=1.5, aa=True)\n xlabel('f [GHz]')\n ylabel('S11 [dB]')\n grid()\n if saveFig:\n savefig(measName + '_s11.png')\n show()\n\n if smithFig:\n figure(figsize=(8, 8))\n subplot(1, 1, 1, projection='smith', grid_major_fancy=True,\n grid_minor_fancy=True, plot_marker_hack=True)\n ZDutPlot = filterData(freq, ZDut, fMin, fMax)\n plot(50 * ZDutPlot, markevery=1, markersize=4.0, label=\"S11\", color='b', linewidth=1.5, aa=True, datatype=SmithAxes.Z_PARAMETER)\n if saveFig:\n savefig(measName + '_smith.png')\n show()\n\noutFileName = measName + '.s1p'\noutFile = open(outFileName, 'w')\noutFile.write('# Hz S RI R 50\\n')\nfor i in range(0, len(GammaDut)):\n outFile.write(str(f[i]) + \"\\t\" + str(numpy.real(GammaDut[i])) + \"\\t\" + str(numpy.imag(GammaDut[i])) + \"\\n\")\noutFile.close()\n"
]
| [
[
"numpy.array",
"numpy.exp",
"numpy.real",
"numpy.power",
"numpy.abs",
"numpy.imag",
"numpy.log10"
]
]
|
thepalbi/codeql | [
"a0b5e1c87c3fcca4c60ecf051238981d2e7dd594"
]
| [
"constraintsolving/solver/solve-test.py"
]
| [
"import tensorflow as tf\nimport numpy as np\nimport tensorflow_constrained_optimization as tfco\nfrom six.moves import xrange\nimport math\nfrom MyConstraintedProblem import MyConstraintedProblem\n\n# Create a simulated 10-dimensional training dataset consisting of 1000 labeled\n# examples, of which 800 are labeled correctly and 200 are mislabeled.\nnum_examples = 1000\nnum_mislabeled_examples = 200\ndimension = 10\n# We will constrain the recall to be at least 90%.\nrecall_lower_bound = 0.9\n\n# Create random \"ground truth\" parameters for a linear model.\nground_truth_weights = np.random.normal(size=dimension) / math.sqrt(dimension)\nground_truth_threshold = 0\n\n# Generate a random set of features for each example.\nfeatures = np.random.normal(size=(num_examples, dimension)).astype(\n np.float32) / math.sqrt(dimension)\n# Compute the labels from these features given the ground truth linear model.\nlabels = (np.matmul(features, ground_truth_weights) >\n ground_truth_threshold).astype(np.float32)\n# Add noise by randomly flipping num_mislabeled_examples labels.\nmislabeled_indices = np.random.choice(\n num_examples, num_mislabeled_examples, replace=False)\nlabels[mislabeled_indices] = 1 - labels[mislabeled_indices]\n\n\n\n# Create variables containing the model parameters.\nweights = tf.Variable(tf.zeros(dimension), dtype=tf.float32, name=\"weights\")\nthreshold = tf.Variable(0.0, dtype=tf.float32, name=\"threshold\")\n\n# Create the optimization problem.\nconstant_labels = tf.constant(labels, dtype=tf.float32)\nconstant_features = tf.constant(features, dtype=tf.float32)\n\ndef predictions():\n return tf.tensordot(constant_features, weights, axes=(1, 0)) - threshold\n\ndef getweights():\n return weights\n# Like the predictions, in eager mode, the labels should be a nullary function\n# returning a Tensor. In graph mode, you can drop the lambda.\n# context = tfco.rate_context(predictions, labels=lambda: constant_labels)\n# problem = tfco.RateMinimizationProblem(\n# tfco.error_rate(context), [tfco.recall(context) >= recall_lower_bound, ])\n\nproblem = MyConstraintedProblem(\n labels=constant_labels,\n predictions=predictions,\n weights=getweights\n)\n\n\ndef average_hinge_loss(labels, predictions):\n # Recall that the labels are binary (0 or 1).\n signed_labels = (labels * 2) - 1\n return np.mean(np.maximum(0.0, 1.0 - signed_labels * predictions))\n\ndef recall(labels, predictions):\n # Recall that the labels are binary (0 or 1).\n positive_count = np.sum(labels)\n true_positives = labels * (predictions > 0)\n true_positive_count = np.sum(true_positives)\n return true_positive_count / positive_count\n\n# ProxyLagrangianOptimizerV2 is based on tf.keras.optimizers.Optimizer.\n# ProxyLagrangianOptimizerV1 (which we do not use here) would work equally well,\n# but is based on the older tf.compat.v1.train.Optimizer.\noptimizer = tfco.ProxyLagrangianOptimizerV2(\n optimizer=tf.keras.optimizers.Adagrad(learning_rate=1.0),\n num_constraints=problem.num_constraints)\n\n# In addition to the model parameters (weights and threshold), we also need to\n# optimize over any trainable variables associated with the problem (e.g.\n# implicit slack variables and weight denominators), and those associated with\n# the optimizer (the analogues of the Lagrange multipliers used by the\n# proxy-Lagrangian formulation).\nvar_list = ([weights, threshold] + problem.trainable_variables +\n optimizer.trainable_variables())\n\n\nfor ii in xrange(2000):\n optimizer.minimize(problem, var_list=var_list)\n\ntrained_weights = weights.numpy()\ntrained_threshold = threshold.numpy()\n\ntrained_predictions = np.matmul(features, trained_weights) - trained_threshold\nprint(\"Constrained average hinge loss = %f\" % average_hinge_loss(\n labels, trained_predictions))\nprint(\"Constrained recall = %f\" % recall(labels, trained_predictions))\nprint(\"Weights: \", trained_weights)\n#\n# optimizer = tf.keras.optimizers.Adagrad(learning_rate=1.0)\n# var_list = [weights, threshold]\n#\n# for ii in xrange(1000):\n# # For optimizing the unconstrained problem, we just minimize the \"objective\"\n# # portion of the minimization problem.\n# optimizer.minimize(problem.objective, var_list=var_list)\n#\n# trained_weights = weights.numpy()\n# trained_threshold = threshold.numpy()\n#\n# trained_predictions = np.matmul(features, trained_weights) - trained_threshold\n# print(\"Unconstrained average hinge loss = %f\" % average_hinge_loss(\n# labels, trained_predictions))\n# print(\"Unconstrained recall = %f\" % recall(labels, trained_predictions))"
]
| [
[
"numpy.random.normal",
"tensorflow.zeros",
"numpy.random.choice",
"numpy.matmul",
"tensorflow.tensordot",
"numpy.sum",
"tensorflow.Variable",
"tensorflow.constant",
"tensorflow.keras.optimizers.Adagrad",
"numpy.maximum"
]
]
|
Kipok/OpenSeq2Seq | [
"cb48d2552e157c88f005c2a7364548a658e4cdf1"
]
| [
"open_seq2seq/utils/hooks.py"
]
| [
"# Copyright (c) 2017 NVIDIA Corporation\nfrom __future__ import absolute_import, division, print_function\nfrom __future__ import unicode_literals\nfrom six.moves import range\n\nimport tensorflow as tf\nimport time\nimport os\n\n\nfrom open_seq2seq.utils.utils import deco_print, log_summaries_from_dict, \\\n get_results_for_epoch\n\n\nclass BroadcastGlobalVariablesHook(tf.train.SessionRunHook):\n \"\"\"\n SessionRunHook that will broadcast all global variables from root rank\n to all other processes during initialization.\n This is necessary to ensure consistent initialization of all workers when\n training is started with random weights or restored from a checkpoint.\n \"\"\"\n\n def __init__(self, root_rank, device=''):\n \"\"\"Construct a new BroadcastGlobalVariablesHook that will broadcast all\n global variables from root rank to all other processes during initialization.\n Args:\n root_rank:\n Rank that will send data, other ranks will receive data.\n device:\n Device to be used for broadcasting. Uses GPU by default\n if Horovod was build with HOROVOD_GPU_BROADCAST.\n \"\"\"\n super(BroadcastGlobalVariablesHook, self).__init__()\n self.root_rank = root_rank\n self.bcast_op = None\n self.device = device\n\n def begin(self):\n def broadcast_global_variables(root_rank):\n from horovod.tensorflow.mpi_ops import broadcast\n ops = []\n for var in tf.global_variables():\n if var.dtype.base_dtype == tf.float16:\n ops.append(tf.assign(var, tf.cast(broadcast(tf.cast(var, tf.float32),\n root_rank), tf.float16)))\n else:\n ops.append(tf.assign(var, broadcast(var, root_rank)))\n return tf.group(*ops)\n\n if not self.bcast_op or self.bcast_op.graph != tf.get_default_graph():\n with tf.device(self.device):\n self.bcast_op = broadcast_global_variables(self.root_rank)\n\n def after_create_session(self, session, coord):\n session.run(self.bcast_op)\n\n\nclass PrintSamplesHook(tf.train.SessionRunHook):\n \"\"\"Session hook that prints training samples and prediction from time to time\n \"\"\"\n def __init__(self, every_steps, model):\n super(PrintSamplesHook, self).__init__()\n self._timer = tf.train.SecondOrStepTimer(every_steps=every_steps)\n self._iter_count = 0\n self._global_step = None\n self._model = model\n # using only first GPU\n output_tensors = model.get_output_tensors(0)\n self._fetches = [\n model.get_data_layer(0).input_tensors,\n output_tensors,\n ]\n\n def begin(self):\n self._iter_count = 0\n self._global_step = tf.train.get_global_step()\n\n def before_run(self, run_context):\n if self._timer.should_trigger_for_step(self._iter_count):\n return tf.train.SessionRunArgs([self._fetches, self._global_step])\n return tf.train.SessionRunArgs([[], self._global_step])\n\n def after_run(self, run_context, run_values):\n results, step = run_values.results\n self._iter_count = step\n\n if not results:\n return\n self._timer.update_last_triggered_step(self._iter_count - 1)\n\n input_values, output_values = results\n dict_to_log = self._model.maybe_print_logs(input_values, output_values, step)\n # optionally logging to tensorboard any values\n # returned from maybe_print_logs\n if self._model.params['save_summaries_steps'] and dict_to_log:\n log_summaries_from_dict(\n dict_to_log,\n self._model.params['logdir'],\n step,\n )\n\n\nclass PrintLossAndTimeHook(tf.train.SessionRunHook):\n \"\"\"Session hook that prints training samples and prediction from time to time\n \"\"\"\n def __init__(self, every_steps, model):\n super(PrintLossAndTimeHook, self).__init__()\n self._timer = tf.train.SecondOrStepTimer(every_steps=every_steps)\n self._every_steps = every_steps\n self._iter_count = 0\n self._global_step = None\n self._model = model\n self._fetches = [model.loss]\n self._last_time = time.time()\n\n def begin(self):\n self._iter_count = 0\n self._global_step = tf.train.get_global_step()\n\n def before_run(self, run_context):\n if self._timer.should_trigger_for_step(self._iter_count):\n return tf.train.SessionRunArgs([self._fetches, self._global_step])\n return tf.train.SessionRunArgs([[], self._global_step])\n\n def after_run(self, run_context, run_values):\n results, step = run_values.results\n self._iter_count = step\n\n if not results:\n return\n self._timer.update_last_triggered_step(self._iter_count - 1)\n\n if self._model.steps_in_epoch is None:\n deco_print(\"Global step {}:\".format(step), end=\" \")\n else:\n deco_print(\n \"Epoch {}, global step {}:\".format(\n step // self._model.steps_in_epoch, step),\n end=\" \",\n )\n\n loss = results[0]\n deco_print(\"loss = {:.4f}\".format(loss), start=\"\", end=\", \")\n\n tm = (time.time() - self._last_time) / self._every_steps\n m, s = divmod(tm, 60)\n h, m = divmod(m, 60)\n\n deco_print(\n \"time per step = {}:{:02}:{:.3f}\".format(int(h), int(m), s),\n start=\"\",\n )\n self._last_time = time.time()\n\n\nclass RunEvaluationHook(tf.train.SessionRunHook):\n \"\"\"Session hook that runs evaluation on a validation set\n \"\"\"\n def __init__(self, every_steps, model, last_step=-1):\n super(RunEvaluationHook, self).__init__()\n self._timer = tf.train.SecondOrStepTimer(every_steps=every_steps)\n self._iter_count = 0\n self._global_step = None\n self._model = model\n self._triggered = False\n self._last_step = last_step\n self._eval_saver = tf.train.Saver(save_relative_paths=True)\n self._best_eval_loss = 1e9\n\n def begin(self):\n self._iter_count = 0\n self._global_step = tf.train.get_global_step()\n\n def before_run(self, run_context):\n self._triggered = self._timer.should_trigger_for_step(self._iter_count)\n return tf.train.SessionRunArgs([[], self._global_step])\n\n def after_run(self, run_context, run_values):\n results, step = run_values.results\n self._iter_count = step\n\n if not self._triggered and step != self._last_step - 1:\n return\n self._timer.update_last_triggered_step(self._iter_count - 1)\n\n if not self._model.on_horovod or self._model.hvd.rank() == 0:\n deco_print(\"Running evaluation on a validation set:\")\n\n results_per_batch, total_loss = get_results_for_epoch(\n self._model, run_context.session, mode=\"eval\", compute_loss=True,\n )\n\n if not self._model.on_horovod or self._model.hvd.rank() == 0:\n deco_print(\"Validation loss: {:.4f}\".format(total_loss), offset=4)\n\n dict_to_log = self._model.finalize_evaluation(results_per_batch, step)\n dict_to_log['eval_loss'] = total_loss\n\n # saving the best validation model\n if self._model.params['save_checkpoint_steps'] and \\\n total_loss < self._best_eval_loss:\n self._best_eval_loss = total_loss\n self._eval_saver.save(\n run_context.session,\n os.path.join(self._model.params['logdir'], 'best_models',\n 'val_loss={:.4f}-step'.format(total_loss)),\n global_step=step + 1,\n )\n\n # optionally logging to tensorboard any values\n # returned from maybe_print_logs\n if self._model.params['save_summaries_steps']:\n log_summaries_from_dict(\n dict_to_log,\n self._model.params['logdir'],\n step,\n )\n"
]
| [
[
"tensorflow.get_default_graph",
"tensorflow.group",
"tensorflow.train.Saver",
"tensorflow.global_variables",
"tensorflow.train.SecondOrStepTimer",
"tensorflow.device",
"tensorflow.train.get_global_step",
"tensorflow.cast",
"tensorflow.train.SessionRunArgs"
]
]
|
qilei123/BboxToolkit | [
"97f61ae97449009c7952f648be57a28d35c2f39b"
]
| [
"BboxToolkit/datasets/DOTAio.py"
]
| [
"import re\nimport os\nimport time\nimport zipfile\n\nimport os.path as osp\nimport numpy as np\n\nfrom PIL import Image\nfrom functools import reduce, partial\nfrom multiprocessing import Pool\nfrom collections import defaultdict\n\nfrom .io import load_imgs\nfrom .misc import get_classes, img_exts\nfrom ..utils import get_bbox_type\nfrom ..transforms import bbox2type\n\n\ndef load_dota(img_dir, ann_dir=None, classes=None, nproc=10):\n assert osp.isdir(img_dir), f'The {img_dir} is not an existing dir!'\n assert ann_dir is None or osp.isdir(ann_dir), f'The {ann_dir} is not an existing dir!'\n classes = get_classes('DOTA' if classes is None else classes)\n cls2lbl = {cls: i for i, cls in enumerate(classes)}\n\n print('Starting loading DOTA dataset information.')\n start_time = time.time()\n _load_func = partial(_load_dota_single,\n img_dir=img_dir,\n ann_dir=ann_dir,\n cls2lbl=cls2lbl)\n if nproc > 1:\n pool = Pool(nproc)\n contents = pool.map(_load_func, os.listdir(img_dir))\n pool.close()\n else:\n contents = list(map(_load_func, os.listdir(img_dir)))\n contents = [c for c in contents if c is not None]\n end_time = time.time()\n print(f'Finishing loading DOTA, get {len(contents)} iamges,',\n f'using {end_time-start_time:.3f}s.')\n\n return contents, classes\n\n\ndef _load_dota_single(imgfile, img_dir, ann_dir, cls2lbl):\n img_id, ext = osp.splitext(imgfile)\n if ext not in img_exts:\n return None\n\n imgpath = osp.join(img_dir, imgfile)\n size = Image.open(imgpath).size\n txtfile = None if ann_dir is None else osp.join(ann_dir, img_id+'.txt')\n content = _load_dota_txt(txtfile, cls2lbl)\n\n content.update(dict(width=size[0], height=size[1], filename=imgfile, id=img_id))\n return content\n\n\ndef _load_dota_txt(txtfile, cls2lbl):\n gsd, bboxes, labels, diffs = None, [], [], []\n if txtfile is None:\n pass\n elif not osp.isfile(txtfile):\n print(f\"Can't find {txtfile}, treated as empty txtfile\")\n else:\n with open(txtfile, 'r') as f:\n for line in f:\n if line.startswith('gsd'):\n num = line.split(':')[-1]\n try:\n gsd = float(num)\n except ValueError:\n gsd = None\n continue\n\n items = line.split(' ')\n if len(items) >= 9:\n if items[8] not in cls2lbl:\n continue\n bboxes.append([float(i) for i in items[:8]])\n labels.append(cls2lbl[items[8]])\n diffs.append(int(items[9]) if len(items) == 10 else 0)\n\n bboxes = np.array(bboxes, dtype=np.float32) if bboxes else \\\n np.zeros((0, 8), dtype=np.float32)\n labels = np.array(labels, dtype=np.int64) if labels else \\\n np.zeros((0, ), dtype=np.int64)\n diffs = np.array(diffs, dtype=np.int64) if diffs else \\\n np.zeros((0, ), dtype=np.int64)\n ann = dict(bboxes=bboxes, labels=labels, diffs=diffs)\n return dict(gsd=gsd, ann=ann)\n\n\ndef load_dota_submission(ann_dir, img_dir=None, classes=None, nproc=10):\n classes = get_classes('DOTA' if classes is None else classes)\n assert osp.isdir(ann_dir), f'The {ann_dir} is not an existing dir!'\n assert img_dir is None or osp.isdir(img_dir), f'The {img_dir} is not an existing dir!'\n\n file_pattern = r'Task[1|2]_(.*)\\.txt'\n cls2file_mapper = dict()\n for f in os.listdir(ann_dir):\n match_objs = re.match(file_pattern, f)\n if match_objs is None:\n fname, _ = osp.splitext(f)\n cls2file_mapper[fname] = f\n else:\n cls2file_mapper[match_objs.group(1)] = f\n\n print('Starting loading DOTA submission information')\n start_time = time.time()\n infos_per_cls = []\n for cls in classes:\n if cls not in cls2file_mapper:\n infos_per_cls.append(dict())\n else:\n subfile = osp.join(ann_dir, cls2file_mapper[cls])\n infos_per_cls.append(_load_dota_submission_txt(subfile))\n\n if img_dir is not None:\n contents, _ = load_imgs(img_dir, nproc=nproc, def_bbox_type='poly')\n else:\n all_id = reduce(lambda x, y: x|y, [d.keys() for d in infos_per_cls])\n contents = [{'id':i} for i in all_id]\n\n for content in contents:\n bboxes, scores, labels = [], [], []\n for i, infos_dict in enumerate(infos_per_cls):\n infos = infos_dict.get(content['id'], dict())\n bboxes.append(infos.get('bboxes', np.zeros((0, 8), dtype=np.float32)))\n scores.append(infos.get('scores', np.zeros((0, ), dtype=np.float32)))\n labels.append(np.zeros((bboxes[-1].shape[0], ), dtype=np.int64) + i)\n\n bboxes = np.concatenate(bboxes, axis=0)\n labels = np.concatenate(labels, axis=0)\n scores = np.concatenate(scores, axis=0)\n content['ann'] = dict(bboxes=bboxes, labels=labels, scores=scores)\n end_time = time.time()\n print(f'Finishing loading DOTA submission, get {len(contents)} images,',\n f'using {end_time-start_time:.3f}s.')\n return contents, classes\n\n\ndef _load_dota_submission_txt(subfile):\n if not osp.isfile(subfile):\n print(f\"Can't find {subfile}, treated as empty subfile\")\n return dict()\n\n collector = defaultdict(list)\n with open(subfile, 'r') as f:\n for line in f:\n img_id, score, *bboxes = line.split(' ')\n bboxes_info = bboxes + [score]\n bboxes_info = [float(i) for i in bboxes_info]\n collector[img_id].append(bboxes_info)\n\n anns_dict = dict()\n for img_id, info_list in collector.items():\n infos = np.array(info_list, dtype=np.float32)\n bboxes, scores = infos[:, :-1], infos[:, -1]\n bboxes = bbox2type(bboxes, 'poly')\n anns_dict[img_id] = dict(bboxes=bboxes, scores=scores)\n return anns_dict\n\n\ndef save_dota_submission(save_dir, id_list, dets_list, task='Task1', classes=None, with_zipfile=True):\n assert task in ['Task1', 'Task2']\n classes = get_classes('DOTA' if classes is None else classes)\n\n if osp.exists(save_dir):\n raise ValueError(f'The save_dir should be a non-exist path, but {save_dir} is existing')\n os.makedirs(save_dir)\n\n files = [osp.join(save_dir ,task+'_'+cls+'.txt') for cls in classes]\n file_objs = [open(f, 'w') for f in files]\n for img_id, dets_per_cls in zip(id_list, dets_list):\n for f, dets in zip(file_objs, dets_per_cls):\n bboxes, scores = dets[:, :-1], dets[:, -1]\n\n if task == 'Task1':\n if get_bbox_type(bboxes) == 'poly' and bboxes.shape[-1] != 8:\n bboxes = bbox2type(bboxes, 'obb')\n bboxes = bbox2type(bboxes, 'poly')\n else:\n bboxes = bbox2type(bboxes, 'hbb')\n\n for bbox, score in zip(bboxes, scores):\n txt_element = [img_id, str(score)] + ['%.2f'%(p) for p in bbox]\n f.writelines(' '.join(txt_element)+'\\n')\n\n for f in file_objs:\n f.close()\n\n if with_zipfile:\n target_name = osp.split(save_dir)[-1]\n with zipfile.ZipFile(osp.join(save_dir, target_name+'.zip'), 'w',\n zipfile.ZIP_DEFLATED) as t:\n for f in files:\n t.write(f, osp.split(f)[-1])\n"
]
| [
[
"numpy.concatenate",
"numpy.array",
"numpy.zeros"
]
]
|
wufanyou/Traffic4Cast-2020-TLab | [
"5226bb1d2db40badb33c6b0ffe659fc6e9dca544"
]
| [
"utils/hrnet/seg_hrnet.py"
]
| [
"# ------------------------------------------------------------------------------\n# Copyright (c) Microsoft\n# Licensed under the MIT License.\n# Written by Ke Sun ([email protected])\n# ------------------------------------------------------------------------------\n# modified by fw\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport logging\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nBatchNorm2d = nn.BatchNorm2d\nBN_MOMENTUM = 0.01\nlogger = logging.getLogger(__name__)\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(\n in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False\n )\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = BatchNorm2d(planes, momentum=BN_MOMENTUM)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = BatchNorm2d(planes, momentum=BN_MOMENTUM)\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):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = BatchNorm2d(planes, momentum=BN_MOMENTUM)\n self.conv2 = nn.Conv2d(\n planes, planes, kernel_size=3, stride=stride, padding=1, bias=False\n )\n self.bn2 = BatchNorm2d(planes, momentum=BN_MOMENTUM)\n self.conv3 = nn.Conv2d(\n planes, planes * self.expansion, kernel_size=1, bias=False\n )\n self.bn3 = BatchNorm2d(planes * self.expansion, momentum=BN_MOMENTUM)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass HighResolutionModule(nn.Module):\n def __init__(\n self,\n num_branches,\n blocks,\n num_blocks,\n num_inchannels,\n num_channels,\n fuse_method,\n multi_scale_output=True,\n ):\n super(HighResolutionModule, self).__init__()\n self._check_branches(\n num_branches, blocks, num_blocks, num_inchannels, num_channels\n )\n\n self.num_inchannels = num_inchannels\n self.fuse_method = fuse_method\n self.num_branches = num_branches\n\n self.multi_scale_output = multi_scale_output\n\n self.branches = self._make_branches(\n num_branches, blocks, num_blocks, num_channels\n )\n self.fuse_layers = self._make_fuse_layers()\n self.relu = nn.ReLU(inplace=True)\n\n def _check_branches(\n self, num_branches, blocks, num_blocks, num_inchannels, num_channels\n ):\n if num_branches != len(num_blocks):\n error_msg = \"NUM_BRANCHES({}) <> NUM_BLOCKS({})\".format(\n num_branches, len(num_blocks)\n )\n logger.error(error_msg)\n raise ValueError(error_msg)\n\n if num_branches != len(num_channels):\n error_msg = \"NUM_BRANCHES({}) <> NUM_CHANNELS({})\".format(\n num_branches, len(num_channels)\n )\n logger.error(error_msg)\n raise ValueError(error_msg)\n\n if num_branches != len(num_inchannels):\n error_msg = \"NUM_BRANCHES({}) <> NUM_INCHANNELS({})\".format(\n num_branches, len(num_inchannels)\n )\n logger.error(error_msg)\n raise ValueError(error_msg)\n\n def _make_one_branch(self, branch_index, block, num_blocks, num_channels, stride=1):\n downsample = None\n if (\n stride != 1\n or self.num_inchannels[branch_index]\n != num_channels[branch_index] * block.expansion\n ):\n downsample = nn.Sequential(\n nn.Conv2d(\n self.num_inchannels[branch_index],\n num_channels[branch_index] * block.expansion,\n kernel_size=1,\n stride=stride,\n bias=False,\n ),\n BatchNorm2d(\n num_channels[branch_index] * block.expansion, momentum=BN_MOMENTUM\n ),\n )\n\n layers = []\n layers.append(\n block(\n self.num_inchannels[branch_index],\n num_channels[branch_index],\n stride,\n downsample,\n )\n )\n self.num_inchannels[branch_index] = num_channels[branch_index] * block.expansion\n for i in range(1, num_blocks[branch_index]):\n layers.append(\n block(self.num_inchannels[branch_index], num_channels[branch_index])\n )\n\n return nn.Sequential(*layers)\n\n def _make_branches(self, num_branches, block, num_blocks, num_channels):\n branches = []\n\n for i in range(num_branches):\n branches.append(self._make_one_branch(i, block, num_blocks, num_channels))\n\n return nn.ModuleList(branches)\n\n def _make_fuse_layers(self):\n if self.num_branches == 1:\n return None\n\n num_branches = self.num_branches\n num_inchannels = self.num_inchannels\n fuse_layers = []\n for i in range(num_branches if self.multi_scale_output else 1):\n fuse_layer = []\n for j in range(num_branches):\n if j > i:\n fuse_layer.append(\n nn.Sequential(\n nn.Conv2d(\n num_inchannels[j],\n num_inchannels[i],\n 1,\n 1,\n 0,\n bias=False,\n ),\n BatchNorm2d(num_inchannels[i], momentum=BN_MOMENTUM),\n )\n )\n elif j == i:\n fuse_layer.append(None)\n else:\n conv3x3s = []\n for k in range(i - j):\n if k == i - j - 1:\n num_outchannels_conv3x3 = num_inchannels[i]\n conv3x3s.append(\n nn.Sequential(\n nn.Conv2d(\n num_inchannels[j],\n num_outchannels_conv3x3,\n 3,\n 2,\n 1,\n bias=False,\n ),\n BatchNorm2d(\n num_outchannels_conv3x3, momentum=BN_MOMENTUM\n ),\n )\n )\n else:\n num_outchannels_conv3x3 = num_inchannels[j]\n conv3x3s.append(\n nn.Sequential(\n nn.Conv2d(\n num_inchannels[j],\n num_outchannels_conv3x3,\n 3,\n 2,\n 1,\n bias=False,\n ),\n BatchNorm2d(\n num_outchannels_conv3x3, momentum=BN_MOMENTUM\n ),\n nn.ReLU(inplace=True),\n )\n )\n fuse_layer.append(nn.Sequential(*conv3x3s))\n fuse_layers.append(nn.ModuleList(fuse_layer))\n\n return nn.ModuleList(fuse_layers)\n\n def get_num_inchannels(self):\n return self.num_inchannels\n\n def forward(self, x):\n if self.num_branches == 1:\n return [self.branches[0](x[0])]\n\n for i in range(self.num_branches):\n x[i] = self.branches[i](x[i])\n\n x_fuse = []\n for i in range(len(self.fuse_layers)):\n y = x[0] if i == 0 else self.fuse_layers[i][0](x[0])\n for j in range(1, self.num_branches):\n if i == j:\n y = y + x[j]\n elif j > i:\n width_output = x[i].shape[-1]\n height_output = x[i].shape[-2]\n y = y + F.interpolate(\n self.fuse_layers[i][j](x[j]),\n size=[height_output, width_output],\n mode=\"bilinear\",\n align_corners=True,\n )\n else:\n y = y + self.fuse_layers[i][j](x[j])\n x_fuse.append(self.relu(y))\n\n return x_fuse\n\n\nblocks_dict = {\"BASIC\": BasicBlock, \"BOTTLENECK\": Bottleneck}\n\n\nclass HighResolutionNet(nn.Module):\n def __init__(self, config, **kwargs):\n extra = config\n self.pos_weight = None\n if \"pos_weight\" in kwargs:\n if kwargs[\"pos_weight\"] is not None:\n self.pos_weight = torch.tensor(kwargs[\"pos_weight\"])\n super(HighResolutionNet, self).__init__()\n\n # stem net\n self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False)\n self.bn1 = BatchNorm2d(64, momentum=BN_MOMENTUM)\n self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1, bias=False)\n self.bn2 = BatchNorm2d(64, momentum=BN_MOMENTUM)\n self.relu = nn.ReLU(inplace=True)\n\n self.stage1_cfg = extra[\"STAGE1\"]\n num_channels = self.stage1_cfg[\"NUM_CHANNELS\"][0]\n block = blocks_dict[self.stage1_cfg[\"BLOCK\"]]\n num_blocks = self.stage1_cfg[\"NUM_BLOCKS\"][0]\n self.layer1 = self._make_layer(block, 64, num_channels, num_blocks)\n stage1_out_channel = block.expansion * num_channels\n\n self.stage2_cfg = extra[\"STAGE2\"]\n num_channels = self.stage2_cfg[\"NUM_CHANNELS\"]\n block = blocks_dict[self.stage2_cfg[\"BLOCK\"]]\n num_channels = [\n num_channels[i] * block.expansion for i in range(len(num_channels))\n ]\n self.transition1 = self._make_transition_layer(\n [stage1_out_channel], num_channels\n )\n self.stage2, pre_stage_channels = self._make_stage(\n self.stage2_cfg, num_channels\n )\n\n self.stage3_cfg = extra[\"STAGE3\"]\n num_channels = self.stage3_cfg[\"NUM_CHANNELS\"]\n block = blocks_dict[self.stage3_cfg[\"BLOCK\"]]\n num_channels = [\n num_channels[i] * block.expansion for i in range(len(num_channels))\n ]\n self.transition2 = self._make_transition_layer(pre_stage_channels, num_channels)\n self.stage3, pre_stage_channels = self._make_stage(\n self.stage3_cfg, num_channels\n )\n\n self.stage4_cfg = extra[\"STAGE4\"]\n num_channels = self.stage4_cfg[\"NUM_CHANNELS\"]\n block = blocks_dict[self.stage4_cfg[\"BLOCK\"]]\n num_channels = [\n num_channels[i] * block.expansion for i in range(len(num_channels))\n ]\n self.transition3 = self._make_transition_layer(pre_stage_channels, num_channels)\n self.stage4, pre_stage_channels = self._make_stage(\n self.stage4_cfg, num_channels, multi_scale_output=True\n )\n\n last_inp_channels = np.int(np.sum(pre_stage_channels))\n\n self.last_layer = nn.Sequential(\n nn.Conv2d(\n in_channels=last_inp_channels,\n out_channels=last_inp_channels,\n kernel_size=1,\n stride=1,\n padding=0,\n ),\n BatchNorm2d(last_inp_channels, momentum=BN_MOMENTUM),\n nn.ReLU(inplace=True),\n nn.Conv2d(\n in_channels=last_inp_channels,\n out_channels=config.NUM_CLASSES,\n kernel_size=extra.FINAL_CONV_KERNEL,\n stride=1,\n padding=1 if extra.FINAL_CONV_KERNEL == 3 else 0,\n ),\n )\n\n def _make_transition_layer(self, num_channels_pre_layer, num_channels_cur_layer):\n num_branches_cur = len(num_channels_cur_layer)\n num_branches_pre = len(num_channels_pre_layer)\n\n transition_layers = []\n for i in range(num_branches_cur):\n if i < num_branches_pre:\n if num_channels_cur_layer[i] != num_channels_pre_layer[i]:\n transition_layers.append(\n nn.Sequential(\n nn.Conv2d(\n num_channels_pre_layer[i],\n num_channels_cur_layer[i],\n 3,\n 1,\n 1,\n bias=False,\n ),\n BatchNorm2d(\n num_channels_cur_layer[i], momentum=BN_MOMENTUM\n ),\n nn.ReLU(inplace=True),\n )\n )\n else:\n transition_layers.append(None)\n else:\n conv3x3s = []\n for j in range(i + 1 - num_branches_pre):\n inchannels = num_channels_pre_layer[-1]\n outchannels = (\n num_channels_cur_layer[i]\n if j == i - num_branches_pre\n else inchannels\n )\n conv3x3s.append(\n nn.Sequential(\n nn.Conv2d(inchannels, outchannels, 3, 2, 1, bias=False),\n BatchNorm2d(outchannels, momentum=BN_MOMENTUM),\n nn.ReLU(inplace=True),\n )\n )\n transition_layers.append(nn.Sequential(*conv3x3s))\n\n return nn.ModuleList(transition_layers)\n\n def _make_layer(self, block, inplanes, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(\n inplanes,\n planes * block.expansion,\n kernel_size=1,\n stride=stride,\n bias=False,\n ),\n BatchNorm2d(planes * block.expansion, momentum=BN_MOMENTUM),\n )\n\n layers = []\n layers.append(block(inplanes, planes, stride, downsample))\n inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def _make_stage(self, layer_config, num_inchannels, multi_scale_output=True):\n num_modules = layer_config[\"NUM_MODULES\"]\n num_branches = layer_config[\"NUM_BRANCHES\"]\n num_blocks = layer_config[\"NUM_BLOCKS\"]\n num_channels = layer_config[\"NUM_CHANNELS\"]\n block = blocks_dict[layer_config[\"BLOCK\"]]\n fuse_method = layer_config[\"FUSE_METHOD\"]\n\n modules = []\n for i in range(num_modules):\n # multi_scale_output is only used last module\n if not multi_scale_output and i == num_modules - 1:\n reset_multi_scale_output = False\n else:\n reset_multi_scale_output = True\n modules.append(\n HighResolutionModule(\n num_branches,\n block,\n num_blocks,\n num_inchannels,\n num_channels,\n fuse_method,\n reset_multi_scale_output,\n )\n )\n num_inchannels = modules[-1].get_num_inchannels()\n\n return nn.Sequential(*modules), num_inchannels\n\n def logits(self, **kwargs):\n x = kwargs[\"x\"].float()\n if \"extra\" in kwargs:\n extra = kwargs[\"extra\"].float()\n x = torch.cat([x, extra], axis=1)\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.relu(x)\n x = self.layer1(x)\n\n x_list = []\n for i in range(self.stage2_cfg[\"NUM_BRANCHES\"]):\n if self.transition1[i] is not None:\n x_list.append(self.transition1[i](x))\n else:\n x_list.append(x)\n y_list = self.stage2(x_list)\n\n x_list = []\n for i in range(self.stage3_cfg[\"NUM_BRANCHES\"]):\n if self.transition2[i] is not None:\n x_list.append(self.transition2[i](y_list[-1]))\n else:\n x_list.append(y_list[i])\n y_list = self.stage3(x_list)\n\n x_list = []\n for i in range(self.stage4_cfg[\"NUM_BRANCHES\"]):\n if self.transition3[i] is not None:\n x_list.append(self.transition3[i](y_list[-1]))\n else:\n x_list.append(y_list[i])\n x = self.stage4(x_list)\n\n # Upsampling\n x0_h, x0_w = x[0].size(2), x[0].size(3)\n x1 = F.interpolate(x[1], size=(x0_h, x0_w), mode=\"bilinear\", align_corners=True)\n x2 = F.interpolate(x[2], size=(x0_h, x0_w), mode=\"bilinear\", align_corners=True)\n x3 = F.interpolate(x[3], size=(x0_h, x0_w), mode=\"bilinear\", align_corners=True)\n\n x = torch.cat([x[0], x1, x2, x3], 1)\n x = self.last_layer(x)\n return x\n\n def forward(self, **kwargs):\n x = self.logits(**kwargs)\n x = (x + 1) / 2\n y = kwargs[\"y\"].float() / 255\n if \"mask\" in kwargs:\n x = x * kwargs[\"mask\"]\n loss = F.mse_loss(x, y)\n return loss\n\n def init_weights(\n self, pretrained=\"\",\n ):\n logger.info(\"=> init weights from normal distribution\")\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.normal_(m.weight, std=0.001)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n if os.path.isfile(pretrained):\n pretrained_dict = torch.load(pretrained)\n logger.info(\"=> loading pretrained model {}\".format(pretrained))\n model_dict = self.state_dict()\n pretrained_dict = {\n k: v for k, v in pretrained_dict.items() if k in model_dict.keys()\n }\n # for k, _ in pretrained_dict.items():\n # logger.info(\n # '=> loading {} pretrained model {}'.format(k, pretrained))\n model_dict.update(pretrained_dict)\n self.load_state_dict(model_dict)\n\n\nclass HighResolutionNetZero(HighResolutionNet):\n def forward(self, **kwargs):\n x = self.logits(**kwargs)\n kwargs[\"y\"] = (kwargs[\"y\"].float() > 0).float()\n if \"mask\" in kwargs:\n x = x * kwargs[\"mask\"]\n kwargs[\"y\"] = kwargs[\"y\"].reshape(-1) # [None]\n x = x.reshape(-1) # [None]\n loss = F.binary_cross_entropy_with_logits(\n x, kwargs[\"y\"], pos_weight=self.pos_weight\n )\n return loss\n\n\nclass HighResolutionNetGaussRank(HighResolutionNet):\n def logits(self, **kwargs):\n x = kwargs[\"x\"].float()\n if \"extra\" in kwargs:\n extra = kwargs[\"extra\"].float()\n extra = extra / 255\n x = torch.cat([x, extra], axis=1)\n x = x * 2 - 1\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.relu(x)\n x = self.layer1(x)\n\n x_list = []\n for i in range(self.stage2_cfg[\"NUM_BRANCHES\"]):\n if self.transition1[i] is not None:\n x_list.append(self.transition1[i](x))\n else:\n x_list.append(x)\n y_list = self.stage2(x_list)\n\n x_list = []\n for i in range(self.stage3_cfg[\"NUM_BRANCHES\"]):\n if self.transition2[i] is not None:\n x_list.append(self.transition2[i](y_list[-1]))\n else:\n x_list.append(y_list[i])\n y_list = self.stage3(x_list)\n\n x_list = []\n for i in range(self.stage4_cfg[\"NUM_BRANCHES\"]):\n if self.transition3[i] is not None:\n x_list.append(self.transition3[i](y_list[-1]))\n else:\n x_list.append(y_list[i])\n x = self.stage4(x_list)\n\n # Upsampling\n x0_h, x0_w = x[0].size(2), x[0].size(3)\n x1 = F.interpolate(x[1], size=(x0_h, x0_w), mode=\"bilinear\", align_corners=True)\n x2 = F.interpolate(x[2], size=(x0_h, x0_w), mode=\"bilinear\", align_corners=True)\n x3 = F.interpolate(x[3], size=(x0_h, x0_w), mode=\"bilinear\", align_corners=True)\n\n x = torch.cat([x[0], x1, x2, x3], 1)\n x = self.last_layer(x)\n return x\n\n\nclass HighResolutionNetGeoEmbedding(HighResolutionNet):\n def __init__(self, config, **kwargs):\n super(HighResolutionNetGeoEmbedding, self).__init__(config, **kwargs)\n\n self.embed = nn.Embedding(\n 215820, kwargs[\"all_cfg\"].MODEL.GEO_EMBED_DIM, max_norm=1\n )\n\n def logits(self, **kwargs):\n x = kwargs[\"x\"].float()\n if \"extra\" in kwargs:\n extra = kwargs[\"extra\"].float()\n x = torch.cat([x, extra], axis=1)\n if \"geo\" in kwargs:\n geo = (self.embed(kwargs[\"geo\"].long()) + 1) / 2 * 255\n geo = geo.permute([0, 3, 1, 2])\n x = torch.cat([x, geo], axis=1)\n\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.relu(x)\n x = self.layer1(x)\n\n x_list = []\n for i in range(self.stage2_cfg[\"NUM_BRANCHES\"]):\n if self.transition1[i] is not None:\n x_list.append(self.transition1[i](x))\n else:\n x_list.append(x)\n y_list = self.stage2(x_list)\n\n x_list = []\n for i in range(self.stage3_cfg[\"NUM_BRANCHES\"]):\n if self.transition2[i] is not None:\n x_list.append(self.transition2[i](y_list[-1]))\n else:\n x_list.append(y_list[i])\n y_list = self.stage3(x_list)\n\n x_list = []\n for i in range(self.stage4_cfg[\"NUM_BRANCHES\"]):\n if self.transition3[i] is not None:\n x_list.append(self.transition3[i](y_list[-1]))\n else:\n x_list.append(y_list[i])\n x = self.stage4(x_list)\n\n # Upsampling\n x0_h, x0_w = x[0].size(2), x[0].size(3)\n x1 = F.interpolate(x[1], size=(x0_h, x0_w), mode=\"bilinear\", align_corners=True)\n x2 = F.interpolate(x[2], size=(x0_h, x0_w), mode=\"bilinear\", align_corners=True)\n x3 = F.interpolate(x[3], size=(x0_h, x0_w), mode=\"bilinear\", align_corners=True)\n x = torch.cat([x[0], x1, x2, x3], 1)\n x = self.last_layer(x)\n return x\n\n\nclass HighResolutionNetGeoEmbeddingWith3DInput(HighResolutionNet):\n def __init__(self, config, **kwargs):\n super(HighResolutionNetGeoEmbeddingWith3DInput, self).__init__(config, **kwargs)\n\n self.embed = nn.Embedding(\n 215820, kwargs[\"all_cfg\"].MODEL.GEO_EMBED_DIM, max_norm=1\n )\n\n self.conv3d = nn.Sequential(\n nn.Conv3d(9, 9, kernel_size=3, stride=2, padding=1, bias=False),\n nn.BatchNorm3d(9),\n nn.ReLU(),\n )\n self.conv3d2d = nn.Sequential(\n nn.Conv2d(54, 64, kernel_size=1, stride=1, padding=0, bias=False),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n )\n self.conv2 = nn.Conv2d(128, 64, kernel_size=3, stride=2, padding=1, bias=False)\n\n def logits(self, **kwargs):\n x = kwargs[\"x\"].float()\n x = self.conv3d((2 * x / 255 - 1))\n x = x.reshape(x.shape[0], x.shape[1] * x.shape[2], x.shape[3], x.shape[4])\n x = self.conv3d2d(x)\n\n extra = kwargs[\"extra\"].float()\n geo = (self.embed(kwargs[\"geo\"].long()) + 1) / 2 * 255\n geo = geo.permute([0, 3, 1, 2])\n y = torch.cat([extra, geo], axis=1)\n y = self.conv1(y)\n y = self.bn1(y)\n x = torch.cat([x, self.relu(y)], axis=1)\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.relu(x)\n x = self.layer1(x)\n\n x_list = []\n for i in range(self.stage2_cfg[\"NUM_BRANCHES\"]):\n if self.transition1[i] is not None:\n x_list.append(self.transition1[i](x))\n else:\n x_list.append(x)\n y_list = self.stage2(x_list)\n\n x_list = []\n for i in range(self.stage3_cfg[\"NUM_BRANCHES\"]):\n if self.transition2[i] is not None:\n x_list.append(self.transition2[i](y_list[-1]))\n else:\n x_list.append(y_list[i])\n y_list = self.stage3(x_list)\n\n x_list = []\n for i in range(self.stage4_cfg[\"NUM_BRANCHES\"]):\n if self.transition3[i] is not None:\n x_list.append(self.transition3[i](y_list[-1]))\n else:\n x_list.append(y_list[i])\n x = self.stage4(x_list)\n\n # Upsampling\n x0_h, x0_w = x[0].size(2), x[0].size(3)\n x1 = F.interpolate(x[1], size=(x0_h, x0_w), mode=\"bilinear\", align_corners=True)\n x2 = F.interpolate(x[2], size=(x0_h, x0_w), mode=\"bilinear\", align_corners=True)\n x3 = F.interpolate(x[3], size=(x0_h, x0_w), mode=\"bilinear\", align_corners=True)\n x = torch.cat([x[0], x1, x2, x3], 1)\n x = self.last_layer(x)\n return x\n\n\ndef get_seg_model(cfg, **kwargs):\n model = globals()[kwargs[\"model_version\"]](cfg, **kwargs)\n return model\n"
]
| [
[
"torch.nn.functional.binary_cross_entropy_with_logits",
"torch.cat",
"torch.nn.ModuleList",
"torch.nn.init.constant_",
"torch.nn.Sequential",
"numpy.sum",
"torch.nn.functional.interpolate",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.functional.mse_loss",
"torch.nn.Conv2d",
"torch.nn.init.normal_",
"torch.tensor",
"torch.nn.Conv3d",
"torch.load",
"torch.nn.BatchNorm3d",
"torch.nn.Embedding"
]
]
|
VirtualRoyalty/TextGenESN | [
"27cbabf55c6aaa5deb6d6846c4358559b2addbed"
]
| [
"utils/train.py"
]
| [
"import numpy as np\nfrom random import sample\nimport torch, torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nfrom torch.autograd import Variable\nfrom IPython.display import clear_output\n\n\ndef trainESN(net,\n data,\n tokens,\n token_to_id,\n max_length,\n n_epoch,\n batch_size,\n opt,\n lr_scheduler,\n history=[],\n device=torch.device('cuda'),\n random_batching=True,\n figsize=(13, 6.5),\n plot_loss=True,\n legend=True):\n \"\"\"GenESN training loop function\"\"\"\n\n try:\n for i in range(n_epoch):\n\n if random_batching:\n batch_ix = to_matrix(sample(data, batch_size), token_to_id, max_len=max_length)\n batch_ix = torch.tensor(batch_ix, dtype=torch.int64)\n one_hot_batch = torch.nn.functional.one_hot(batch_ix, len(tokens))\n else:\n batch_ix = to_matrix(data[i * batch_size:(i+1) * batch_size], token_to_id, max_len=max_length)\n batch_ix = torch.tensor(batch_ix, dtype=torch.int64)\n one_hot_batch = torch.nn.functional.one_hot(batch_ix, len(tokens))\n\n sequence = compute_state(net, one_hot_batch)\n predicted_seq = sequence[:, :-1]\n actual_next_tokens = batch_ix[:, 1:].long().to(device)\n\n loss = cross_entropy(predicted_seq, actual_next_tokens)\n # loss = - torch.mean(torch.gather(predicted_seq, dim=2, index=actual_next_tokens[:, :, None]))\n loss.backward()\n opt.step()\n opt.zero_grad()\n\n history.append(loss.data.cpu().numpy())\n lr_scheduler.step(loss)\n if plot_loss:\n if (i + 1) % 100 == 0 or i == 1:\n plt.figure(figsize=figsize)\n plt.grid()\n clear_output(True)\n if legend:\n plt.plot(history, '.-',\n label='loss, lr = {}, epochs={} '.format(opt.param_groups[0]['lr'], i))\n else:\n plt.plot(history, '.-', label='loss')\n plt.legend()\n plt.title('The loss function of ESN')\n plt.show()\n except KeyboardInterrupt:\n print('KeyboardInterrupt, stoping...')\n return\n\n\ndef cross_entropy(pred, target):\n # print(pred.shape, target.shape)\n target_flat = target.view(-1)\n pred_flat = pred.reshape(pred.shape[0]*pred.shape[1], pred.shape[-1])\n # print(pred_flat.shape, target_flat.shape)\n return F.cross_entropy(pred_flat, target_flat, ignore_index=0)\n\n\ndef to_matrix(data,\n token_to_id,\n max_len=None,\n dtype='float32',\n batch_first=True):\n \"\"\"Casts a list of tokens into rnn-digestable matrix\"\"\"\n\n max_len = max_len or max(map(len, data))\n data_ix = np.zeros([len(data), max_len], dtype) + token_to_id[' ']\n\n for i in range(len(data)):\n line_ix = [token_to_id[c] for c in data[i]]\n data_ix[i, :len(line_ix)] = line_ix\n\n if not batch_first:\n data_ix = np.transpose(data_ix)\n\n return data_ix\n\n\ndef compute_state(net, batch_index):\n \"\"\"GenESN state computing\"\"\"\n\n batch_size, max_length, _ = batch_index.size()\n\n hid_state = net.init_hidden()\n logprobs = []\n\n for x_t in batch_index.transpose(0, 1):\n hid_state, logp_next = net(x_t.float().to(net.device), hid_state)\n logprobs.append(logp_next)\n\n return torch.stack(logprobs, dim=1)\n\n\ndef lm_cross_entropy(pred, target):\n\n pred_flat = pred.reshape(pred.shape[0] * pred.shape[1], pred.shape[-1])\n target_flat = target.view(-1)\n\n return F.cross_entropy(pred_flat, target_flat, ignore_index=0)\n\n\ndef scheduler(optimizer, patience):\n return torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer,\n patience=patience,\n factor=0.5,\n verbose=True)\n"
]
| [
[
"torch.device",
"torch.stack",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.figure",
"torch.nn.functional.cross_entropy",
"numpy.transpose",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.tensor",
"matplotlib.pyplot.show"
]
]
|
Zeitsperre/flyingpigeon | [
"678370bf428af7ffe11ee79be3b8a89c73215e5e"
]
| [
"flyingpigeon/ocgisDissimilarity.py"
]
| [
"import dissimilarity as dd\nimport numpy as np\nfrom ocgis.util.helpers import iter_array\nfrom ocgis.calc.base import AbstractParameterizedFunction, AbstractFieldFunction\nfrom ocgis.collection.field import Field\nfrom ocgis.constants import NAME_DIMENSION_TEMPORAL\n\nmetrics = dd.__all__\n\n# NOTE: This code builds on ocgis branch v-2.0.0.dev1\n\n\nclass Dissimilarity(AbstractFieldFunction, AbstractParameterizedFunction):\n \"\"\"\n OCGIS class to compute a dissimilarity metric between two\n distributions.\n \"\"\"\n key = 'dissimilarity'\n long_name = 'Dissimilarity metric comparing two samples'\n standard_name = 'dissimilarity_metric'\n description = 'Metric evaluating the dissimilarity between two ' \\\n 'multivariate samples'\n parms_definition = {'dist': str, 'target': Field, 'candidate': tuple}\n required_variables = ['candidate', 'target']\n _potential_dist = metrics\n\n def calculate(self, target=None, candidate=None, dist='seuclidean'):\n \"\"\"\n\n Parameters\n ----------\n target : ocgis Field\n The target distribution the different candidates are compared\n to.\n candidate : tuple\n Sequence of variable names identifying climate indices on which\n the comparison will be performed.\n dist : {'seuclidean', 'nearest_neighbor', 'zech_aslan',\n 'kolmogorov_smirnov', 'friedman_rafsky', 'kldiv'}\n Name of the distance measure, or dissimilarity metric.\n \"\"\"\n assert (dist in self._potential_dist)\n\n # Get the function from the module.\n metric = getattr(dd, dist)\n\n for var in candidate:\n if var not in target.keys():\n raise ValueError(\"{} not in candidate Field.\".format(var))\n\n # Build the (n,d) array for the target sample.\n ref = np.array([target[c].get_value().squeeze() for c in candidate]).T\n assert ref.ndim == 2\n\n # Create the fill variable based on the first candidate variable.\n variable = self.field[candidate[0]]\n crosswalk = self._get_dimension_crosswalk_(variable)\n time_axis = crosswalk.index(NAME_DIMENSION_TEMPORAL)\n fill_dimensions = list(variable.dimensions)\n fill_dimensions.pop(time_axis)\n fill = self.get_fill_variable(variable,\n 'dissimilarity', fill_dimensions,\n self.file_only,\n add_repeat_record_archetype_name=True)\n fill.units = ''\n # ================== #\n # Metric computation #\n # ================== #\n\n # Iterator over every dimension except time\n itr = iter_array(fill)\n\n arr = self.get_variable_value(fill)\n for ind in itr:\n\n # Build target array\n dind = list(ind)\n dind.insert(time_axis, slice(None))\n data = np.array([self.field[c][dind].get_value().squeeze() for c in\n candidate])\n\n p = np.ma.masked_invalid(data).T\n\n # Compress masked values from target array.\n pc = p.compress(~p.mask.any(1), 0)\n\n # Compute the actual metric value. The 5 value threshold is\n # arbitrary.\n if pc.shape[0] >= 5:\n arr.data[ind] = metric(ref, pc)\n else:\n arr.data[ind] = np.nan\n\n # Add the output variable to calculations variable collection. This\n # is what is returned by the execute() call.\n self.vc.add_variable(fill)\n\n\n # Create a well-formed climatology time variable for the full time extent (with bounds).\n tgv = self.field.time.get_grouping('all')\n # Replaces the time value on the field.\n self.field.set_time(tgv)\n fill.units = ''\n"
]
| [
[
"numpy.ma.masked_invalid"
]
]
|
gvvynplaine/dgl | [
"6294677f8acc6bc040baf922910473e1c82995ba"
]
| [
"examples/mxnet/rgcn/entity_classify.py"
]
| [
"\"\"\"\nModeling Relational Data with Graph Convolutional Networks\nPaper: https://arxiv.org/abs/1703.06103\nCode: https://github.com/tkipf/relational-gcn\n\nDifference compared to tkipf/relation-gcn\n* l2norm applied to all weights\n* remove nodes that won't be touched\n\"\"\"\n\nimport argparse\nimport numpy as np\nimport time\nimport mxnet as mx\nfrom mxnet import gluon\nimport mxnet.ndarray as F\nimport dgl\nfrom dgl.nn.mxnet import RelGraphConv\nfrom dgl.contrib.data import load_data\nfrom functools import partial\nfrom dgl.data.rdf import AIFBDataset, MUTAGDataset, BGSDataset, AMDataset\n\nfrom model import BaseRGCN\n\nclass EntityClassify(BaseRGCN):\n def build_input_layer(self):\n return RelGraphConv(self.num_nodes, self.h_dim, self.num_rels, \"basis\",\n self.num_bases, activation=F.relu, self_loop=self.use_self_loop,\n dropout=self.dropout)\n\n def build_hidden_layer(self, idx):\n return RelGraphConv(self.h_dim, self.h_dim, self.num_rels, \"basis\",\n self.num_bases, activation=F.relu, self_loop=self.use_self_loop,\n dropout=self.dropout)\n\n def build_output_layer(self):\n return RelGraphConv(self.h_dim, self.out_dim, self.num_rels, \"basis\",\n self.num_bases, activation=None,\n self_loop=self.use_self_loop)\n\ndef main(args):\n # load graph data\n if args.dataset == 'aifb':\n dataset = AIFBDataset()\n elif args.dataset == 'mutag':\n dataset = MUTAGDataset()\n elif args.dataset == 'bgs':\n dataset = BGSDataset()\n elif args.dataset == 'am':\n dataset = AMDataset()\n else:\n raise ValueError()\n\n # Load from hetero-graph\n hg = dataset[0]\n\n num_rels = len(hg.canonical_etypes)\n num_of_ntype = len(hg.ntypes)\n category = dataset.predict_category\n num_classes = dataset.num_classes\n train_mask = hg.nodes[category].data.pop('train_mask')\n test_mask = hg.nodes[category].data.pop('test_mask')\n train_idx = mx.nd.array(np.nonzero(train_mask.asnumpy())[0], dtype='int64')\n test_idx = mx.nd.array(np.nonzero(test_mask.asnumpy())[0], dtype='int64')\n labels = mx.nd.array(hg.nodes[category].data.pop('labels'), dtype='int64')\n\n # split dataset into train, validate, test\n if args.validation:\n val_idx = train_idx[:len(train_idx) // 5]\n train_idx = train_idx[len(train_idx) // 5:]\n else:\n val_idx = train_idx\n\n # calculate norm for each edge type and store in edge\n for canonical_etype in hg.canonical_etypes:\n u, v, eid = hg.all_edges(form='all', etype=canonical_etype)\n v = v.asnumpy()\n _, inverse_index, count = np.unique(v, return_inverse=True, return_counts=True)\n degrees = count[inverse_index]\n norm = np.ones(eid.shape[0]) / degrees\n hg.edges[canonical_etype].data['norm'] = mx.nd.expand_dims(mx.nd.array(norm), axis=1)\n\n # get target category id\n category_id = len(hg.ntypes)\n for i, ntype in enumerate(hg.ntypes):\n if ntype == category:\n category_id = i\n\n g = dgl.to_homo(hg)\n num_nodes = g.number_of_nodes()\n node_ids = mx.nd.arange(num_nodes)\n edge_norm = g.edata['norm']\n edge_type = g.edata[dgl.ETYPE]\n\n # find out the target node ids in g\n node_tids = g.ndata[dgl.NTYPE]\n loc = (node_tids == category_id)\n loc = mx.nd.array(np.nonzero(loc.asnumpy())[0], dtype='int64')\n target_idx = node_ids[loc]\n\n # since the nodes are featureless, the input feature is then the node id.\n feats = mx.nd.arange(num_nodes, dtype='int32')\n\n # check cuda\n use_cuda = args.gpu >= 0\n if use_cuda:\n ctx = mx.gpu(args.gpu)\n feats = feats.as_in_context(ctx)\n edge_type = edge_type.as_in_context(ctx)\n edge_norm = edge_norm.as_in_context(ctx)\n labels = labels.as_in_context(ctx)\n train_idx = train_idx.as_in_context(ctx)\n g = g.to(ctx)\n else:\n ctx = mx.cpu(0)\n\n # create model\n model = EntityClassify(num_nodes,\n args.n_hidden,\n num_classes,\n num_rels,\n num_bases=args.n_bases,\n num_hidden_layers=args.n_layers - 2,\n dropout=args.dropout,\n use_self_loop=args.use_self_loop,\n gpu_id=args.gpu)\n model.initialize(ctx=ctx)\n\n # optimizer\n trainer = gluon.Trainer(model.collect_params(), 'adam', {'learning_rate': args.lr, 'wd': args.l2norm})\n loss_fcn = gluon.loss.SoftmaxCELoss(from_logits=False)\n\n # training loop\n print(\"start training...\")\n forward_time = []\n backward_time = []\n for epoch in range(args.n_epochs):\n t0 = time.time()\n with mx.autograd.record():\n pred = model(g, feats, edge_type, edge_norm)\n pred = pred[target_idx]\n loss = loss_fcn(pred[train_idx], labels[train_idx])\n t1 = time.time()\n loss.backward()\n trainer.step(len(train_idx))\n t2 = time.time()\n\n forward_time.append(t1 - t0)\n backward_time.append(t2 - t1)\n print(\"Epoch {:05d} | Train Forward Time(s) {:.4f} | Backward Time(s) {:.4f}\".\n format(epoch, forward_time[-1], backward_time[-1]))\n\n train_acc = F.sum(mx.nd.cast(pred[train_idx].argmax(axis=1), 'int64') == labels[train_idx]).asscalar() / train_idx.shape[0]\n val_acc = F.sum(mx.nd.cast(pred[val_idx].argmax(axis=1), 'int64') == labels[val_idx]).asscalar() / len(val_idx)\n print(\"Train Accuracy: {:.4f} | Validation Accuracy: {:.4f}\".format(train_acc, val_acc))\n print()\n\n logits = model.forward(g, feats, edge_type, edge_norm)\n logits = logits[target_idx]\n test_acc = F.sum(mx.nd.cast(logits[test_idx].argmax(axis=1), 'int64') == labels[test_idx]).asscalar() / len(test_idx)\n print(\"Test Accuracy: {:.4f}\".format(test_acc))\n print()\n\n print(\"Mean forward time: {:4f}\".format(np.mean(forward_time[len(forward_time) // 4:])))\n print(\"Mean backward time: {:4f}\".format(np.mean(backward_time[len(backward_time) // 4:])))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='RGCN')\n parser.add_argument(\"--dropout\", type=float, default=0,\n help=\"dropout probability\")\n parser.add_argument(\"--n-hidden\", type=int, default=16,\n help=\"number of hidden units\")\n parser.add_argument(\"--gpu\", type=int, default=-1,\n help=\"gpu\")\n parser.add_argument(\"--lr\", type=float, default=1e-2,\n help=\"learning rate\")\n parser.add_argument(\"--n-bases\", type=int, default=-1,\n help=\"number of filter weight matrices, default: -1 [use all]\")\n parser.add_argument(\"--n-layers\", type=int, default=2,\n help=\"number of propagation rounds\")\n parser.add_argument(\"-e\", \"--n-epochs\", type=int, default=50,\n help=\"number of training epochs\")\n parser.add_argument(\"-d\", \"--dataset\", type=str, required=True,\n help=\"dataset to use\")\n parser.add_argument(\"--l2norm\", type=float, default=0,\n help=\"l2 norm coef\")\n parser.add_argument(\"--use-self-loop\", default=False, action='store_true',\n help=\"include self feature as a special relation\")\n fp = parser.add_mutually_exclusive_group(required=False)\n fp.add_argument('--validation', dest='validation', action='store_true')\n fp.add_argument('--testing', dest='validation', action='store_false')\n parser.set_defaults(validation=True)\n\n args = parser.parse_args()\n print(args)\n args.bfs_level = args.n_layers + 1 # pruning used nodes for memory\n main(args)\n"
]
| [
[
"numpy.ones",
"numpy.unique"
]
]
|
sushinoya/ggpy | [
"455f75edaa55b2f9bce7f24cddf81096be5362d5"
]
| [
"ggplot/geoms/geom_bar.py"
]
| [
"from .geom import geom\nimport pandas as pd\nimport matplotlib.patches as patches\n\n\nclass geom_bar(geom):\n \"\"\"\n Bar chart\n\n Parameters\n ----------\n x:\n x values for bins/categories\n color:\n color of the outer line\n alpha:\n transparency of fill\n size:\n thickness of outer line\n linetype:\n type of the outer line ('solid', 'dashed', 'dashdot', 'dotted')\n fill:\n color the interior of the bar will be\n\n Examples\n --------\n \"\"\"\n\n DEFAULT_AES = {'alpha': None, 'color': None, 'fill': '#333333',\n 'linetype': 'solid', 'size': 1.0}\n REQUIRED_AES = {'x'}\n DEFAULT_PARAMS = {\"width\": 0.8}\n _aes_renames = {'linetype': 'linestyle', 'size': 'linewidth',\n 'fill': 'color', 'color': 'edgecolor'}\n\n def setup_data(self, data, _aes, facets=None):\n (data, _aes) = self._update_data(data, _aes)\n x_col = _aes['x']\n weight_col = _aes.get('weight')\n\n if not weight_col:\n if '__weight__' not in data:\n data.insert(0, '__weight__', 1)\n weight_col = '__weight__'\n else:\n data['__weight__'] = data[weight_col]\n weight_col = '__weight__'\n\n fill_col = _aes.get('fill')\n if fill_col:\n fill_col = [fill_col]\n else:\n fill_col = []\n\n groupers = [x_col]\n if facets:\n if facets.rowvar:\n groupers.append(facets.rowvar)\n if facets.colvar:\n groupers.append(facets.colvar)\n dfa = (data[groupers + fill_col + [weight_col]].groupby(groupers + fill_col).sum()).reset_index()\n dfb = (data[groupers + [weight_col]].groupby(groupers).sum()).reset_index()\n df = pd.merge(dfa, dfb, on=groupers)\n df.rename(columns={'__weight___x': '__weight__', '__weight___y': '__total_weight__'}, inplace=True)\n if self.params.get('position')=='fill':\n df['__calc_weight__'] = df['__weight__'] / df['__total_weight__']\n else:\n df['__calc_weight__'] = df['__weight__']\n return df\n\n\n def plot(self, ax, data, _aes, x_levels, fill_levels, lookups):\n (data, _aes) = self._update_data(data, _aes)\n variables = _aes.data\n weight_col = _aes.get('weight')\n x_levels = sorted(x_levels)\n\n if not weight_col:\n if '__weight__' not in data:\n data.insert(0, '__weight__', 1.0)\n weight_col = '__weight__'\n\n params = self._get_plot_args(data, _aes)\n\n if fill_levels is not None:\n width = self.params[\"width\"] / len(fill_levels)\n else:\n width = self.params[\"width\"]\n padding = width / 2\n\n\n xticks = []\n for i, x_level in enumerate(x_levels):\n mask = data[variables['x']] == x_level\n row = data[mask]\n if len(row) == 0:\n xticks.append(i)\n continue\n\n if fill_levels is not None:\n fillval = row[variables['fill']].iloc[0]\n fill_idx = fill_levels.tolist().index(fillval)\n fill_x_adjustment = width * len(fill_levels)/2.\n else:\n fill_x_adjustment = width / 2\n\n if self.params.get('position') in ('stack', 'fill'):\n dodge = 0.0\n fill_x_adjustment = width / 2\n if fill_levels is None:\n height = 1.0\n ypos = 0\n else:\n mask = (lookups[variables['x']] == x_level) & (lookups[variables['fill']] == fillval)\n height = lookups[mask]['__calc_weight__'].sum()\n mask = (lookups[variables['x']] == x_level) & (lookups[variables['fill']] < fillval)\n ypos = lookups[mask]['__calc_weight__'].sum()\n else:\n if fill_levels is not None:\n dodge = width * fill_idx\n else:\n dodge = width\n ypos = 0.0\n height = row[weight_col].sum()\n\n xy = (dodge + i - fill_x_adjustment, ypos)\n\n ax.add_patch(patches.Rectangle(xy, width, height, **params))\n if fill_levels is not None:\n xticks.append(i)\n else:\n xticks.append(i + dodge)\n\n # need this b/c we're using patches\n ax.autoscale_view()\n\n # this will happen multiple times, but it's ok b/c it'll be the same each time\n ax.set_xticks(xticks)\n ax.set_xticklabels(x_levels)\n"
]
| [
[
"matplotlib.patches.Rectangle",
"pandas.merge"
]
]
|
jtomori/houdini2vr | [
"b2fe65cfee0bea14abe20275c0c21f6e917cda48"
]
| [
"scripts/python/hou2vr.py"
]
| [
"\"\"\"\nPreview your Houdini VR renders in HMD\n\"\"\"\n\nimport os\nimport hou\nimport time\nimport base64\nimport inspect\nimport logging\nimport urllib2\nimport webbrowser\nimport numpy as np\nimport SocketServer\nfrom PIL import Image\nimport SimpleHTTPServer\nfrom pathlib2 import Path\nfrom threading import Thread\n\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger(__name__)\n\n# CONFIG\nweb_server_address = \"127.0.0.1\"\nweb_server_port = 8000\nauto_save_interval = 5\n\ndef getCameraInfo(viewer):\n \"\"\"\n Returns a dictionary with information about camera rendering in passed IPR:\n layout: integer representing camera layout\n 0: horizontal (left - right)\n 1: vertical (top - bottom)\n stereo: integer representing whether rendering is stereo (1 - two eyes), or mono (0 - one eye)\n \n default values are 0 - if ROP node was not implemented (parm names change between renderers)\n \"\"\"\n \n out_dict = {\n \"layout\" : 0,\n \"stereo\" : 0\n }\n\n rop_node = viewer.ropNode()\n\n if rop_node.type().name() == \"ifd\" or rop_node.type().name() == \"arnold\": # Mantra / Arnold - they use the same camera and parameters\n cam_node = rop_node.parm(\"camera\").evalAsNode()\n layout = cam_node.parm(\"vrlayout\").eval()\n\n out_dict[\"layout\"] = layout\n if layout < 2:\n out_dict[\"stereo\"] = 1\n\n elif rop_node.type().name() == \"Redshift_ROP\" or rop_node.type().name() == \"Redshift_IPR\": # Redshift\n if rop_node.parm(\"linked_rop\").eval() == \"\":\n log.warning(\"Redshift_IPR node has empty Linked ROP parameter.\")\n return out_dict\n\n cam_node = rop_node.parm(\"linked_rop\").evalAsNode().parm(\"RS_renderCamera\").evalAsNode()\n\n layout = cam_node.parm(\"RS_campro_stereoMode\").eval()\n\n out_dict[\"layout\"] = layout\n if layout < 2:\n out_dict[\"stereo\"] = 1\n\n else: # Not implemented warning\n log.warning(\"ROP node is not implemented\")\n \n return out_dict\n\ndef getImageData():\n \"\"\"\n Returns a dictionary with information about displayed image\n\n it contains:\n img_plane - string with name of displayed image plane\n res - tuple of two ints for X and Y image resolution\n pixels - tuple of pixel tuples (4 floats, RGBA), in row-major order starting at the bottom left corner of the image\n layout - an integer representing camera layout\n 0: horizontal (left - right)\n 1: vertical (top - bottom)\n stereo - an integer whether rendering is stereo (1) or not (0)\n viewer - an reference pointing to hou.paneTabType.IPRViewer pane tab object\n \"\"\"\n viewer = hou.ui.paneTabOfType(hou.paneTabType.IPRViewer)\n img_data = {}\n \n if not viewer:\n log.warning(\"No Render View pane found\")\n return None\n else:\n if viewer.planes() == ():\n log.warning(\"No image planes found, is your scene rendering?\")\n return None\n else:\n cam_info = getCameraInfo(viewer)\n img_plane = viewer.displayedPlane()\n \n img_data[\"img_plane\"] = img_plane\n img_data[\"res\"] = viewer.imageResolution()\n img_data[\"pixels\"] = viewer.pixels(img_plane)\n img_data[\"layout\"] = cam_info[\"layout\"]\n img_data[\"stereo\"] = cam_info[\"stereo\"]\n img_data[\"viewer\"] = viewer\n \n return img_data\n\ndef updateImageData(img_data):\n \"\"\"\n Updates value of \"pixels\" in img_data dictionary, it is meant to be run after getImageData() call, which will populate needed information in the img_data dict.\n \"\"\"\n img_data[\"pixels\"] = img_data[\"viewer\"].pixels( img_data[\"img_plane\"] )\n\ndef plotImage(img_data):\n \"\"\"\n Plots gama-corrected image using matplotlib\n Depends on matplotlib\n \"\"\"\n import matplotlib\n matplotlib.use(\"Qt5Agg\")\n import matplotlib.pyplot as plt\n\n pixels = img_data[\"pixels\"]\n res = img_data[\"res\"]\n\n pixels = np.array(pixels)\n pixels = pixels.reshape(res[1], res[0], 4)\n pixels = np.flipud(pixels)\n\n pixels[:,:,:3] = pixels[:,:,:3]**(1/2.2)\n\n fig2d = plt.figure()\n plot = fig2d.add_subplot(111)\n imgplot = plt.imshow(pixels)\n plot.set_title(img_data[\"img_plane\"])\n\n plt.show()\n\n return\n\ndef saveImageAsPng(img_data, path=None):\n \"\"\"\n Saves incoming data as PNG in specified path, or in $HIP/tmp/tmp.png if not specified\n img_data is a dict which is returned from getImageData()\n path is a Path object\n \"\"\"\n if not img_data:\n return\n\n if not path:\n folder_path = Path(hou.getenv(\"HIP\"), \"tmp\")\n if not folder_path.exists():\n os.makedirs(str(folder_path))\n img_path = folder_path / \"tmp.png\"\n else:\n img_path = path\n\n pixels = img_data[\"pixels\"]\n res = img_data[\"res\"]\n\n pixels = np.array(pixels)\n pixels = pixels.reshape(res[1], res[0], 4)\n pixels = np.flipud(pixels)\n\n pixels *= 255\n pixels = np.clip(pixels, 0, 255)\n\n png_img = Image.fromarray(pixels.astype(np.uint8))\n png_img.save(str(img_path))\n log.info(\"Saving image into {}\".format(str(img_path)))\n\ndef isServerRunning():\n \"\"\"\n Checks whether server is running or not\n returns True if connection can be made or False if not\n \"\"\"\n try:\n os.environ[\"no_proxy\"] = \"127.0.0.1,localhost\" # fixes a problem when behing a proxy\n urllib2.urlopen(\"http://{}:{}\".format(web_server_address, web_server_port), timeout=1)\n return True\n except urllib2.URLError: \n return False\n\ndef startServer():\n \"\"\"\n Starts a simple httpserver at specified address and port (specified through global vars)\n \"\"\"\n handler = SimpleHTTPServer.SimpleHTTPRequestHandler\n httpd = SocketServer.TCPServer((web_server_address, web_server_port), handler)\n log.info(\"Starting web server at port {}\".format(web_server_port))\n httpd.serve_forever()\n\ndef autoSaveThread():\n \"\"\"\n Thread responsible for fetching pixels from IPR and saving them out\n Checks hou.session.hou2vr_autoSave to see if it should keep on running\n \"\"\"\n \n img_data = getImageData()\n img_path = getImgOutPath()\n run = True\n\n if not img_data:\n return\n\n while run:\n old_pixels = img_data[\"pixels\"]\n updateImageData(img_data)\n\n if img_data[\"pixels\"] != old_pixels:\n saveImageAsPng(img_data=img_data, path=img_path)\n else:\n log.info(\"Not saving, render hasn't changed\")\n \n try:\n run = hou.session.hou2vr_autoSave\n except AttributeError:\n run = False\n \n time.sleep(auto_save_interval)\n \ndef startAutoSave():\n \"\"\"\n Starts a separate thread which will be automatically saving out rendering image\n It also sets global hou.session.hou2vr_autoSave variable to True, which thread is checking against to know if it should keep running\n \"\"\"\n hou.session.hou2vr_autoSave = True\n\n process = Thread(target=autoSaveThread, args=())\n process.setDaemon(True)\n process.start()\n\ndef stopAutoSave():\n \"\"\"\n Stops auto saving thread by setting hou.session.hou2vr_autoSave to False\n \"\"\"\n try:\n hou.session.hou2vr_autoSave = False\n except AttributeError:\n pass\n\ndef getImgOutPath(img_name=\"tmp.png\"):\n \"\"\"\n Constructs a path (and creates folders if needed) relative to this repo where image will be saved, e.g.\n tmp/juraj/tmp.png\n \n Returns Path object\n \"\"\"\n root = Path(__file__).parents[2]\n tmp = root / \"tmp\" / os.environ[\"USER\"]\n img = tmp / \"tmp.png\"\n if not tmp.exists():\n os.makedirs(str(tmp))\n \n return img\n\ndef showInWebBrowser():\n \"\"\"\n Saves image in a tmp location, launches web server if not already running and launches web-browser which displays render image in VR\n \"\"\"\n root = Path(__file__).parents[2]\n\n img = getImgOutPath()\n img_relative = img.relative_to(root)\n\n img_data = getImageData()\n \n try:\n auto_refresh = int(hou.session.hou2vr_autoSave)\n except AttributeError:\n auto_refresh = 0\n\n if img_data:\n saveImageAsPng(img_data=img_data, path=img)\n\n if isServerRunning():\n log.info(\"Server is running\")\n else:\n log.info(\"Server is not running, starting...\")\n os.chdir(str(root))\n\n process = Thread(target=startServer, args=())\n process.setDaemon(True)\n process.start()\n \n webbrowser.open_new_tab(url=\"http://{address}:{port}/web/index.html?img_path={img}&layout={layout}&stereo={stereo}&auto_refresh={auto_refresh}&save_interval={save_interval}\".format( address=web_server_address, port=web_server_port, img=\"/\" + str(img_relative).replace(\"\\\\\", \"/\"), layout=img_data[\"layout\"], stereo=img_data[\"stereo\"], auto_refresh=auto_refresh, save_interval=auto_save_interval ))\n\ndef encodeImage(img_data):\n \"\"\"\n Encodes image into base64\n\n TODO: * check if it produces identical results with decodeImage()\n \"\"\"\n res = img_data[\"res\"]\n pixels = img_data[\"pixels\"]\n\n pixels_array = np.array(pixels)\n \n pixels_array = pixels_array.reshape(res[1], res[0], 4)\n pixels_array = np.flip(pixels_array, 0)\n pixels_array[:,:,:3] = pixels_array[:,:,:3]**(1/2.2)\n pixels_array = pixels_array.flatten()\n \n pixels_array *= 255\n \n return base64.b64encode( pixels_array.astype(np.uint8) )\n\ndef decodeImage(img_string):\n \"\"\"\n Decodes image from base64\n\n TODO: * this seems not to work properly, produces different results, maybe flipped?\n * get somehow resolution in\n \"\"\"\n pixels = np.frombuffer(base64.b64decode(img_string), np.uint8)\n pixels = pixels.reshape(10, 10, 4)\n pixels = pixels.astype(np.float32) / 255\n \n return pixels\n"
]
| [
[
"matplotlib.use",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.flipud",
"numpy.clip",
"matplotlib.pyplot.show",
"numpy.flip",
"matplotlib.pyplot.imshow"
]
]
|
fleeb24/foundation | [
"62ac096e6c53e12f2e29480506687c652c399d50"
]
| [
"omnilearn/community/ssim.py"
]
| [
"\n\nimport numpy as np\nfrom scipy import signal\nfrom scipy.ndimage.filters import convolve\nfrom PIL import Image\n\n\n\ndef _FSpecialGauss(size, sigma):\n \"\"\"Function to mimic the 'fspecial' gaussian MATLAB function.\"\"\"\n radius = size // 2\n offset = 0.0\n start, stop = -radius, radius + 1\n if size % 2 == 0:\n offset = 0.5\n stop -= 1\n x, y = np.mgrid[offset + start:stop, offset + start:stop]\n assert len(x) == size\n g = np.exp(-((x**2 + y**2) / (2.0 * sigma**2)))\n return g / g.sum()\n\n\ndef _SSIMForMultiScale(img1,\n img2,\n max_val=255,\n filter_size=11,\n filter_sigma=1.5,\n k1=0.01,\n k2=0.03):\n \"\"\"Return the Structural Similarity Map between `img1` and `img2`.\n\n This function attempts to match the functionality of ssim_index_new.m by\n Zhou Wang: http://www.cns.nyu.edu/~lcv/ssim/msssim.zip\n\n Arguments:\n img1: Numpy array holding the first RGB image batch.\n img2: Numpy array holding the second RGB image batch.\n max_val: the dynamic range of the images (i.e., the difference between the\n maximum the and minimum allowed values).\n filter_size: Size of blur kernel to use (will be reduced for small images).\n filter_sigma: Standard deviation for Gaussian blur kernel (will be reduced\n for small images).\n k1: Constant used to maintain stability in the SSIM calculation (0.01 in\n the original paper).\n k2: Constant used to maintain stability in the SSIM calculation (0.03 in\n the original paper).\n\n Returns:\n Pair containing the mean SSIM and contrast sensitivity between `img1` and\n `img2`.\n\n Raises:\n RuntimeError: If input images don't have the same shape or don't have four\n dimensions: [batch_size, height, width, depth].\n \"\"\"\n if img1.shape != img2.shape:\n raise RuntimeError(\n 'Input images must have the same shape (%s vs. %s).', img1.shape,\n img2.shape)\n if img1.ndim != 4:\n raise RuntimeError('Input images must have four dimensions, not %d',\n img1.ndim)\n\n img1 = img1.astype(np.float64)\n img2 = img2.astype(np.float64)\n _, height, width, _ = img1.shape\n\n # Filter size can't be larger than height or width of images.\n size = min(filter_size, height, width)\n\n # Scale down sigma if a smaller filter size is used.\n sigma = size * filter_sigma / filter_size if filter_size else 0\n\n if filter_size:\n window = np.reshape(_FSpecialGauss(size, sigma), (1, size, size, 1))\n mu1 = signal.fftconvolve(img1, window, mode='valid')\n mu2 = signal.fftconvolve(img2, window, mode='valid')\n sigma11 = signal.fftconvolve(img1 * img1, window, mode='valid')\n sigma22 = signal.fftconvolve(img2 * img2, window, mode='valid')\n sigma12 = signal.fftconvolve(img1 * img2, window, mode='valid')\n else:\n # Empty blur kernel so no need to convolve.\n mu1, mu2 = img1, img2\n sigma11 = img1 * img1\n sigma22 = img2 * img2\n sigma12 = img1 * img2\n\n mu11 = mu1 * mu1\n mu22 = mu2 * mu2\n mu12 = mu1 * mu2\n sigma11 -= mu11\n sigma22 -= mu22\n sigma12 -= mu12\n\n # Calculate intermediate values used by both ssim and cs_map.\n c1 = (k1 * max_val)**2\n c2 = (k2 * max_val)**2\n v1 = 2.0 * sigma12 + c2\n v2 = sigma11 + sigma22 + c2\n ssim = np.mean((((2.0 * mu12 + c1) * v1) / ((mu11 + mu22 + c1) * v2)))\n cs = np.mean(v1 / v2)\n return ssim, cs\n\n\ndef MultiScaleSSIM(img1,\n img2,\n max_val=255,\n filter_size=11,\n filter_sigma=1.5,\n k1=0.01,\n k2=0.03,\n weights=None):\n \"\"\"Return the MS-SSIM score between `img1` and `img2`.\n\n This function implements Multi-Scale Structural Similarity (MS-SSIM) Image\n Quality Assessment according to Zhou Wang's paper, \"Multi-scale structural\n similarity for image quality assessment\" (2003).\n Link: https://ece.uwaterloo.ca/~z70wang/publications/msssim.pdf\n\n Author's MATLAB implementation:\n http://www.cns.nyu.edu/~lcv/ssim/msssim.zip\n\n Arguments:\n img1: Numpy array holding the first RGB image batch.\n img2: Numpy array holding the second RGB image batch.\n max_val: the dynamic range of the images (i.e., the difference between the\n maximum the and minimum allowed values).\n filter_size: Size of blur kernel to use (will be reduced for small images).\n filter_sigma: Standard deviation for Gaussian blur kernel (will be reduced\n for small images).\n k1: Constant used to maintain stability in the SSIM calculation (0.01 in\n the original paper).\n k2: Constant used to maintain stability in the SSIM calculation (0.03 in\n the original paper).\n weights: List of weights for each level; if none, use five levels and the\n weights from the original paper.\n\n Returns:\n MS-SSIM score between `img1` and `img2`.\n\n Raises:\n RuntimeError: If input images don't have the same shape or don't have four\n dimensions: [batch_size, height, width, depth].\n \"\"\"\n if img1.shape != img2.shape:\n raise RuntimeError(\n 'Input images must have the same shape (%s vs. %s).', img1.shape,\n img2.shape)\n if img1.ndim != 4:\n raise RuntimeError('Input images must have four dimensions, not %d',\n img1.ndim)\n\n # Note: default weights don't sum to 1.0 but do match the paper / matlab code.\n weights = np.array(weights if weights else\n [0.0448, 0.2856, 0.3001, 0.2363, 0.1333])\n levels = weights.size\n downsample_filter = np.ones((1, 2, 2, 1)) / 4.0\n im1, im2 = [x.astype(np.float64) for x in [img1, img2]]\n mssim = np.array([])\n mcs = np.array([])\n for _ in range(levels):\n ssim, cs = _SSIMForMultiScale(\n im1,\n im2,\n max_val=max_val,\n filter_size=filter_size,\n filter_sigma=filter_sigma,\n k1=k1,\n k2=k2)\n mssim = np.append(mssim, ssim)\n mcs = np.append(mcs, cs)\n filtered = [\n convolve(im, downsample_filter, mode='reflect')\n for im in [im1, im2]\n ]\n im1, im2 = [x[:, ::2, ::2, :] for x in filtered]\n return (np.prod(mcs[0:levels - 1]**weights[0:levels - 1]) *\n (mssim[levels - 1]**weights[levels - 1]))\n\n\ndef msssim(original, compared):\n if isinstance(original, str):\n original = np.array(Image.open(original).convert('RGB'), dtype=np.float32)\n if isinstance(compared, str):\n compared = np.array(Image.open(compared).convert('RGB'), dtype=np.float32)\n\n original = original[None, ...] if original.ndim == 3 else original\n compared = compared[None, ...] if compared.ndim == 3 else compared\n\n return MultiScaleSSIM(original, compared, max_val=255)\n\n\ndef psnr(original, compared):\n if isinstance(original, str):\n original = np.array(Image.open(original).convert('RGB'), dtype=np.float32)\n if isinstance(compared, str):\n compared = np.array(Image.open(compared).convert('RGB'), dtype=np.float32)\n\n mse = np.mean(np.square(original - compared))\n psnr = np.clip(\n np.multiply(np.log10(255. * 255. / mse[mse > 0.]), 10.), 0., 99.99)[0]\n return psnr\n\n\n\n\n\n\n"
]
| [
[
"numpy.square",
"numpy.array",
"scipy.ndimage.filters.convolve",
"scipy.signal.fftconvolve",
"numpy.ones",
"numpy.exp",
"numpy.mean",
"numpy.prod",
"numpy.append",
"numpy.log10"
]
]
|
okumakito/dnb-tsod | [
"26789adf38bd4947887fad53ea462af3af6c9573"
]
| [
"scripts/preprocess_GSE112653.py"
]
| [
"import numpy as np\nimport pandas as pd\n\ndef preprocess_GSE112653():\n\n # NOTE: the mapping relations between probe names and gene symbols\n # were extracted from 028005_D_GeneList_20171030.txt obtained at:\n # https://earray.chem.agilent.com/earray/catalogGeneLists.do?action=displaylist\n # It was the latest at the momemnt of the paper submission.\n data_file_name = '../data/GSE112653_series_matrix.txt'\n mapping_file_name = '../data/id_mapping.tsv' \n output_file_name = '../data/data.tsv'\n\n # find !Sample_title ----------------------------------------\n with open(data_file_name, 'r') as f:\n for i, line in enumerate(f):\n if line.startswith('!Sample_title'):\n break\n header_lines = [i -1, i + 35] # '!Sample_title', 'ID_REF'\n\n # load expression data file ---------------------------------\n\n df = pd.read_csv(data_file_name, sep='\\t', index_col=0,\n low_memory=False, header=header_lines)\n df.drop('!series_matrix_table_end', inplace=True) # => 62976 x 64\n df.index = df.index.astype(int)\n\n # rename columns ------------------------------------------------\n\n col_idx = df.columns.get_level_values(0)\n condition_idx = col_idx.str.split('_').str[0]\n week_idx = col_idx.str.split('_').str[1].str.replace('w','')\n df.columns = [np.arange(len(col_idx)), condition_idx, week_idx]\n df.columns.names = ['sample_no', 'condition', 'week']\n \n # id conversion -------------------------------------------------\n\n mapping_sr = pd.read_csv(mapping_file_name, sep='\\t',\n usecols=['FeatureNum', 'GeneSymbol'],\n index_col=0, squeeze=True).dropna()\n df = df.loc[mapping_sr.index].rename(mapping_sr)\n df = df.groupby(axis=0,level=0).mean()\n df.index.name = 'gene_symbol'\n\n # save to file -------------------------------------------------\n\n df.to_csv(output_file_name, sep='\\t')\n\n\nif __name__ == '__main__':\n preprocess_GSE112653()\n"
]
| [
[
"pandas.read_csv"
]
]
|
geinarm/cmsc818_gudjon | [
"e48638bcc96b865f2daf749bd22dc75dda35aed8"
]
| [
"arm/obstacle.py"
]
| [
"import shapely\nimport numpy as np\nfrom matplotlib.patches import Polygon\nfrom matplotlib.collections import PatchCollection\n\nclass Obstacle(object):\n def __init__(self, frame, width, height):\n self.frame = frame\n self.width = width\n self.height = height\n\n self.shape = np.array([ [-0.5, 0.5],[0.5, 0.5], [0.5, -0.5], [-0.5, -0.5] ])\n self.shape *= np.array([width, height])\n self.ax_artists = []\n\n def get_position(self):\n return self.frame.origin()\n\n def get_points(self):\n return self.frame.transform_points(self.shape)\n\n def get_collider(self):\n return shapely.geometry.Polygon(self.get_points())\n\n def point_collides(self, x, y):\n point = shapely.geometry.Point(x, y)\n collider = self.get_collider()\n return point.intersects(collider)\n\n def draw(self, ax, color='red', clear=True):\n if clear:\n for a in self.ax_artists:\n a.remove()\n self.ax_artists = []\n\n poly = Polygon(self.get_points(), True)\n p = PatchCollection([poly], alpha=1.0, facecolors=color)\n #p.set_array(np.array(colors))\n #ax.add_collection(p)\n self.ax_artists.append(ax.add_collection(p))"
]
| [
[
"numpy.array",
"matplotlib.collections.PatchCollection"
]
]
|
Zeyu-Shen/differential-privacy-library | [
"4047b6a55ee108f87ad9d18c14359c5158637a65"
]
| [
"diffprivlib/models/forest.py"
]
| [
"\n# MIT License\n#\n# Copyright (C) IBM Corporation 2021\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nRandom Forest Classifier with Differential Privacy\n\"\"\"\nfrom collections import defaultdict, namedtuple\nimport numbers\nimport warnings\nfrom joblib import Parallel, delayed\nimport numpy as np\n\nfrom sklearn.utils import check_array\nfrom sklearn.utils.fixes import _joblib_parallel_args\nfrom sklearn.ensemble._forest import ForestClassifier\nfrom sklearn.tree import DecisionTreeClassifier as BaseDecisionTreeClassifier\n\nfrom diffprivlib.accountant import BudgetAccountant\nfrom diffprivlib.utils import PrivacyLeakWarning\nfrom diffprivlib.mechanisms import PermuteAndFlip\nfrom diffprivlib.validation import DiffprivlibMixin\n\nDataset = namedtuple('Dataset', ['X', 'y'])\n\n\nclass RandomForestClassifier(ForestClassifier, DiffprivlibMixin):\n r\"\"\"Random Forest Classifier with differential privacy.\n This class implements Differentially Private Random Decision Forests using Smooth Sensitivity [1].\n :math:`\\epsilon`-Differential privacy is achieved by constructing decision trees via random splitting criterion and\n applying Exponential Mechanism to produce a noisy label.\n Parameters\n ----------\n n_estimators: int, default: 10\n The number of trees in the forest.\n epsilon: float, default: 1.0\n Privacy parameter :math:`\\epsilon`.\n cat_feature_threshold: int, default: 10\n Threshold value used to determine categorical features. For example, value of ``10`` means\n any feature that has less than or equal to 10 unique values will be treated as a categorical feature.\n n_jobs : int, default: 1\n Number of CPU cores used when parallelising over classes. ``-1`` means\n using all processors.\n verbose : int, default: 0\n Set to any positive number for verbosity.\n accountant : BudgetAccountant, optional\n Accountant to keep track of privacy budget.\n max_depth: int, default: 15\n The maximum depth of the tree. Final depth of the tree will be calculated based on the number of continuous\n and categorical features, but it wont be more than this number.\n Note: The depth translates to an exponential increase in memory usage.\n random_state: float, optional\n Sets the numpy random seed.\n feature_domains: dict, optional\n A dictionary of domain values for all features where keys are the feature indexes in the training data and\n the values are an array of domain values for categorical features and an array of min and max values for\n continuous features. For example, if the training data is [[2, 'dog'], [5, 'cat'], [7, 'dog']], then\n the feature_domains would be {'0': [2, 7], '1': ['dog', 'cat']}. If not provided, feature domains will\n be constructed from the data, but this will result in :class:`.PrivacyLeakWarning`.\n Attributes\n ----------\n n_features_in_: int\n The number of features when fit is performed.\n n_classes_: int\n The number of classes.\n classes_: array of shape (n_classes, )\n The classes labels.\n cat_features_: array of categorical feature indexes\n Categorical feature indexes.\n max_depth_: int\n Final max depth used for constructing decision trees.\n estimators_: list of DecisionTreeClassifier\n The collection of fitted sub-estimators.\n feature_domains_: dictionary of domain values mapped to feature\n indexes in the training data\n Examples\n --------\n >>> from sklearn.datasets import make_classification\n >>> from diffprivlib.models import RandomForestClassifier\n >>> X, y = make_classification(n_samples=1000, n_features=4,\n ... n_informative=2, n_redundant=0,\n ... random_state=0, shuffle=False)\n >>> clf = RandomForestClassifier(n_estimators=100, random_state=0)\n >>> clf.fit(X, y)\n >>> print(clf.predict([[0, 0, 0, 0]]))\n [1]\n References\n ----------\n [1] Sam Fletcher, Md Zahidul Islam. \"Differentially Private Random Decision Forests using Smooth Sensitivity\"\n https://arxiv.org/abs/1606.03572\n \"\"\"\n\n def __init__(self, n_estimators=10, *, epsilon=1.0, bounds=None, n_jobs=1, verbose=0, accountant=None,\n max_depth=15, random_state=None, **unused_args):\n super().__init__(\n base_estimator=DecisionTreeClassifier(),\n n_estimators=n_estimators,\n estimator_params=(\"cat_feature_threshold\", \"max_depth\", \"epsilon\", \"random_state\"),\n n_jobs=n_jobs,\n random_state=random_state,\n verbose=verbose)\n self.epsilon = epsilon\n self.bounds = bounds\n self.max_depth = max_depth\n self.accountant = BudgetAccountant.load_default(accountant)\n\n if random_state is not None:\n np.random.seed(random_state)\n\n self._warn_unused_args(unused_args)\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"Fit the model to the given training data.\n Parameters\n ----------\n X : array-like, shape (n_samples, n_features)\n Training vector, where n_samples is the number of samples and n_features is the number of features.\n y : array-like, shape (n_samples,)\n Target vector relative to X.\n sample_weight : ignored\n Ignored by diffprivlib. Present for consistency with sklearn API.\n Returns\n -------\n self: class\n \"\"\"\n self.accountant.check(self.epsilon, 0)\n\n if sample_weight is not None:\n self._warn_unused_args(\"sample_weight\")\n\n X, y = self._validate_data(X, y)\n\n if not float(self.n_estimators).is_integer() or self.n_estimators < 0:\n raise ValueError(f'Number of estimators should be a positive integer; got {self.n_estimators}')\n\n if self.bounds is None:\n self.bounds = (np.min(X, axis=0), np.max(X, axis=0))\n self.bounds = self._check_bounds(self.bounds, shape=X.shape[1])\n X = self._clip_to_bounds(X, self.bounds)\n\n self.n_outputs_ = 1\n self.n_features_in_ = X.shape[1]\n self.max_depth_ = calc_tree_depth(n_features=self.n_features_in_, max_depth=self.max_depth)\n self.classes_ = np.unique(y)\n self.n_classes_ = len(self.classes_)\n\n if self.n_estimators > len(X):\n raise ValueError('Number of estimators is more than the available samples')\n\n subset_size = int(len(X) / self.n_estimators)\n datasets = []\n estimators = []\n\n for i in range(self.n_estimators):\n estimator = DecisionTreeClassifier(max_depth=self.max_depth_,\n epsilon=self.epsilon,\n bounds=self.bounds,\n classes=self.classes_)\n estimators.append(estimator)\n datasets.append(Dataset(X=X[i*subset_size:(i+1)*subset_size], y=y[i*subset_size:(i+1)*subset_size]))\n\n estimators = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, **_joblib_parallel_args(prefer='processes'))(\n delayed(lambda estimator, X, y: estimator.fit(X, y))(estimator, dataset.X, dataset.y)\n for estimator, dataset in zip(estimators, datasets)\n )\n\n self.estimators_ = estimators\n self.accountant.spend(self.epsilon, 0)\n self.fitted_ = True\n\n return self\n\n\nclass DecisionTreeClassifier(BaseDecisionTreeClassifier, DiffprivlibMixin):\n r\"\"\"Decision Tree Classifier with differential privacy.\n This class implements the base differentially private decision tree classifier\n for the Random Forest classifier algorithm. Not meant to be used separately.\n Parameters\n ----------\n max_depth: int, default: 15\n The maximum depth of the tree.\n epsilon: float, default: 1.0\n Privacy parameter :math:`\\epsilon`.\n bounds: tuple, optional\n Bounds of the data, provided as a tuple of the form (min, max). `min` and `max` can either be scalars, covering\n the min/max of the entire data, or vectors with one entry per feature. If not provided, the bounds are computed\n on the data when ``.fit()`` is first called, resulting in a :class:`.PrivacyLeakWarning`.\n classes: array of shape (n_classes_, ), optional\n Array of class labels. If not provided, will be determined from the data.\n random_state: float, optional\n Sets the numpy random seed.\n Attributes\n ----------\n n_features_in_: int\n The number of features when fit is performed.\n n_classes_: int\n The number of classes.\n classes_: array of shape (n_classes, )\n The class labels.\n \"\"\"\n def __init__(self, max_depth=5, *, epsilon=1, bounds=None, classes=None, random_state=None):\n # TODO: Remove try...except when sklearn v1.0 is min-requirement\n try:\n super().__init__(\n criterion=None,\n splitter=None,\n max_depth=max_depth,\n min_samples_split=None,\n min_samples_leaf=None,\n min_weight_fraction_leaf=None,\n max_features=None,\n random_state=random_state,\n max_leaf_nodes=None,\n min_impurity_decrease=None,\n min_impurity_split=None\n )\n except TypeError:\n super().__init__(\n criterion=None,\n splitter=None,\n max_depth=max_depth,\n min_samples_split=None,\n min_samples_leaf=None,\n min_weight_fraction_leaf=None,\n max_features=None,\n random_state=random_state,\n max_leaf_nodes=None,\n min_impurity_decrease=None\n )\n self.epsilon = epsilon\n self.bounds = bounds\n self.classes = classes\n\n if random_state is not None:\n np.random.seed(random_state)\n\n def _build(self, features, bounds, current_depth=1):\n if not features or current_depth >= self.max_depth+1:\n return DecisionNode(level=current_depth, classes=self.classes_)\n\n bounds_lower, bounds_upper = self._check_bounds(bounds, shape=len(features))\n\n split_feature = np.random.choice(features)\n node = DecisionNode(level=current_depth, classes=self.classes_, split_feature=split_feature)\n\n split_value = np.random.uniform(bounds_lower[split_feature], bounds_upper[split_feature])\n node.set_split_value(split_value)\n\n left_bounds_upper = bounds_upper.copy()\n left_bounds_upper[split_feature] = split_value\n right_bounds_lower = bounds_lower.copy()\n right_bounds_lower[split_feature] = split_value\n\n left_child = self._build(features, (bounds_lower, left_bounds_upper), current_depth + 1)\n right_child = self._build(features, (right_bounds_lower, bounds_upper), current_depth + 1)\n node.set_left_child(left_child)\n node.set_right_child(right_child)\n\n return node\n\n def fit(self, X, y, sample_weight=None, check_input=True, X_idx_sorted=\"deprecated\"):\n if sample_weight is not None:\n self._warn_unused_args(\"sample_weight\")\n\n if check_input:\n X, y = self._validate_data(X, y, multi_output=False)\n self.n_outputs_ = 1\n\n if self.bounds is None:\n self.bounds = (np.min(X, axis=0), np.max(X, axis=0))\n self.bounds = self._check_bounds(self.bounds, shape=X.shape[1])\n\n self.classes_ = self.classes\n\n if self.classes_ is None:\n self.classes_ = np.unique(y)\n\n self.n_classes_ = len(self.classes_)\n\n self.n_features_in_ = X.shape[1]\n features = list(range(self.n_features_in_))\n\n self.tree_ = self._build(features, self.bounds)\n\n for i, _ in enumerate(X):\n node = self.tree_.classify(X[i])\n node.update_class_count(y[i].item())\n\n self.tree_.set_noisy_label(self.epsilon, self.classes_)\n\n return self\n\n @property\n def n_features_(self):\n return self.n_features_in_\n\n def _more_tags(self):\n return {}\n\n\nclass DecisionNode:\n \"\"\"Base Decision Node\n \"\"\"\n\n def __init__(self, level, classes, split_feature=None, split_value=None):\n \"\"\"\n Initialize DecisionNode\n Parameters\n ----------\n level: int\n Node level in the tree\n classes: list\n List of class labels\n split_feature: int\n Split feature index\n split_value: Any\n Feature value to split at\n \"\"\"\n self._level = level\n self._classes = classes\n self._split_feature = split_feature\n self._split_value = split_value\n self._left_child = None\n self._right_child = None\n self._class_counts = defaultdict(int)\n self._noisy_label = None\n\n @property\n def noisy_label(self):\n \"\"\"Get noisy label\"\"\"\n return self._noisy_label\n\n def set_split_value(self, split_value):\n \"\"\"Set split value\"\"\"\n self._split_value = split_value\n\n def set_left_child(self, node):\n \"\"\"Set left child of the node\"\"\"\n self._left_child = node\n\n def set_right_child(self, node):\n \"\"\"Set right child of the node\"\"\"\n self._right_child = node\n\n def is_leaf(self):\n \"\"\"Check whether the node is leaf node\"\"\"\n return not self._left_child and not self._right_child\n\n def update_class_count(self, class_value):\n \"\"\"Update the class count for the given class\"\"\"\n self._class_counts[class_value] += 1\n\n def classify(self, x):\n \"\"\"Classify the given data\"\"\"\n if self.is_leaf():\n return self\n\n x_val = x[self._split_feature]\n if x_val < self._split_value:\n child = self._left_child\n else:\n child = self._right_child\n\n return child.classify(x)\n\n def set_noisy_label(self, epsilon, class_values):\n \"\"\"Set the noisy label for this node\"\"\"\n if self.is_leaf():\n if self._noisy_label is None:\n for val in class_values:\n if val not in self._class_counts:\n self._class_counts[val] = 0\n\n utility = list(self._class_counts.values())\n candidates = list(self._class_counts.keys())\n mech = PermuteAndFlip(epsilon=epsilon, sensitivity=1, monotonic=True, utility=utility,\n candidates=candidates)\n self._noisy_label = mech.randomise()\n else:\n if self._left_child:\n self._left_child.set_noisy_label(epsilon, class_values)\n if self._right_child:\n self._right_child.set_noisy_label(epsilon, class_values)\n\n def predict(self, X):\n \"\"\"Predict using this node\"\"\"\n y = []\n X = np.array(X)\n check_array(X)\n\n for x in X:\n node = self.classify(x)\n proba = np.zeros(len(self._classes))\n proba[np.where(self._classes == node.noisy_label)[0].item()] = 1\n y.append(proba)\n\n return np.array(y)\n\n\ndef calc_tree_depth(n_features, max_depth=5):\n \"\"\"Calculate tree depth\n Args:\n n_features (int): Number of features\n max_depth (int, optional): Max depth tree. Defaults to 15.\n Returns:\n [int]: Final depth tree\n \"\"\"\n # Designed using balls-in-bins probability. See the paper for details.\n m = float(n_features)\n depth = 0\n expected_empty = m # the number of unique attributes not selected so far\n while expected_empty > m / 2: # repeat until we have less than half the attributes being empty\n expected_empty = m * ((m - 1) / m) ** depth\n depth += 1\n # the above was only for half the numerical attributes. now add half the categorical attributes\n return min(max_depth, depth)"
]
| [
[
"numpy.max",
"numpy.array",
"numpy.random.choice",
"numpy.random.seed",
"sklearn.utils.fixes._joblib_parallel_args",
"numpy.min",
"numpy.where",
"numpy.random.uniform",
"sklearn.utils.check_array",
"numpy.unique"
]
]
|
jayroxis/quadratic-residual-networks | [
"eeb9b0a449b6ac8cd55f4bb2d11ce1d3071d975d"
]
| [
"QRes/main/discrete_time_identification (KdV)/KdV.py"
]
| [
"\"\"\"\n@author: Maziar Raissi\n\"\"\"\n\nimport sys\nsys.path.insert(0, '../../Utilities/')\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport scipy.io\nfrom plotting import newfig, savefig\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.gridspec as gridspec\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport argparse\n\n\nnp.random.seed(1234)\ntf.set_random_seed(1234)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--mod', default='lite', type=str, help='the version of QRes network, can be \"full\" or \"lite\".')\nparser.add_argument('--epochs', default=50000, type=int, help='number of training epochs.')\nargs = parser.parse_args()\n\n\nclass PhysicsInformedNN:\n # Initialize the class\n def __init__(self, x0, u0, x1, u1, layers, dt, lb, ub, q):\n \n self.lb = lb\n self.ub = ub\n \n self.x0 = x0\n self.x1 = x1\n \n self.u0 = u0\n self.u1 = u1\n \n self.layers = layers\n self.dt = dt\n self.q = max(q,1)\n \n # Initialize NN\n self.weights, self.biases = self.initialize_NN(layers)\n \n # Initialize parameters\n self.lambda_1 = tf.Variable([0.0], dtype=tf.float32)\n self.lambda_2 = tf.Variable([-6.0], dtype=tf.float32) \n \n # Load IRK weights\n tmp = np.float32(np.loadtxt('../../Utilities/IRK_weights/Butcher_IRK%d.txt' % (q), ndmin = 2))\n weights = np.reshape(tmp[0:q**2+q], (q+1,q)) \n self.IRK_alpha = weights[0:-1,:]\n self.IRK_beta = weights[-1:,:] \n self.IRK_times = tmp[q**2+q:]\n \n # tf placeholders and graph\n self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,\n log_device_placement=True))\n \n self.x0_tf = tf.placeholder(tf.float32, shape=(None, self.x0.shape[1]))\n self.x1_tf = tf.placeholder(tf.float32, shape=(None, self.x1.shape[1]))\n self.u0_tf = tf.placeholder(tf.float32, shape=(None, self.u0.shape[1]))\n self.u1_tf = tf.placeholder(tf.float32, shape=(None, self.u1.shape[1]))\n self.dummy_x0_tf = tf.placeholder(tf.float32, shape=(None, self.q)) # dummy variable for fwd_gradients \n self.dummy_x1_tf = tf.placeholder(tf.float32, shape=(None, self.q)) # dummy variable for fwd_gradients \n \n self.U0_pred = self.net_U0(self.x0_tf) # N0 x q\n self.U1_pred = self.net_U1(self.x1_tf) # N1 x q\n \n self.loss = tf.reduce_sum(tf.square(self.u0_tf - self.U0_pred)) + \\\n tf.reduce_sum(tf.square(self.u1_tf - self.U1_pred)) \n \n self.optimizer = tf.contrib.opt.ScipyOptimizerInterface(self.loss, \n method = 'L-BFGS-B', \n options = {'maxiter': 50000,\n 'maxfun': 50000,\n 'maxcor': 50,\n 'maxls': 50,\n 'ftol' : 1.0 * np.finfo(float).eps}) \n \n self.optimizer_Adam = tf.compat.v1.train.AdamOptimizer()\n self.train_op_Adam = self.optimizer_Adam.minimize(self.loss)\n \n init = tf.global_variables_initializer()\n self.sess.run(init)\n \n self.loss_log = []\n \n def initialize_NN(self, layers): \n weights = []\n biases = []\n num_layers = len(layers) \n for l in range(0,num_layers-1):\n W1 = self.xavier_init(size=[layers[l], layers[l+1]])\n W2 = self.xavier_init(size=[layers[l], layers[l+1]])\n b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32)\n weights.append((W1, W2))\n biases.append(b) \n return weights, biases\n \n def xavier_init(self, size):\n in_dim = size[0]\n out_dim = size[1] \n xavier_stddev = np.sqrt(2/(in_dim + out_dim))\n return tf.Variable(tf.truncated_normal([in_dim, out_dim], stddev=xavier_stddev), dtype=tf.float32)\n \n def neural_net(self, X, weights, biases):\n num_layers = len(weights) + 1\n \n H = 2.0*(X - self.lb)/(self.ub - self.lb) - 1.0\n for l in range(0,num_layers-2):\n W1, W2 = weights[l]\n b = biases[l]\n H1 = tf.add(tf.matmul(H, W1), b)\n H2 = tf.matmul(H, W2)\n H = tf.tanh(tf.add(H1 * H2, H1))\n W1, W2 = weights[-1]\n b = biases[-1]\n H1 = tf.add(tf.matmul(H, W1), b)\n H2 = tf.matmul(H, W2)\n Y = tf.add(H1 * H2, H1)\n return Y\n \n def fwd_gradients_0(self, U, x): \n g = tf.gradients(U, x, grad_ys=self.dummy_x0_tf)[0]\n return tf.gradients(g, self.dummy_x0_tf)[0]\n \n def fwd_gradients_1(self, U, x): \n g = tf.gradients(U, x, grad_ys=self.dummy_x1_tf)[0]\n return tf.gradients(g, self.dummy_x1_tf)[0] \n \n def net_U0(self, x):\n lambda_1 = self.lambda_1\n lambda_2 = tf.exp(self.lambda_2)\n U = self.neural_net(x, self.weights, self.biases) \n U_x = self.fwd_gradients_0(U, x)\n U_xx = self.fwd_gradients_0(U_x, x)\n U_xxx = self.fwd_gradients_0(U_xx, x) \n F = -lambda_1*U*U_x - lambda_2*U_xxx\n U0 = U - self.dt*tf.matmul(F, self.IRK_alpha.T)\n return U0\n \n def net_U1(self, x):\n lambda_1 = self.lambda_1\n lambda_2 = tf.exp(self.lambda_2)\n U = self.neural_net(x, self.weights, self.biases) \n U_x = self.fwd_gradients_1(U, x)\n U_xx = self.fwd_gradients_1(U_x, x)\n U_xxx = self.fwd_gradients_1(U_xx, x) \n F = -lambda_1*U*U_x - lambda_2*U_xxx\n U1 = U + self.dt*tf.matmul(F, (self.IRK_beta - self.IRK_alpha).T)\n return U1\n\n def callback(self, loss):\n print('Loss:', loss)\n self.loss_log.append(loss)\n \n def train(self, nIter):\n tf_dict = {self.x0_tf: self.x0, self.u0_tf: self.u0, \n self.x1_tf: self.x1, self.u1_tf: self.u1,\n self.dummy_x0_tf: np.ones((self.x0.shape[0], self.q)),\n self.dummy_x1_tf: np.ones((self.x1.shape[0], self.q))}\n \n start_time = time.time()\n for it in range(nIter):\n self.sess.run(self.train_op_Adam, tf_dict)\n \n # Print\n if it % 10 == 0:\n elapsed = time.time() - start_time\n loss_value = self.sess.run(self.loss, tf_dict)\n lambda_1_value = self.sess.run(self.lambda_1)\n lambda_2_value = np.exp(self.sess.run(self.lambda_2))\n print('It: %d, Loss: %.3e, l1: %.3f, l2: %.5f, Time: %.2f' % \n (it, loss_value, lambda_1_value, lambda_2_value, elapsed))\n self.loss_log.append(loss_value)\n start_time = time.time()\n \n self.optimizer.minimize(self.sess,\n feed_dict = tf_dict,\n fetches = [self.loss],\n loss_callback = self.callback)\n \n def predict(self, x_star):\n \n U0_star = self.sess.run(self.U0_pred, {self.x0_tf: x_star, self.dummy_x0_tf: np.ones((x_star.shape[0], self.q))}) \n U1_star = self.sess.run(self.U1_pred, {self.x1_tf: x_star, self.dummy_x1_tf: np.ones((x_star.shape[0], self.q))})\n \n return U0_star, U1_star\n\n \nif __name__ == \"__main__\": \n \n q = 50\n skip = 120\n\n N0 = 199\n N1 = 201\n \n if args.mod == 'full':\n layers = [1, 35, 35, 35, 35, q]\n else:\n layers = [1, 20, 20, 20, 20, q]\n \n data = scipy.io.loadmat('../Data/KdV.mat')\n \n t_star = data['tt'].flatten()[:,None]\n x_star = data['x'].flatten()[:,None]\n Exact = np.real(data['uu'])\n \n idx_t = 40\n \n ######################################################################\n ######################## Noiseles Data ###############################\n ######################################################################\n noise = 0.0 \n \n idx_x = np.random.choice(Exact.shape[0], N0, replace=False)\n x0 = x_star[idx_x,:]\n u0 = Exact[idx_x,idx_t][:,None]\n u0 = u0 + noise*np.std(u0)*np.random.randn(u0.shape[0], u0.shape[1])\n \n idx_x = np.random.choice(Exact.shape[0], N1, replace=False)\n x1 = x_star[idx_x,:]\n u1 = Exact[idx_x,idx_t + skip][:,None]\n u1 = u1 + noise*np.std(u1)*np.random.randn(u1.shape[0], u1.shape[1])\n \n dt = np.asscalar(t_star[idx_t+skip] - t_star[idx_t]) \n \n # Doman bounds\n lb = x_star.min(0)\n ub = x_star.max(0)\n\n model = PhysicsInformedNN(x0, u0, x1, u1, layers, dt, lb, ub, q)\n model.train(nIter = args.epochs)\n \n U0_pred, U1_pred = model.predict(x_star) \n \n lambda_1_value = model.sess.run(model.lambda_1)\n lambda_2_value = np.exp(model.sess.run(model.lambda_2))\n \n error_lambda_1 = np.abs(lambda_1_value - 1.0)/1.0 *100\n error_lambda_2 = np.abs(lambda_2_value - 0.0025)/0.0025 * 100\n \n print('Error lambda_1: %f%%' % (error_lambda_1))\n print('Error lambda_2: %f%%' % (error_lambda_2))\n loss_log = np.array(model.loss_log)\n np.save('loss/loss_clean_QRes.npy', loss_log) \n \n ######################################################################\n ########################### Noisy Data ###############################\n ######################################################################\n noise = 0.01 \n \n u0 = u0 + noise*np.std(u0)*np.random.randn(u0.shape[0], u0.shape[1])\n u1 = u1 + noise*np.std(u1)*np.random.randn(u1.shape[0], u1.shape[1])\n \n model = PhysicsInformedNN(x0, u0, x1, u1, layers, dt, lb, ub, q) \n model.train(nIter = args.epochs)\n \n U_pred = model.predict(x_star)\n \n U0_pred, U1_pred = model.predict(x_star) \n \n lambda_1_value_noisy = model.sess.run(model.lambda_1)\n lambda_2_value_noisy = np.exp(model.sess.run(model.lambda_2))\n \n error_lambda_1_noisy = np.abs(lambda_1_value_noisy - 1.0)/1.0 *100\n error_lambda_2_noisy = np.abs(lambda_2_value_noisy - 0.0025)/0.0025 * 100\n \n print('Error lambda_1: %f%%' % (error_lambda_1_noisy))\n print('Error lambda_2: %f%%' % (error_lambda_2_noisy))\n loss_log = np.array(model.loss_log)\n np.save('loss/loss_noisy_QRes.npy', loss_log) \n \n ######################################################################\n ############################# Plotting ###############################\n ######################################################################\n \n fig, ax = newfig(1.0, 1.5)\n ax.axis('off')\n \n gs0 = gridspec.GridSpec(1, 2)\n gs0.update(top=1-0.06, bottom=1-1/3+0.05, left=0.15, right=0.85, wspace=0)\n ax = plt.subplot(gs0[:, :])\n \n h = ax.imshow(Exact, interpolation='nearest', cmap='rainbow',\n extent=[t_star.min(),t_star.max(), lb[0], ub[0]],\n origin='lower', aspect='auto')\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n fig.colorbar(h, cax=cax)\n \n line = np.linspace(x_star.min(), x_star.max(), 2)[:,None]\n ax.plot(t_star[idx_t]*np.ones((2,1)), line, 'w-', linewidth = 1.0)\n ax.plot(t_star[idx_t + skip]*np.ones((2,1)), line, 'w-', linewidth = 1.0) \n ax.set_xlabel('$t$')\n ax.set_ylabel('$x$')\n ax.set_title('$u(t,x)$', fontsize = 10)\n \n gs1 = gridspec.GridSpec(1, 2)\n gs1.update(top=1-1/3-0.1, bottom=1-2/3, left=0.15, right=0.85, wspace=0.5)\n\n ax = plt.subplot(gs1[0, 0])\n ax.plot(x_star,Exact[:,idx_t][:,None], 'b', linewidth = 2, label = 'Exact')\n ax.plot(x0, u0, 'rx', linewidth = 2, label = 'Data')\n ax.set_xlabel('$x$')\n ax.set_ylabel('$u(t,x)$')\n ax.set_title('$t = %.2f$\\n%d trainng data' % (t_star[idx_t], u0.shape[0]), fontsize = 10)\n \n ax = plt.subplot(gs1[0, 1])\n ax.plot(x_star,Exact[:,idx_t + skip][:,None], 'b', linewidth = 2, label = 'Exact')\n ax.plot(x1, u1, 'rx', linewidth = 2, label = 'Data')\n ax.set_xlabel('$x$')\n ax.set_ylabel('$u(t,x)$')\n ax.set_title('$t = %.2f$\\n%d trainng data' % (t_star[idx_t+skip], u1.shape[0]), fontsize = 10)\n ax.legend(loc='upper center', bbox_to_anchor=(-0.3, -0.3), ncol=2, frameon=False)\n \n gs2 = gridspec.GridSpec(1, 2)\n gs2.update(top=1-2/3-0.05, bottom=0, left=0.15, right=0.85, wspace=0.0)\n \n ax = plt.subplot(gs2[0, 0])\n ax.axis('off')\n s1 = r'$\\begin{tabular}{ |c|c| } \\hline Correct PDE & $u_t + u u_x + 0.0025 u_{xxx} = 0$ \\\\ \\hline Identified PDE (clean data) & '\n s2 = r'$u_t + %.3f u u_x + %.7f u_{xxx} = 0$ \\\\ \\hline ' % (lambda_1_value, lambda_2_value)\n s3 = r'Identified PDE (1\\% noise) & '\n s4 = r'$u_t + %.3f u u_x + %.7f u_{xxx} = 0$ \\\\ \\hline ' % (lambda_1_value_noisy, lambda_2_value_noisy)\n s5 = r'\\end{tabular}$'\n s = s1+s2+s3+s4+s5\n ax.text(-0.1,0.2,s)\n\n savefig('./figures/KdV') \n \n with open('results.txt', 'w') as f:\n s = 'Error lambda_1: %f%%\\n' % (error_lambda_1) + 'Error lambda_2: %f%%\\n' % (error_lambda_2) + 'Error lambda_1: %f%%\\n' % (error_lambda_1_noisy) +'Error lambda_2: %f%%' % (error_lambda_2_noisy)\n print(s)\n f.write(s)\n "
]
| [
[
"tensorflow.exp",
"numpy.random.choice",
"tensorflow.matmul",
"tensorflow.gradients",
"numpy.finfo",
"tensorflow.global_variables_initializer",
"tensorflow.set_random_seed",
"tensorflow.compat.v1.train.AdamOptimizer",
"tensorflow.Variable",
"numpy.save",
"tensorflow.ConfigProto",
"numpy.asscalar",
"numpy.sqrt",
"tensorflow.add",
"matplotlib.pyplot.subplot",
"numpy.array",
"tensorflow.zeros",
"numpy.reshape",
"numpy.random.randn",
"numpy.real",
"tensorflow.truncated_normal",
"numpy.std",
"numpy.loadtxt",
"tensorflow.placeholder",
"matplotlib.gridspec.GridSpec",
"numpy.random.seed",
"numpy.ones",
"numpy.abs",
"tensorflow.square"
]
]
|
yahanda/automl-image-prediction-with-onnx-on-edge | [
"d3cd47cb90d76123793dd92f9aa6a8bf12b32ef7"
]
| [
"onnxruntime/python/tools/tensorrt/perf/post.py"
]
| [
"import argparse\nimport sys\nimport os\nimport pandas as pd\nimport time\nfrom datetime import datetime, timedelta\nfrom azure.kusto.data import KustoConnectionStringBuilder\nfrom azure.kusto.data.helpers import dataframe_from_result_table \nfrom azure.kusto.ingest import (\n IngestionProperties,\n DataFormat,\n ReportLevel,\n QueuedIngestClient,\n)\nfrom perf_utils import *\n\n# database connection strings \ncluster_ingest = \"https://ingest-onnxruntimedashboarddb.southcentralus.kusto.windows.net\"\ndatabase = \"ep_perf_dashboard\"\n\n# table names\nfail = 'fail'\nmemory = 'memory'\nlatency = 'latency'\nstatus = 'status'\nlatency_over_time = 'latency_over_time'\nspecs = 'specs' \nsession = 'session'\n\ntime_string_format = '%Y-%m-%d %H:%M:%S'\n\ndef parse_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-r\", \"--report_folder\", help=\"Path to the local file report\", required=True)\n parser.add_argument(\n \"-c\", \"--commit_hash\", help=\"Commit id\", required=True)\n parser.add_argument(\n \"-u\", \"--report_url\", help=\"Report Url\", required=True)\n parser.add_argument(\n \"-t\", \"--trt_version\", help=\"Tensorrt Version\", required=True)\n parser.add_argument(\n \"-b\", \"--branch\", help=\"Branch\", required=True)\n return parser.parse_args()\n\ndef parse_csv(report_file):\n table = pd.read_csv(report_file)\n return table\n\ndef adjust_columns(table, columns, db_columns, model_group): \n table = table[columns]\n table = table.set_axis(db_columns, axis=1)\n table = table.assign(Group=model_group)\n return table \n\ndef get_latency_over_time(commit_hash, report_url, branch, latency_table):\n if not latency_table.empty:\n over_time = latency_table\n over_time = over_time.melt(id_vars=[model_title, group_title], var_name='Ep', value_name='Latency')\n over_time = over_time.assign(CommitId=commit_hash)\n over_time = over_time.assign(ReportUrl=report_url)\n over_time = over_time.assign(Branch=branch)\n over_time = over_time[['CommitId', model_title, 'Ep', 'Latency', 'ReportUrl', group_title, 'Branch']]\n over_time.fillna('', inplace=True)\n return over_time\n \ndef get_failures(fail, model_group):\n fail_columns = fail.keys()\n fail_db_columns = [model_title, 'Ep', 'ErrorType', 'ErrorMessage']\n fail = adjust_columns(fail, fail_columns, fail_db_columns, model_group)\n return fail\n\ndef get_memory(memory, model_group): \n memory_columns = [model_title]\n for provider in provider_list: \n if cpu not in provider:\n memory_columns.append(provider + memory_ending)\n memory_db_columns = [model_title, cuda, trt, standalone_trt, cuda_fp16, trt_fp16, standalone_trt_fp16]\n memory = adjust_columns(memory, memory_columns, memory_db_columns, model_group)\n return memory\n\ndef get_latency(latency, model_group):\n latency_columns = [model_title]\n for provider in provider_list: \n latency_columns.append(provider + avg_ending)\n latency_db_columns = table_headers\n latency = adjust_columns(latency, latency_columns, latency_db_columns, model_group)\n return latency\n \ndef get_status(status, model_group):\n status_columns = status.keys()\n status_db_columns = table_headers\n status = adjust_columns(status, status_columns, status_db_columns, model_group)\n return status\n\ndef get_specs(specs, branch, commit_id, upload_time):\n specs = specs.append({'.': 6, 'Spec': 'Branch', 'Version' : branch}, ignore_index=True)\n specs = specs.append({'.': 7, 'Spec': 'CommitId', 'Version' : commit_id}, ignore_index=True)\n specs = specs.append({'.': 8, 'Spec': 'UploadTime', 'Version' : upload_time}, ignore_index=True)\n return specs\n\ndef get_session(session, model_group):\n session_columns = session.keys()\n session_db_columns = [model_title] + ort_provider_list\n session = adjust_columns(session, session_columns, session_db_columns, model_group)\n return session\n\ndef write_table(ingest_client, table, table_name, upload_time, identifier):\n if table.empty:\n return\n table = table.assign(UploadTime=upload_time) # add UploadTime\n table = table.assign(Identifier=identifier) # add Identifier\n ingestion_props = IngestionProperties(\n database=database,\n table=table_name,\n data_format=DataFormat.CSV,\n report_level=ReportLevel.FailuresAndSuccesses\n )\n # append rows\n ingest_client.ingest_from_dataframe(table, ingestion_properties=ingestion_props)\n\ndef get_time(): \n date_time = time.strftime(time_string_format)\n return date_time\n\ndef get_identifier(commit_id, trt_version, branch):\n return commit_id + '_' + trt_version + '_' + branch\n\ndef main():\n \n args = parse_arguments()\n \n # connect to database\n kcsb_ingest = KustoConnectionStringBuilder.with_az_cli_authentication(cluster_ingest)\n ingest_client = QueuedIngestClient(kcsb_ingest)\n date_time = get_time()\n identifier = get_identifier(args.commit_hash, args.trt_version, args.branch)\n \n try:\n result_file = args.report_folder\n\n folders = os.listdir(result_file)\n os.chdir(result_file)\n\n tables = [fail, memory, latency, status, latency_over_time, specs, session]\n table_results = {}\n for table_name in tables:\n table_results[table_name] = pd.DataFrame()\n\n for model_group in folders:\n os.chdir(model_group)\n csv_filenames = os.listdir()\n for csv in csv_filenames:\n table = parse_csv(csv)\n if session in csv: \n table_results[session] = table_results[session].append(get_session(table, model_group), ignore_index=True)\n if specs in csv: \n table_results[specs] = table_results[specs].append(get_specs(table, args.branch, args.commit_hash, date_time), ignore_index=True)\n if fail in csv:\n table_results[fail] = table_results[fail].append(get_failures(table, model_group), ignore_index=True)\n if latency in csv:\n table_results[memory] = table_results[memory].append(get_memory(table, model_group), ignore_index=True)\n table_results[latency] = table_results[latency].append(get_latency(table, model_group), ignore_index=True)\n table_results[latency_over_time] = table_results[latency_over_time].append(get_latency_over_time(args.commit_hash, args.report_url, args.branch, table_results[latency]), ignore_index=True)\n if status in csv: \n table_results[status] = table_results[status].append(get_status(table, model_group), ignore_index=True)\n os.chdir(result_file)\n for table in tables: \n print('writing ' + table + ' to database')\n db_table_name = 'ep_model_' + table\n write_table(ingest_client, table_results[table], db_table_name, date_time, identifier)\n\n except BaseException as e: \n print(str(e))\n sys.exit(1)\n\nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"pandas.DataFrame",
"pandas.read_csv"
]
]
|
haxdds/vectorbt | [
"96a8e24ba64dfadcecffa20ee0d596d4f17240c2",
"96a8e24ba64dfadcecffa20ee0d596d4f17240c2"
]
| [
"tests/test_labels.py",
"vectorbt/utils/colors.py"
]
| [
"from datetime import datetime\n\nimport numpy as np\nimport pandas as pd\n\nimport vectorbt as vbt\n\nclose_ts = pd.DataFrame({\n 'a': [1, 2, 1, 2, 3, 2],\n 'b': [3, 2, 3, 2, 1, 2]\n}, index=pd.Index([\n datetime(2020, 1, 1),\n datetime(2020, 1, 2),\n datetime(2020, 1, 3),\n datetime(2020, 1, 4),\n datetime(2020, 1, 5),\n datetime(2020, 1, 6)\n]))\n\npos_ths = [np.array([1, 1 / 2]), np.array([2, 1 / 2]), np.array([3, 1 / 2])]\nneg_ths = [np.array([1 / 2, 1 / 3]), np.array([1 / 2, 2 / 3]), np.array([1 / 2, 3 / 4])]\n\n\n# ############# Global ############# #\n\ndef setup_module():\n vbt.settings.numba['check_func_suffix'] = True\n vbt.settings.caching.enabled = False\n vbt.settings.caching.whitelist = []\n vbt.settings.caching.blacklist = []\n\n\ndef teardown_module():\n vbt.settings.reset()\n\n\n# ############# generators.py ############# #\n\nclass TestGenerators:\n def test_FMEAN(self):\n pd.testing.assert_frame_equal(\n vbt.FMEAN.run(close_ts, window=(2, 3), ewm=False).fmean,\n pd.DataFrame(\n np.array([\n [1.5, 2.5, 1.6666666666666667, 2.3333333333333335],\n [1.5, 2.5, 2.0, 2.0],\n [2.5, 1.5, 2.3333333333333335, 1.6666666666666667],\n [2.5, 1.5, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n (2, False, 'a'),\n (2, False, 'b'),\n (3, False, 'a'),\n (3, False, 'b'),\n ], names=['fmean_window', 'fmean_ewm', None])\n )\n )\n pd.testing.assert_frame_equal(\n vbt.FMEAN.run(close_ts, window=(2, 3), ewm=True).fmean,\n pd.DataFrame(\n np.array([\n [1.8024691358024691, 2.197530864197531, 1.8125, 2.1875],\n [1.4074074074074074, 2.5925925925925926, 1.625, 2.375],\n [2.2222222222222223, 1.7777777777777777, 2.25, 1.75],\n [2.666666666666667, 1.3333333333333335, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n (2, True, 'a'),\n (2, True, 'b'),\n (3, True, 'a'),\n (3, True, 'b'),\n ], names=['fmean_window', 'fmean_ewm', None])\n )\n )\n\n def test_FSTD(self):\n pd.testing.assert_frame_equal(\n vbt.FSTD.run(close_ts, window=(2, 3), ewm=False).fstd,\n pd.DataFrame(\n np.array([\n [0.5, 0.5, 0.4714045207910384, 0.4714045207910183],\n [0.5, 0.5, 0.816496580927726, 0.816496580927726],\n [0.5, 0.5, 0.4714045207910183, 0.4714045207910384],\n [0.5, 0.5, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n (2, False, 'a'),\n (2, False, 'b'),\n (3, False, 'a'),\n (3, False, 'b'),\n ], names=['fstd_window', 'fstd_ewm', None])\n )\n )\n pd.testing.assert_frame_equal(\n vbt.FSTD.run(close_ts, window=(2, 3), ewm=True).fstd,\n pd.DataFrame(\n np.array([\n [0.64486716348143, 0.6448671634814303, 0.6462561866810479, 0.6462561866810479],\n [0.8833005039168617, 0.8833005039168604, 0.8591246929842246, 0.8591246929842246],\n [0.5916079783099623, 0.5916079783099623, 0.5477225575051662, 0.5477225575051662],\n [0.7071067811865476, 0.7071067811865476, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n (2, True, 'a'),\n (2, True, 'b'),\n (3, True, 'a'),\n (3, True, 'b'),\n ], names=['fstd_window', 'fstd_ewm', None])\n )\n )\n\n def test_FMIN(self):\n pd.testing.assert_frame_equal(\n vbt.FMIN.run(close_ts, window=(2, 3)).fmin,\n pd.DataFrame(\n np.array([\n [1.0, 2.0, 1.0, 2.0],\n [1.0, 2.0, 1.0, 1.0],\n [2.0, 1.0, 2.0, 1.0],\n [2.0, 1.0, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n (2, 'a'),\n (2, 'b'),\n (3, 'a'),\n (3, 'b'),\n ], names=['fmin_window', None])\n )\n )\n\n def test_FMAX(self):\n pd.testing.assert_frame_equal(\n vbt.FMAX.run(close_ts, window=(2, 3)).fmax,\n pd.DataFrame(\n np.array([\n [2.0, 3.0, 2.0, 3.0],\n [2.0, 3.0, 3.0, 3.0],\n [3.0, 2.0, 3.0, 2.0],\n [3.0, 2.0, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n (2, 'a'),\n (2, 'b'),\n (3, 'a'),\n (3, 'b'),\n ], names=['fmax_window', None])\n )\n )\n\n def test_FIXLB(self):\n pd.testing.assert_frame_equal(\n vbt.FIXLB.run(close_ts, n=(2, 3)).labels,\n pd.DataFrame(\n np.array([\n [0.0, 0.0, 1.0, -0.3333333333333333],\n [0.0, 0.0, 0.5, -0.5],\n [2.0, -0.6666666666666666, 1.0, -0.3333333333333333],\n [0.0, 0.0, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n (2, 'a'),\n (2, 'b'),\n (3, 'a'),\n (3, 'b'),\n ], names=['fixlb_n', None])\n )\n )\n\n def test_MEANLB(self):\n pd.testing.assert_frame_equal(\n vbt.MEANLB.run(close_ts, window=(2, 3), ewm=False).labels,\n pd.DataFrame(\n np.array([\n [0.5, -0.16666666666666666, 0.6666666666666667, -0.22222222222222218],\n [-0.25, 0.25, 0.0, 0.0],\n [1.5, -0.5, 1.3333333333333335, -0.4444444444444444],\n [0.25, -0.25, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n (2, False, 'a'),\n (2, False, 'b'),\n (3, False, 'a'),\n (3, False, 'b'),\n ], names=['meanlb_window', 'meanlb_ewm', None])\n )\n )\n pd.testing.assert_frame_equal(\n vbt.MEANLB.run(close_ts, window=(2, 3), ewm=True).labels,\n pd.DataFrame(\n np.array([\n [0.8024691358024691, -0.2674897119341564, 0.8125, -0.2708333333333333],\n [-0.2962962962962963, 0.2962962962962963, -0.1875, 0.1875],\n [1.2222222222222223, -0.40740740740740744, 1.25, -0.4166666666666667],\n [0.3333333333333335, -0.33333333333333326, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n (2, True, 'a'),\n (2, True, 'b'),\n (3, True, 'a'),\n (3, True, 'b'),\n ], names=['meanlb_window', 'meanlb_ewm', None])\n )\n )\n\n def test_LEXLB(self):\n pd.testing.assert_frame_equal(\n vbt.LEXLB.run(close_ts, pos_th=pos_ths, neg_th=neg_ths).labels,\n pd.DataFrame(\n np.array([\n [-1, 1, -1, 1, 0, 0],\n [1, -1, 0, 0, 0, 0],\n [-1, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [1, -1, 1, -1, 0, 0],\n [0, 1, 0, 1, 0, 0]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n ('array_0', 'array_0', 'a'),\n ('array_0', 'array_0', 'b'),\n ('array_1', 'array_1', 'a'),\n ('array_1', 'array_1', 'b'),\n ('array_2', 'array_2', 'a'),\n ('array_2', 'array_2', 'b')\n ], names=['lexlb_pos_th', 'lexlb_neg_th', None])\n )\n )\n\n def test_TRENDLB(self):\n pd.testing.assert_frame_equal(\n vbt.TRENDLB.run(close_ts, pos_th=pos_ths, neg_th=neg_ths, mode='Binary').labels,\n pd.DataFrame(\n np.array([\n [1.0, 0.0, 1.0, 0.0, np.nan, np.nan],\n [0.0, 1.0, 1.0, 0.0, np.nan, np.nan],\n [1.0, 0.0, 1.0, 0.0, np.nan, np.nan],\n [1.0, 0.0, 1.0, 0.0, np.nan, np.nan],\n [np.nan, 1.0, np.nan, 1.0, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n ('array_0', 'array_0', 0, 'a'),\n ('array_0', 'array_0', 0, 'b'),\n ('array_1', 'array_1', 0, 'a'),\n ('array_1', 'array_1', 0, 'b'),\n ('array_2', 'array_2', 0, 'a'),\n ('array_2', 'array_2', 0, 'b')\n ], names=['trendlb_pos_th', 'trendlb_neg_th', 'trendlb_mode', None])\n )\n )\n pd.testing.assert_frame_equal(\n vbt.TRENDLB.run(close_ts, pos_th=pos_ths, neg_th=neg_ths, mode='BinaryCont').labels,\n pd.DataFrame(\n np.array([\n [1.0, 0.0, 1.0, 0.0, np.nan, np.nan],\n [0.0, 1.0, 0.5, 0.5, np.nan, np.nan],\n [1.0, 0.0, 1.0, 0.0, np.nan, np.nan],\n [0.5, 0.5, 0.5, 0.5, np.nan, np.nan],\n [np.nan, 1.0, np.nan, 1.0, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n ('array_0', 'array_0', 1, 'a'),\n ('array_0', 'array_0', 1, 'b'),\n ('array_1', 'array_1', 1, 'a'),\n ('array_1', 'array_1', 1, 'b'),\n ('array_2', 'array_2', 1, 'a'),\n ('array_2', 'array_2', 1, 'b')\n ], names=['trendlb_pos_th', 'trendlb_neg_th', 'trendlb_mode', None])\n )\n )\n pd.testing.assert_frame_equal(\n vbt.TRENDLB.run(close_ts, pos_th=pos_ths, neg_th=neg_ths, mode='BinaryContSat').labels,\n pd.DataFrame(\n np.array([\n [1.0, 0.0, 1.0, 0.0, np.nan, np.nan],\n [0.0, 1.0, 0.5, 0.4999999999999999, np.nan, np.nan],\n [1.0, 0.0, 1.0, 0.0, np.nan, np.nan],\n [0.6666666666666667, 0.0, 0.5, 0.4999999999999999, np.nan, np.nan],\n [np.nan, 1.0, np.nan, 1.0, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n ('array_0', 'array_0', 2, 'a'),\n ('array_0', 'array_0', 2, 'b'),\n ('array_1', 'array_1', 2, 'a'),\n ('array_1', 'array_1', 2, 'b'),\n ('array_2', 'array_2', 2, 'a'),\n ('array_2', 'array_2', 2, 'b')\n ], names=['trendlb_pos_th', 'trendlb_neg_th', 'trendlb_mode', None])\n )\n )\n pd.testing.assert_frame_equal(\n vbt.TRENDLB.run(close_ts, pos_th=pos_ths, neg_th=neg_ths, mode='PctChange').labels,\n pd.DataFrame(\n np.array([\n [1.0, -0.3333333333333333, 2.0, -0.6666666666666666, np.nan, np.nan],\n [-0.5, 0.5, 0.5, -0.5, np.nan, np.nan],\n [2.0, -0.6666666666666666, 2.0, -0.6666666666666666, np.nan, np.nan],\n [0.5, -0.5, 0.5, -0.5, np.nan, np.nan],\n [np.nan, 1.0, np.nan, 1.0, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n ('array_0', 'array_0', 3, 'a'),\n ('array_0', 'array_0', 3, 'b'),\n ('array_1', 'array_1', 3, 'a'),\n ('array_1', 'array_1', 3, 'b'),\n ('array_2', 'array_2', 3, 'a'),\n ('array_2', 'array_2', 3, 'b')\n ], names=['trendlb_pos_th', 'trendlb_neg_th', 'trendlb_mode', None])\n )\n )\n pd.testing.assert_frame_equal(\n vbt.TRENDLB.run(close_ts, pos_th=pos_ths, neg_th=neg_ths, mode='PctChangeNorm').labels,\n pd.DataFrame(\n np.array([\n [0.5, -0.3333333333333333, 0.6666666666666666, -0.6666666666666666, np.nan, np.nan],\n [-0.5, 0.3333333333333333, 0.3333333333333333, -0.5, np.nan, np.nan],\n [0.6666666666666666, -0.6666666666666666, 0.6666666666666666,\n -0.6666666666666666, np.nan, np.nan],\n [0.3333333333333333, -0.5, 0.3333333333333333, -0.5, np.nan, np.nan],\n [np.nan, 0.5, np.nan, 0.5, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n ('array_0', 'array_0', 4, 'a'),\n ('array_0', 'array_0', 4, 'b'),\n ('array_1', 'array_1', 4, 'a'),\n ('array_1', 'array_1', 4, 'b'),\n ('array_2', 'array_2', 4, 'a'),\n ('array_2', 'array_2', 4, 'b')\n ], names=['trendlb_pos_th', 'trendlb_neg_th', 'trendlb_mode', None])\n )\n )\n\n def test_BOLB(self):\n pd.testing.assert_frame_equal(\n vbt.BOLB.run(close_ts, window=1, pos_th=pos_ths, neg_th=neg_ths).labels,\n pd.DataFrame(\n np.array([\n [1.0, -1.0, 0.0, 0.0, 0.0, 0.0],\n [-1.0, 1.0, -1.0, 1.0, -1.0, 1.0],\n [1.0, -1.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, -1.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 1.0, 0.0, 1.0, 0.0, 1.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n (1, 'array_0', 'array_0', 'a'),\n (1, 'array_0', 'array_0', 'b'),\n (1, 'array_1', 'array_1', 'a'),\n (1, 'array_1', 'array_1', 'b'),\n (1, 'array_2', 'array_2', 'a'),\n (1, 'array_2', 'array_2', 'b')\n ], names=['bolb_window', 'bolb_pos_th', 'bolb_neg_th', None])\n )\n )\n pd.testing.assert_frame_equal(\n vbt.BOLB.run(close_ts, window=2, pos_th=pos_ths, neg_th=neg_ths).labels,\n pd.DataFrame(\n np.array([\n [1.0, -1.0, 0.0, 0.0, 0.0, 0.0],\n [-1.0, 1.0, -1.0, 1.0, -1.0, 1.0],\n [1.0, -1.0, 1.0, -1.0, 0.0, 0.0],\n [0.0, -1.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 1.0, 0.0, 1.0, 0.0, 1.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n ]),\n index=close_ts.index,\n columns=pd.MultiIndex.from_tuples([\n (2, 'array_0', 'array_0', 'a'),\n (2, 'array_0', 'array_0', 'b'),\n (2, 'array_1', 'array_1', 'a'),\n (2, 'array_1', 'array_1', 'b'),\n (2, 'array_2', 'array_2', 'a'),\n (2, 'array_2', 'array_2', 'b')\n ], names=['bolb_window', 'bolb_pos_th', 'bolb_neg_th', None])\n )\n )\n",
"# Copyright (c) 2021 Oleg Polakow. All rights reserved.\n# This code is licensed under Apache 2.0 with Commons Clause license (see LICENSE.md for details)\n\n\"\"\"Utilities for working with colors.\"\"\"\n\nimport numpy as np\n\nfrom vectorbt import _typing as tp\n\n\ndef rgb_from_cmap(cmap_name: str, value: float, value_range: tp.Tuple[float, float]) -> str:\n \"\"\"Map `value_range` to colormap with name `cmap_name` and get RGB of the `value` from that range.\"\"\"\n import matplotlib.pyplot as plt\n\n if value_range[0] == value_range[1]:\n norm_value = 0.5\n else:\n norm_value = (value - value_range[0]) / (value_range[1] - value_range[0])\n cmap = plt.get_cmap(cmap_name)\n return \"rgb(%d,%d,%d)\" % tuple(np.round(np.asarray(cmap(norm_value))[:3] * 255))\n\n\ndef adjust_opacity(color: tp.Any, opacity: float) -> str:\n \"\"\"Adjust opacity of color.\"\"\"\n import matplotlib.colors as mc\n\n rgb = mc.to_rgb(color)\n return 'rgba(%d,%d,%d,%.4f)' % (int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255), opacity)\n\n\ndef adjust_lightness(color: tp.Any, amount: float = 0.7) -> str:\n \"\"\"Lightens the given color by multiplying (1-luminosity) by the given amount.\n\n Input can be matplotlib color string, hex string, or RGB tuple.\n Output will be an RGB string.\"\"\"\n import matplotlib.colors as mc\n import colorsys\n\n try:\n c = mc.cnames[color]\n except:\n c = color\n c = colorsys.rgb_to_hls(*mc.to_rgb(c))\n rgb = colorsys.hls_to_rgb(c[0], max(0, min(1, amount * c[1])), c[2])\n return 'rgb(%d,%d,%d)' % (int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255))\n"
]
| [
[
"numpy.array",
"pandas.MultiIndex.from_tuples"
],
[
"matplotlib.colors.to_rgb",
"matplotlib.pyplot.get_cmap"
]
]
|
tzom/yHydra | [
"094714069302d0f5ce1913346d8cde8e24c7a59c"
]
| [
"search_score.py"
]
| [
"import multiprocessing, sys, os\nimport tensorflow as tf\nfrom load_config import CONFIG\nOUTPUT_DIR = CONFIG['RESULTS_DIR']\n\nimport pandas as pd\nimport numpy as np\nfrom score_utils import calc_ions, scoring\nfrom tqdm import tqdm\nfrom utils import batched_list,unbatched_list\nfrom proteomics_utils import normalize_intensities,theoretical_peptide_mass,trim_peaks_list\n\nMAX_N_PEAKS = CONFIG['MAX_N_PEAKS']#500\nBATCH_SIZE=CONFIG['BATCH_SIZE']#64\nNUMBER_OF_THREADS=CONFIG['NUMBER_OF_THREADS']#64\nK=CONFIG['K']#50\nTOPK=1\nVERBOSE = False\nSUBSET=None\n\ndef trim_peaks_list_(x): \n mzs, intensities = x\n mzs, intensities = mzs, normalize_intensities(intensities)\n return trim_peaks_list(mzs, intensities,MAX_N_PEAKS=MAX_N_PEAKS)\n\n#if __name__ == '__main__':\ndef search_score(OUTPUT_DIR=OUTPUT_DIR):\n \n with pd.HDFStore(os.path.join(OUTPUT_DIR,'search_results.h5')) as store, pd.HDFStore(os.path.join(OUTPUT_DIR,'search_results_scored.h5')) as store_out:\n raw_files = store.keys()\n search_results_scored = pd.DataFrame()\n\n with multiprocessing.Pool(NUMBER_OF_THREADS) as p:\n \n peptide_charge = set()\n for key in raw_files:\n search_results = store[key]\n search_results = search_results[:SUBSET]\n print('explode...' )\n tmp = search_results[['topk_peptides','charge']].explode('topk_peptides')\n additional_peptide_charge = list(zip(tmp.topk_peptides,tmp.charge))\n additional_peptide_charge = set(additional_peptide_charge)\n peptide_charge = peptide_charge.union(additional_peptide_charge)\n\n print('calculate ions...')\n ions = list(p.map(calc_ions,tqdm(peptide_charge)))\n peptide_charge_2_ions = dict(zip(peptide_charge,ions))\n\n for key in raw_files:\n search_results = store[key]\n\n top_peptides = []\n top_peptide_is_decoys = []\n top_peptide_distances = []\n best_scores = []\n all_scores = []\n\n\n search_results = search_results[:SUBSET]\n #for i,row in enumerate(search_results.iterrows()):\n for i in tqdm(range(0,len(search_results),BATCH_SIZE)): \n rows = search_results.iloc[i:i+BATCH_SIZE] # TODO: fix last batch\n true_peptide = rows['peptide'].to_numpy()\n batched_topk_peptides = rows['topk_peptides'].to_numpy()\n charges = rows['charge'].to_numpy()\n \n apparent_batch_size = len(rows)\n\n topk_peptides = np.array(unbatched_list(batched_topk_peptides))\n\n # isoforms = list(parser.isoforms(peptideSequence,variable_mods=VARIABLE_MODS)) \n # print(isoforms)\n # for isoform in isoforms:\n # isoform = isoform.replace('oxM','m')\n apparent_K = int(len(topk_peptides)/apparent_batch_size)\n charges_tiled = np.repeat(charges,apparent_K)\n topk_peptides_charge = list(zip(topk_peptides,charges_tiled))\n\n ions = [peptide_charge_2_ions[key] for key in topk_peptides_charge]\n\n # for _ in range(1):\n # if VERBOSE:\n # print('calc ions...')\n # ions = list(p.map(calc_ions,topk_peptides_charge))\n \n ions = np.reshape(ions,(apparent_batch_size,apparent_K,-1))\n #ions = np.zeros((apparent_batch_size,k,200))\n #print(len(ions))\n #ions = list(batched_list(ions,batch_size))\n #mzs = np.array(rows['mzs'])\n #intensities = np.array(rows['intensities'])\n mzs = rows['mzs'].tolist()\n intensities = rows['intensities'].tolist()\n for _ in range(1):\n if VERBOSE:\n print('trim peaks...')\n mzs, intensities = zip(*list(p.map(trim_peaks_list_,list(zip(mzs,intensities)))))\n #mzs, intensities = list(map(trim_ions,rows['mzs'])),list(map(trim_ions,rows['intensities']))\n #mzs, intensities = np.array(rows['mzs']),np.array(rows['intensities'])\n #mzs, intensities = np.expand_dims(mzs,0), np.expand_dims(intensities,0)\n\n mzs = np.array(mzs)\n intensities = np.array(intensities)\n #ions = np.array(ions)\n #print(ions.shape)\n #ions = np.transpose(ions,(1,0,2))\n\n # print(mzs.shape)\n # print(intensities.shape)\n for _ in range(1):\n if VERBOSE:\n print('scoring...')\n best_score_index, best_score, pos_score = scoring(mzs, intensities, ions) \n #print(pos_score.shape)\n #replace zeros with -1\n #pos_score = np.where(pos_score==0.0, -100.0, pos_score)\n sorted_index = np.argsort(pos_score,axis=-1)[:,::-1]\n sorted_index = sorted_index[:,:TOPK]\n #sorted_index = np.reshape(best_score_index,(len(best_score_index),1))\n \n #print(sorted_index)\n top_peptide_ = batched_topk_peptides\n top_peptide_is_decoy_ = rows['is_decoy'].to_numpy()\n top_peptide_distance_ = rows['topk_distances'].to_numpy()\n best_score_ = np.array(pos_score)\n \n top_peptide = [top_peptide_[i][sorted_index[i,:]] for i in range(top_peptide_.shape[0])]\n top_peptide_is_decoy = [top_peptide_is_decoy_[i][sorted_index[i,:]] for i in range(top_peptide_is_decoy_.shape[0])]\n top_peptide_distance = [top_peptide_distance_[i][sorted_index[i,:]] for i in range(top_peptide_distance_.shape[0])]\n best_score = [best_score_[i][sorted_index[i,:]] for i in range(best_score_.shape[0])]\n\n #top_peptide = [batched_topk_peptides[id][b] for id,b in enumerate(best_score_index)]\n #top_peptide_is_decoy = [rows['is_decoy'].to_numpy()[id][b] for id,b in enumerate(best_score_index)]\n #top_peptide_distance = [rows['topk_distances'].to_numpy()[id][b] for id,b in enumerate(best_score_index)]\n if VERBOSE:\n print(sum(top_peptide==true_peptide))\n #print(sum(top_peptide==true_peptide),top_peptide,true_peptide,best_score)\n # if i > 10:\n # quit()\n\n top_peptides.extend(top_peptide)\n top_peptide_is_decoys.extend(top_peptide_is_decoy)\n top_peptide_distances.extend(top_peptide_distance)\n best_scores.extend(best_score)\n all_scores.extend(np.reshape(pos_score,-1))\n\n #search_results = search_results[:SUBSET]\n \n search_results= search_results.iloc[np.repeat(np.arange(len(search_results)), TOPK)]\n\n\n search_results['best_is_decoy']=list(unbatched_list(top_peptide_is_decoys))\n search_results['best_distance']=list(unbatched_list(top_peptide_distances))\n search_results['best_score']=list(unbatched_list(best_scores))\n search_results['best_peptide']=list(unbatched_list(top_peptides))\n all_peptides = list(unbatched_list(top_peptides))\n search_results['peptide_mass']= list(map(lambda x: theoretical_peptide_mass(*x),zip(all_peptides,np.zeros_like(all_peptides))))\n search_results['delta_mass']=search_results['pepmass'] - search_results['peptide_mass']\n print(len(search_results))\n #search_results=search_results.drop(columns=['mzs', 'intensities'])\n print(sum(search_results['best_peptide']==search_results['peptide'])/len(search_results))\n\n print(search_results)\n print(search_results.columns)\n\n #search_results.to_csv('search_results_scored.csv',index=False)\n #search_results.to_hdf(os.path.join(OUTPUT_DIR,'search_results_scored.h5'),key='search_results_scored', mode='w')\n\n #search_results_scored = pd.concat([search_results_scored,search_results],ignore_index=True)\n #with pd.HDFStore(os.path.join(OUTPUT_DIR,'search_results_scored.h5')) as store_out:\n store_out.put(key,search_results)\n #search_results_scored.to_hdf(os.path.join(OUTPUT_DIR,'search_results_scored.h5'),key='search_results_scored', mode='w')"
]
| [
[
"numpy.array",
"numpy.zeros_like",
"numpy.reshape",
"pandas.DataFrame",
"numpy.argsort",
"numpy.repeat"
]
]
|
devmessias/edgeseraser | [
"86b0517db6a13f90ceb7f4a6cca41d051fc80e09"
]
| [
"tests/test_noise_score.py"
]
| [
"import igraph as ig\nimport networkx as nx\nimport numpy as np\nfrom edgeseraser import noise_score\n\n\ndef test_nx_filter():\n g = nx.circulant_graph(10, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n noise_score.filter_nx_graph(g)\n bb = nx.edge_betweenness_centrality(g, normalized=False)\n nx.set_edge_attributes(g, bb, \"betweenness\")\n noise_score.filter_nx_graph(g, field=\"betweenness\")\n g = nx.Graph()\n g.add_nodes_from([chr(i) for i in range(100)])\n g.add_edges_from([(chr(i), chr(i + 1)) for i in range(99)])\n noise_score.filter_nx_graph(g)\n\n\ndef test_get_noise_score():\n noise_score.noisy_scores(\n np.array([1, 2, 3]), np.array([1, 2, 3]), 10, np.array([1, 2, 3])\n )\n\n\ndef test_ig_graph_filter():\n g = ig.Graph.Erdos_Renyi(100, 1, directed=False)\n cl = g.clusters()\n g = cl.giant()\n ne_old = g.ecount()\n g2 = g.copy()\n noise_score.filter_ig_graph(g, 0.1)\n assert ne_old > g.ecount()\n g2.es[\"weight2\"] = 1.0\n noise_score.filter_ig_graph(g2, 0.1, field=\"weight2\")\n assert ne_old > g2.ecount()\n g = ig.Graph()\n for i in range(100):\n g.add_vertex(name=chr(i))\n for i in range(99):\n g.add_edge(chr(i), chr(i + 1))\n noise_score.filter_ig_graph(g, 0.1)\n"
]
| [
[
"numpy.array"
]
]
|
HSouch/TBRIDGE | [
"1f266c64d905eca48749092687376708bcf09d48"
]
| [
"tbridge/medians.py"
]
| [
"from numpy import arange, nan, inf, sort, median, floor, max, nanmedian, transpose, asarray, std\nfrom numpy.random import choice, randint\nfrom scipy.interpolate import interp1d\n\nimport multiprocessing as mp\n\nfrom astropy.io import fits\nfrom astropy.table import Table\n\nimport tbridge\nimport os\nimport shutil\nfrom pathlib import Path\n\n\ndef as_interpolations(profile_list, fill_value_type='min', x_key=\"sma\", y_key=\"intens\"):\n\n interps = []\n\n for prof in profile_list:\n sma, intens = prof[x_key], prof[y_key]\n try:\n interp = interp1d(sma, intens, bounds_error=False, fill_value=0)\n interps.append(interp)\n except ValueError:\n continue\n return interps\n\n\ndef bin_max(profile_list, key=\"sma\"):\n max_val = -999\n\n for prof in profile_list:\n arr_max = max(prof[key])\n max_val = arr_max if arr_max > max_val else max_val\n\n return max_val\n\n\ndef save_medians(median_data, bootstrap_data=None, output_filename=\"medians.fits\"):\n median_sma, median_interp = median_data\n median_intens = median_interp(median_sma)\n\n out_hdulist = fits.HDUList()\n\n t = Table([median_sma, median_intens], names=[\"SMA\", \"INTENS\"])\n out_hdulist.append(fits.BinTableHDU(t))\n if bootstrap_data is not None:\n b_sma, b_1sig_l, b_1sig_u, b_2sig_l, b_2sig_u, b_3sig_l, b_3sig_u, b_5sig_l, b_5sig_u = bootstrap_data\n # Append Lower Bootstrap Value\n t = Table([b_sma, b_1sig_l(b_sma), b_2sig_l(b_sma), b_3sig_l(b_sma), b_5sig_l(b_sma)],\n names=[\"SMA\", \"INTENS_1SIG\", \"INTENS_2SIG\", \"INTENS_3SIG\", \"INTENS_5SIG\"])\n out_hdulist.append(fits.BinTableHDU(t))\n # Append Upper Bootstrap Value\n t = Table([b_sma, b_1sig_u(b_sma), b_2sig_u(b_sma), b_3sig_u(b_sma), b_5sig_u(b_sma)],\n names=[\"SMA\", \"INTENS_1SIG\", \"INTENS_2SIG\", \"INTENS_3SIG\", \"INTENS_5SIG\"])\n out_hdulist.append(fits.BinTableHDU(t))\n\n out_hdulist.writeto(output_filename, overwrite=True)\n\n\ndef index_format(in_dir, x_bins, y_bins, out_dir=\"dir_copy/\", indices=(1, 2), method='duplicate'):\n \"\"\"\n Duplicate a directory but with the files in index format.\n :param in_dir: Input directory of median objects\n :param out_dir: Only needed if running in duplicate mode. Duplicates files in new directory\n :param x_bins: x-axis bin values (usually grabbed from config file)\n :param y_bins: y-axis bin values\n :param indices: When splitting the file, the indices correspond to x and y parameter locations.\n For example, if your filename is: bin_9.2-9.6_0.3-0.5_0.0-0.5_bare.fits\n and you want the x parameter to be 9.2-9.6 and the y parameter to be 0.3-0.5, you would\n set:\n indices=[1,2]\n :param method: duplicate directory or rename files\n 'duplicate' : generate a new directory\n 'rename' : Rename the files in input directory\n :return:\n \"\"\"\n subdirs = os.listdir(in_dir)\n\n if method == 'duplicate' and not os.path.isdir(out_dir):\n os.mkdir(out_dir)\n\n for subdir in subdirs:\n\n if os.path.isfile(in_dir + subdir):\n continue\n\n subdir += \"/\"\n files = os.listdir(in_dir + subdir)\n\n if method == 'duplicate' and not os.path.isdir(out_dir + subdir):\n os.mkdir(out_dir + subdir)\n\n for f in files:\n splits = f.split(\"_\")\n x_split = splits[indices[0]].split(\"-\")\n x_val = (float(x_split[0]) + float(x_split[1])) / 2\n y_split = splits[indices[1]].split(\"-\")\n y_val = (float(y_split[0]) + float(y_split[1])) / 2\n\n x_index, y_index = tbridge.bin_index(x_val, x_bins), tbridge.bin_index(y_val, y_bins)\n\n # print(f, \"|\", x_val, x_index, y_val, y_index)\n new_filename = str(x_index) + \"_\" + str(y_index) + \"_\" + f.split(\"_\")[-1]\n if method == 'duplicate':\n shutil.copyfile(in_dir + subdir + f, out_dir + subdir + new_filename)\n elif method == 'rename':\n os.rename(in_dir + subdir + f, in_dir + subdir + new_filename)\n\n\ndef load_median_info(filename):\n \"\"\"\n Load a complete set of median info (TBriDGE output) in as a dict object.\n :param filename:\n :return:\n \"\"\"\n median_data = {}\n\n hdul = fits.open(filename)\n med, l, u = Table.read(hdul[1]), Table.read(hdul[2]), Table.read(hdul[3])\n\n median_data[\"MED_SMA\"] = med[\"SMA\"]\n median_data[\"MED_INTENS\"] = med[\"INTENS\"]\n\n median_data[\"MED_ADJ\"] = tbridge.adjust_profile(med[\"SMA\"], med[\"INTENS\"])\n\n median_data[\"L_1SIG\"] = (l[\"SMA\"], l[\"INTENS_1SIG\"])\n median_data[\"U_1SIG\"] = (u[\"SMA\"], u[\"INTENS_1SIG\"])\n median_data[\"L_1SIG_ADJ\"] = tbridge.adjust_profile(l[\"SMA\"], l[\"INTENS_1SIG\"])\n median_data[\"U_1SIG_ADJ\"] = tbridge.adjust_profile(u[\"SMA\"], u[\"INTENS_1SIG\"])\n\n median_data[\"L_2SIG\"] = (l[\"SMA\"], l[\"INTENS_2SIG\"])\n median_data[\"U_2SIG\"] = (u[\"SMA\"], u[\"INTENS_2SIG\"])\n median_data[\"L_2SIG_ADJ\"] = tbridge.adjust_profile(l[\"SMA\"], l[\"INTENS_2SIG\"])\n median_data[\"U_2SIG_ADJ\"] = tbridge.adjust_profile(u[\"SMA\"], u[\"INTENS_2SIG\"])\n\n median_data[\"L_3SIG\"] = (l[\"SMA\"], l[\"INTENS_3SIG\"])\n median_data[\"U_3SIG\"] = (u[\"SMA\"], u[\"INTENS_3SIG\"])\n median_data[\"L_3SIG_ADJ\"] = tbridge.adjust_profile(l[\"SMA\"], l[\"INTENS_3SIG\"])\n median_data[\"U_3SIG_ADJ\"] = tbridge.adjust_profile(u[\"SMA\"], u[\"INTENS_3SIG\"])\n\n median_data[\"L_5SIG\"] = (l[\"SMA\"], l[\"INTENS_5SIG\"])\n median_data[\"U_5SIG\"] = (u[\"SMA\"], u[\"INTENS_5SIG\"])\n median_data[\"L_5SIG_ADJ\"] = tbridge.adjust_profile(l[\"SMA\"], l[\"INTENS_5SIG\"])\n median_data[\"U_5SIG_ADJ\"] = tbridge.adjust_profile(u[\"SMA\"], u[\"INTENS_5SIG\"])\n\n return median_data\n\n\ndef bin_max(profiles, key=\"sma\"):\n bin_max = -999\n for prof in profiles:\n try:\n prof_max = prof[key][-1]\n if prof_max > bin_max:\n bin_max = prof_max\n except Exception as error:\n continue\n return bin_max\n\n\ndef normalize_bin(profiles, bin_max, step=0.5, key=\"sma\"):\n new_sma = arange(0, bin_max + step, step)\n normalized_profiles = [prof(new_sma) for prof in profiles]\n\n return new_sma, asarray(normalized_profiles)\n\n\ndef normalized_median(normalized_profiles, handle_nans=True):\n if handle_nans:\n median_prof = nanmedian(normalized_profiles, axis=0)\n else:\n median_prof = median(normalized_profiles, axis=0)\n # print(median_prof.shape)\n return median_prof\n\n\ndef normalized_bootstrap(normalized_profiles, iterations=1001, gaussian=True, handle_nans=True):\n true_median = normalized_median(normalized_profiles)\n\n medians = []\n bin_size = len(normalized_profiles)\n for i in range(iterations):\n pop = normalized_profiles[randint(0, bin_size, size=bin_size)]\n medians.append(normalized_median(pop, handle_nans=handle_nans))\n\n medians = asarray(medians)\n\n # If we can assume a Gaussian distribution, this part is easy\n if gaussian:\n slices = std(transpose(medians), axis=1)\n\n lower_1sig = true_median - slices\n upper_1sig = true_median + slices\n\n lower_2sig = true_median - 2 * slices\n upper_2sig = true_median + 2 * slices\n\n lower_3sig = true_median - 3 * slices\n upper_3sig = true_median + 3 * slices\n\n lower_5sig = true_median - 5 * slices\n upper_5sig = true_median + 5 * slices\n\n return {\"L_1SIG\": lower_1sig, \"L_2SIG\": lower_2sig, \"L_3SIG\": lower_3sig, \"L_5SIG\": lower_5sig,\n \"U_1SIG\": upper_1sig, \"U_2SIG\": upper_2sig, \"U_3SIG\": upper_3sig, \"U_5SIG\": upper_5sig}\n\n else:\n slices = sort(transpose(medians))\n\n lower_index_1sig, upper_index_1sig = int(iterations * 0.159), int(iterations * 0.841)\n lower_index_2sig, upper_index_2sig = int(iterations * 0.023), int(iterations * 0.977)\n lower_index_3sig, upper_index_3sig = int(iterations * 0.002), int(iterations * 0.998)\n\n lower_1sig = [median_slice[lower_index_1sig] for median_slice in slices]\n upper_1sig = [median_slice[upper_index_1sig] for median_slice in slices]\n\n lower_2sig = [median_slice[lower_index_2sig] for median_slice in slices]\n upper_2sig = [median_slice[upper_index_2sig] for median_slice in slices]\n\n lower_3sig = [median_slice[lower_index_3sig] for median_slice in slices]\n upper_3sig = [median_slice[upper_index_3sig] for median_slice in slices]\n\n lower_5sig = [median_slice[0] for median_slice in slices]\n upper_5sig = [median_slice[len(median_slice) - 1] for median_slice in slices]\n\n return {\"L_1SIG\": lower_1sig, \"L_2SIG\": lower_2sig, \"L_3SIG\": lower_3sig, \"L_5SIG\": lower_5sig,\n \"U_1SIG\": upper_1sig, \"U_2SIG\": upper_2sig, \"U_3SIG\": upper_3sig, \"U_5SIG\": upper_5sig}\n\n\ndef median_pipeline(full_filename, output_filename=None, step=0.5):\n profiles = tbridge.load_profile_set(full_filename)\n\n bin_max_value = bin_max(profiles)\n median_sma, normalized_profiles = normalize_bin(tbridge.as_interpolations(profiles), bin_max_value,\n step=step)\n\n median_profile = normalized_median(normalized_profiles)\n b_dict = normalized_bootstrap(normalized_profiles)\n\n if output_filename is not None:\n out_hdulist = fits.HDUList()\n\n med_table = Table([median_sma, median_profile], names=[\"SMA\", \"INTENS\"])\n\n b_lower_table = Table([median_sma, b_dict[\"L_1SIG\"],\n b_dict[\"L_2SIG\"], b_dict[\"L_3SIG\"], b_dict[\"L_5SIG\"]],\n names=[\"SMA\", \"INTENS_1SIG\", \"INTENS_2SIG\", \"INTENS_3SIG\", \"INTENS_5SIG\"])\n\n b_upper_table = Table([median_sma, b_dict[\"U_1SIG\"], b_dict[\"U_2SIG\"],\n b_dict[\"U_3SIG\"], b_dict[\"U_5SIG\"]],\n names=[\"SMA\", \"INTENS_1SIG\", \"INTENS_2SIG\", \"INTENS_3SIG\", \"INTENS_5SIG\"])\n\n out_hdulist.append(fits.BinTableHDU(med_table))\n out_hdulist.append(fits.BinTableHDU(b_lower_table))\n out_hdulist.append(fits.BinTableHDU(b_upper_table))\n\n out_hdulist.writeto(output_filename, overwrite=True)\n\n return b_dict.update({\"MEDIAN\": med_table, \"SMA\": median_sma})\n\n\n"
]
| [
[
"numpy.max",
"scipy.interpolate.interp1d",
"numpy.asarray",
"numpy.median",
"numpy.arange",
"numpy.transpose",
"numpy.random.randint",
"numpy.nanmedian"
]
]
|
Kai-46/opencv | [
"e82e672a933c8bd713ff53ac9ca553ede169b566"
]
| [
"samples/python/dis_opt_flow.py"
]
| [
"#!/usr/bin/env python\n\n'''\nexample to show optical flow estimation using DISOpticalFlow\n\nUSAGE: dis_opt_flow.py [<video_source>]\n\nKeys:\n 1 - toggle HSV flow visualization\n 2 - toggle glitch\n 3 - toggle spatial propagation of flow vectors\n 4 - toggle temporal propagation of flow vectors\nESC - exit\n'''\n\n# Python 2/3 compatibility\nfrom __future__ import print_function\n\nimport numpy as np\nimport cv2 as cv\nimport video\n\n\ndef draw_flow(img, flow, step=16):\n h, w = img.shape[:2]\n y, x = np.mgrid[step/2:h:step, step/2:w:step].reshape(2,-1).astype(int)\n fx, fy = flow[y,x].T\n lines = np.vstack([x, y, x+fx, y+fy]).T.reshape(-1, 2, 2)\n lines = np.int32(lines + 0.5)\n vis = cv.cvtColor(img, cv.COLOR_GRAY2BGR)\n cv.polylines(vis, lines, 0, (0, 255, 0))\n for (x1, y1), (x2, y2) in lines:\n cv.circle(vis, (x1, y1), 1, (0, 255, 0), -1)\n return vis\n\n\ndef draw_hsv(flow):\n h, w = flow.shape[:2]\n fx, fy = flow[:,:,0], flow[:,:,1]\n ang = np.arctan2(fy, fx) + np.pi\n v = np.sqrt(fx*fx+fy*fy)\n hsv = np.zeros((h, w, 3), np.uint8)\n hsv[...,0] = ang*(180/np.pi/2)\n hsv[...,1] = 255\n hsv[...,2] = np.minimum(v*4, 255)\n bgr = cv.cvtColor(hsv, cv.COLOR_HSV2BGR)\n return bgr\n\n\ndef warp_flow(img, flow):\n h, w = flow.shape[:2]\n flow = -flow\n flow[:,:,0] += np.arange(w)\n flow[:,:,1] += np.arange(h)[:,np.newaxis]\n res = cv.remap(img, flow, None, cv.INTER_LINEAR)\n return res\n\n\nif __name__ == '__main__':\n import sys\n print(__doc__)\n try:\n fn = sys.argv[1]\n except IndexError:\n fn = 0\n\n cam = video.create_capture(fn)\n ret, prev = cam.read()\n prevgray = cv.cvtColor(prev, cv.COLOR_BGR2GRAY)\n show_hsv = False\n show_glitch = False\n use_spatial_propagation = False\n use_temporal_propagation = True\n cur_glitch = prev.copy()\n inst = cv.DISOpticalFlow.create(cv.DISOPTICAL_FLOW_PRESET_MEDIUM)\n inst.setUseSpatialPropagation(use_spatial_propagation)\n\n flow = None\n while True:\n ret, img = cam.read()\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n if flow is not None and use_temporal_propagation:\n #warp previous flow to get an initial approximation for the current flow:\n flow = inst.calc(prevgray, gray, warp_flow(flow,flow))\n else:\n flow = inst.calc(prevgray, gray, None)\n prevgray = gray\n\n cv.imshow('flow', draw_flow(gray, flow))\n if show_hsv:\n cv.imshow('flow HSV', draw_hsv(flow))\n if show_glitch:\n cur_glitch = warp_flow(cur_glitch, flow)\n cv.imshow('glitch', cur_glitch)\n\n ch = 0xFF & cv.waitKey(5)\n if ch == 27:\n break\n if ch == ord('1'):\n show_hsv = not show_hsv\n print('HSV flow visualization is', ['off', 'on'][show_hsv])\n if ch == ord('2'):\n show_glitch = not show_glitch\n if show_glitch:\n cur_glitch = img.copy()\n print('glitch is', ['off', 'on'][show_glitch])\n if ch == ord('3'):\n use_spatial_propagation = not use_spatial_propagation\n inst.setUseSpatialPropagation(use_spatial_propagation)\n print('spatial propagation is', ['off', 'on'][use_spatial_propagation])\n if ch == ord('4'):\n use_temporal_propagation = not use_temporal_propagation\n print('temporal propagation is', ['off', 'on'][use_temporal_propagation])\n cv.destroyAllWindows()\n"
]
| [
[
"numpy.zeros",
"numpy.minimum",
"numpy.arange",
"numpy.arctan2",
"numpy.sqrt",
"numpy.int32",
"numpy.vstack"
]
]
|
huy-ha/garage | [
"259b6faf7134314e2db738c4f0357d7883699773"
]
| [
"src/garage/tf/policies/discrete_qf_derived_policy.py"
]
| [
"\"\"\"A Discrete QFunction-derived policy.\n\nThis policy chooses the action that yields to the largest Q-value.\n\"\"\"\nimport akro\nimport numpy as np\nimport tensorflow as tf\n\nfrom garage.misc.overrides import overrides\nfrom garage.tf.policies import Policy\n\n\nclass DiscreteQfDerivedPolicy(Policy):\n \"\"\"DiscreteQfDerived policy.\n\n Args:\n env_spec (garage.envs.env_spec.EnvSpec): Environment specification.\n qf (garage.q_functions.QFunction): The q-function used.\n name (str): Name of the policy.\n \"\"\"\n\n def __init__(self, env_spec, qf, name='DiscreteQfDerivedPolicy'):\n super().__init__(name, env_spec)\n\n assert isinstance(env_spec.action_space, akro.Discrete)\n self._env_spec = env_spec\n self._qf = qf\n\n self._initialize()\n\n def _initialize(self):\n self._f_qval = tf.compat.v1.get_default_session().make_callable(\n self._qf.q_vals,\n feed_list=[self._qf.model.networks['default'].input])\n\n @property\n def vectorized(self):\n \"\"\"Vectorized or not.\"\"\"\n return True\n\n @overrides\n def get_action(self, observation):\n \"\"\"Get action from this policy for the input observation.\n\n Args:\n observation (numpy.ndarray): Observation from environment.\n\n Returns:\n Single optimal action from this policy.\n\n \"\"\"\n q_vals = self._f_qval([observation])\n opt_action = np.argmax(q_vals)\n\n return opt_action\n\n @overrides\n def get_actions(self, observations):\n \"\"\"Get actions from this policy for the input observations.\n\n Args:\n observations (numpy.ndarray): Observations from environment.\n\n Returns:\n Optimal actions from this policy.\n\n \"\"\"\n q_vals = self._f_qval(observations)\n opt_actions = np.argmax(q_vals, axis=1)\n\n return opt_actions\n\n def __getstate__(self):\n \"\"\"Object.__getstate__.\"\"\"\n new_dict = self.__dict__.copy()\n del new_dict['_f_qval']\n return new_dict\n\n def __setstate__(self, state):\n \"\"\"Object.__setstate__.\"\"\"\n self.__dict__.update(state)\n self._initialize()\n"
]
| [
[
"tensorflow.compat.v1.get_default_session",
"numpy.argmax"
]
]
|
vss888/statsmodels | [
"e56c4046ff8807c3c16d6a9293b5cb5dfe6f0cd0"
]
| [
"statsmodels/examples/ex_kde_normalreference.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nAuthor: Padarn Wilson\n\nPerformance of normal reference plug-in estimator vs silverman. Sample is drawn\nfrom a mixture of gaussians. Distribution has been chosen to be reasoanbly close\nto normal.\n\"\"\"\n\nfrom __future__ import print_function\nimport numpy as np\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nimport statsmodels.nonparametric.api as npar\nfrom statsmodels.distributions.mixture_rvs import mixture_rvs\n\n# example from test_kde.py mixture of two normal distributions\nnp.random.seed(12345)\nx = mixture_rvs([.1, .9], size=200, dist=[stats.norm, stats.norm],\n kwargs=(dict(loc=0, scale=.5), dict(loc=1, scale=.5)))\n\nkde = npar.KDEUnivariate(x)\n\n\nkernel_names = ['Gaussian', 'Epanechnikov', 'Biweight',\n 'Triangular', 'Triweight', 'Cosine'\n ]\n\nkernel_switch = ['gau', 'epa', 'tri', 'biw',\n 'triw', 'cos'\n ]\n\n\ndef true_pdf(x):\n pdf = 0.1 * stats.norm.pdf(x, loc=0, scale=0.5)\n pdf += 0.9 * stats.norm.pdf(x, loc=1, scale=0.5)\n return pdf\n\nfig = plt.figure()\nfor ii, kn in enumerate(kernel_switch):\n\n ax = fig.add_subplot(2, 3, ii + 1) # without uniform\n\n # gh5792. Remove except after matplotlib>2.1 required\n try:\n ax.hist(x, bins=20, density=True, alpha=0.25)\n except AttributeError:\n ax.hist(x, bins=20, normed=True, alpha=0.25)\n\n kde.fit(kernel=kn, bw='silverman', fft=False)\n ax.plot(kde.support, kde.density)\n\n kde.fit(kernel=kn, bw='normal_reference', fft=False)\n ax.plot(kde.support, kde.density)\n\n ax.plot(kde.support, true_pdf(kde.support), color='black', linestyle='--')\n\n ax.set_title(kernel_names[ii])\n\n\nax.legend(['silverman', 'normal reference', 'true pdf'], loc='lower right')\nax.set_title('200 points')\nplt.show()\n"
]
| [
[
"numpy.random.seed",
"matplotlib.pyplot.show",
"scipy.stats.norm.pdf",
"matplotlib.pyplot.figure"
]
]
|
Sunethan/APD-analyser | [
"30a190c763017017ce16e171b5bf641fda62a4b0"
]
| [
"plugin/GenerationRate/BandToBandTunneling.py"
]
| [
"import numpy as np\nimport physics as phys\nimport utils\n\nq = 1.6e-19 # [C]\nme = 9.11e-31 # [kg]\nhbar = 1.054e-34 # [J-s]\neps_InP = 12.5 * 8.85e-14 # [F/cm]\neps_InGaAs = 13.9 * 8.85e-14 # [F/cm] In 0.53 Ga 0.47 As\nEg_InP = 1.35 * q # [J]\nEg_InGaAs = 0.742 * q # [J] # TCAD 應該是 0.7428\n\n\ndef Jt_E_InGaAs(F, ND):\n # 前置參數(來自 Jt_InGaAs)\n mr = 1\n ratio = 0.06\n alpha = 1\n gamma = 1 # [Edx ~ E * (W * gamma)] 之前不知為何設定為 0.5,目前覺得這個修正 gamma 應該不需存在。\n F = F * 100 # 把單位從 V/cm 轉成 V/m\n\n # 其他參數\n me = 9.11e-31 # [kg]\n mc = 0.04 * me # [kg]\n mv = 0.04 * me # [kg]\n # meff = 2 * mc * mv / (mc + mv) * mr # [kg]\n meff = 0.04 * mr * me\n # Eg = 0.718 * q # [J] [From TCAD]\n Eg = Eg_InGaAs # [J] [https://www.batop.de/information/Eg_InGaAs.html#]\n w = ratio * eps_InGaAs / (q * ND)\n TunnelingCurrent = (2 * meff / Eg) ** 0.5 * (\n q ** 3 * F ** (alpha + 1) * w * gamma / ((2 * np.pi) ** 3 * hbar ** 2)) * \\\n np.exp(- np.pi / (4 * q * hbar * F) * (2 * meff * Eg ** 3) ** 0.5)\n return TunnelingCurrent * 1e-4 # [A / cm^2]\n\n\n\ndef Jt_InGaAs(V, ND, alpha, mr, ratio):\n # (J.J. Liou 1980)\n gamma = 1 # [Edx ~ E * (W * gamma)] 之前不知為何設定為 0.5,目前覺得這個修正 gamma 應該不需存在。\n me = 9.11e-31 # [kg]\n mc = 0.04 * me # [kg]\n mv = 0.04 * me # [kg]\n # meff = 2 * mc * mv / (mc + mv) * mr # [kg]\n meff = 0.04 * mr * me\n # Eg = 0.718 * q # [J] [From TCAD]\n Eg = Eg_InGaAs # [J] [https://www.batop.de/information/Eg_InGaAs.html#]\n F = (2 * q * V * ND / eps_InGaAs) ** 0.5 * 100 # [V/m]\n w = ratio * (2 * eps_InGaAs * V / (q * ND)) ** 0.5 / 100 # [m]\n hbar = 1.054e-34 # [J-s]\n #print('A: %.3e, TCAD: %.3e ' % ((2 * meff / Eg) ** 0.5 * q ** 2 / ((2 * np.pi) ** 3 * hbar ** 2), 7.271e19))\n #print('B: %.3e, TCAD: %.3e' % (np.pi / (4 * q * hbar) * (2 * meff * Eg ** 3) ** 0.5, 5.14e6))\n\n A_TCAD = 7.271e19 * 1e4 # [m-2s-1V-2]\n B_TCAD = 5.14e6 * 100 # [V/m]\n\n TunnelingCurrent = (2 * meff / Eg) ** 0.5 * (q ** 3 * F ** (alpha + 1) * w * gamma / ((2 * np.pi) ** 3 * hbar ** 2)) * \\\n np.exp(- np.pi / (4 * q * hbar * F) * (2 * meff * Eg ** 3) ** 0.5)\n\n TunnelingCurrent_TCAD = A_TCAD * q * w * F ** (alpha + 1) * np.exp(- B_TCAD / F) * 1e-4 # [A/cm2]\n return TunnelingCurrent * 1e-4 # [A / cm^2]\n\n\ndef Jt_InP(V, ND, alpha, mr, ratio):\n # (J.J. Liou 1980)\n gamma = 1 # [Edx ~ E * (W * gamma)] 之前不知為何設定為 0.5,目前覺得這個修正 gamma 應該不需存在。\n me = 9.11e-31 # [kg]\n mc = 0.1149 * me # [kg] 正確是 0.1149,但 Ando 似乎是 0.065\n mv = 0.1149 * me # [kg]\n #meff = 0.1149 * mr * me\n meff = 2 * mc * mv / (mc + mv)\n # Eg = 0.718 * q # [J] [From TCAD]\n Eg = Eg_InP # [J] [https://www.batop.de/information/Eg_InGaAs.html#]\n F = (2 * q * V * ND / eps_InP) ** 0.5 * 100 # [V/m]\n w = ratio * (2 * eps_InP * V / (q * ND)) ** 0.5 / 100 # [m]\n hbar = 1.054e-34 # [J-s]\n #print((2 * meff / Eg) ** 0.5 * q ** 2 / ((2 * np.pi) ** 3 * hbar ** 2) * 0.4)\n TunnelingCurrent = (2 * meff / Eg) ** 0.5 * (q ** 3 * F ** (alpha + 1) * w * gamma / ((2 * np.pi) ** 3 * hbar ** 2)) * \\\n np.exp(- np.pi / (4 * q * hbar * F) * (2 * meff * Eg ** 3) ** 0.5)\n return TunnelingCurrent * 1e-4 # [A / cm^2]\n\n\ndef G_BTB_InGaAs(E_Vcm, T, mr):\n if type(E_Vcm) is np.ndarray:\n G = []\n for F in E_Vcm:\n if F == 0:\n G.append(0)\n else:\n E = F * 100\n meff = 0.04 * mr * me\n # TCAD: A = 7.271e19 [cm-2s-1V-2]\n A = (2 * meff / (q * phys.Eg_InGaAs(T))) ** 0.5 * q ** 2 / ((2 * np.pi) ** 3 * hbar ** 2) # [m-2s-1V-2]\n # A = 7.271e19 * 1e4\n # TCAD: B = 5.14e6 [V/cm]\n B = np.pi / (4 * q * hbar) * (2 * meff * (q * phys.Eg_InGaAs(T)) ** 3) ** 0.5 # [V/m]\n # B = 5.14e6 * 100 # [V/m]\n G.append(A * E ** 2 * np.exp(- B / E))\n return np.asarray(G)\n else:\n if E_Vcm == 0:\n return 0\n else:\n E = E_Vcm * 100 # [V/m]\n meff = 0.04 * mr * me\n # TCAD: A = 7.271e19 [cm-2s-1V-2]\n A = (2 * meff / phys.Eg_InGaAs(T)) ** 0.5 * q ** 2 / ((2 * np.pi) ** 3 * hbar ** 2) # [m-2s-1V-2]\n # A = 7.271e19 * 1e4\n # TCAD: B = 5.14e6 [V/cm]\n B = np.pi / (4 * q * hbar) * (2 * meff * phys.Eg_InGaAs(T) ** 3) ** 0.5 # [V/m]\n # B = 5.14e6 * 100 # [V/M]\n return A * E ** 2 * np.exp(- B / E) # E[V/m] ---> G = [m-3s-1]\n\n\ndef G_BTB_InP(E_Vcm, T, m_ratio):\n if type(E_Vcm) is np.ndarray:\n G = []\n for F in E_Vcm:\n if F == 0:\n G.append(0)\n else:\n E = F * 100\n meff = m_ratio * me # 0.1149 * me\n # TCAD: A = 7.271e19 [cm-2s-1V-2]\n A = (2 * meff / (q * phys.Eg_InP(T))) ** 0.5 * q ** 2 / ((2 * np.pi) ** 3 * hbar ** 2) # [m-2s-1V-2]\n # TCAD: B = 5.14e6 [V/cm]\n B = np.pi / (4 * q * hbar) * (2 * meff * (q * phys.Eg_InP(T)) ** 3) ** 0.5 # [V/m]\n G.append(A * E ** 2 * np.exp(- B / E)) # E[V/m] ---> G = [m-3s-1]\n return np.asarray(G)\n else:\n if E_Vcm == 0:\n return 0\n else:\n E = E_Vcm * 100\n meff = m_ratio * me # 0.1149 * me\n # TCAD: A = 7.271e19 [cm-2s-1V-2]\n A = (2 * meff / phys.Eg_InP(T)) ** 0.5 * q ** 2 / ((2 * np.pi) ** 3 * hbar ** 2) # [m-2s-1V-2]\n # TCAD: B = 5.14e6 [V/cm]\n B = np.pi / (4 * q * hbar) * (2 * meff * phys.Eg_InP(T) ** 3) ** 0.5 # [V/m]\n return A * E ** 2 * np.exp(- B / E) # E[V/m] ---> G = [m-3s-1]\n\n\ndef J_BTB_InP(x_cm_array, E_Vcm_array, T, m_ratio):\n return utils.ydx(x_cm_array, q * G_BTB_InP(E_Vcm_array, T, m_ratio), 0, len(x_cm_array) - 1)\n\n\ndef J_BTB_InGaAs(x_cm_array, E_Vcm_array, T, m_ratio):\n return utils.ydx(x_cm_array, q * G_BTB_InGaAs(E_Vcm_array, T, m_ratio / 0.04), 0, len(x_cm_array) - 1)\n\n\ndef Em_InGaAs(V, ND):\n F = (2 * q * V * ND / eps_InGaAs) ** 0.5 # [V/cm]\n return F\n\n\ndef Em_InP(V, ND):\n F = (2 * q * V * ND / eps_InP) ** 0.5 # [V/cm]\n return F\n\n\ndef W_InGaAs(V, ND):\n w = (2 * eps_InGaAs * V / (q * ND)) ** 0.5\n return w # [cm]\n\n\ndef W_InP(V, ND):\n w = (2 * eps_InP * V / (q * ND)) ** 0.5\n return w # [cm]\n"
]
| [
[
"numpy.asarray",
"numpy.exp"
]
]
|
liyufan/recapture | [
"52ecf446ba6438275256d59cadd5a17de08d591c"
]
| [
"LBP_WS.py"
]
| [
"import argparse\nimport os\nimport pickle as pkl\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport pywt\nimport skimage\nimport skimage.io\nfrom skimage import feature\nfrom sklearn import svm, metrics\nfrom sklearn.model_selection import GridSearchCV, train_test_split\nfrom sklearn.utils import Bunch\n\n\ndef lbp_describe(image, p, r, eps=1e-7, vis=False):\n\tlbp = feature.local_binary_pattern(image, p, r, method='uniform')\n\thist, _ = np.histogram(lbp.ravel(), bins=np.arange(0, p + 3), range=(0, p + 2))\n\n\thist = hist.astype(\"float\")\n\thist /= (hist.sum() + eps)\n\n\treturn (hist, lbp / (p + 2) * 255) if vis else hist\n\n\ndef wavelet(img):\n\tcoeffs = pywt.wavedec2(img, wavelet='haar', level=3)\n\tcA3, (cH3, cV3, cD3), (cH2, cV2, cD2), (cH1, cV1, cD1) = coeffs\n\tfeature = []\n\tfor mat in [cH3, cV3, cD3, cH2, cV2, cD2, cH1, cV1, cD1]:\n\t\tfeature.append(mat.mean())\n\t\tfeature.append(mat.std())\n\n\treturn np.array(feature)\n\n# noinspection DuplicatedCode\ndef prepare_image_feature(container_path, dimension=(64, 64), re_gen=False, use_existed=False):\n\timage_dir = Path(container_path) # /train or /test\n\t# folders = [directory for directory in image_dir.iterdir() if\n\t# directory.is_dir()] # 文件夹列表:[/RecapturedImage, /SingleCapturedImage]\n\t# TODO: Change name here\n\tclass_array = ['RecapturedImage', 'SingleCapturedImage']\n\tfolders = []\n\tfor cls in class_array:\n\t\tp = image_dir.joinpath(cls)\n\t\tfolders.append(p)\n\tcategories = [fo.name for fo in folders] # 文件夹名称列表:['Recapture..', 'singleCapture..']\n\tdescr = \"A image classification dataset\"\n\tlbp_param = [(8, 1), (16, 2), (24, 3), (24, 4)]\n\tlbp_ws_hist_data = []\n\ttarget = []\n\tfile_names = []\n\tfile = Path()\n\tfor label, direc in enumerate(folders): # label 0,1为文件夹下标,direc为文件夹:/RecapturedImage /Single..\n\t\tlbp_file_path = image_dir.joinpath(direc, 'lbp_ws.pkl') # 生成pkl文件\n\t\tif lbp_file_path.exists() and lbp_file_path.stat().st_size > 0:\n\t\t\twith open(lbp_file_path, 'rb') as cache_file:\n\t\t\t\tlbp_ws_dic = pkl.load(cache_file)\n\t\telse:\n\t\t\tlbp_ws_dic = dict()\n\t\tdir_stack = [direc]\n\t\twhile len(dir_stack):\n\t\t\tcur_dir = dir_stack.pop() # 当前文件夹\n\t\t\tprint(f'iter into {cur_dir.name}')\n\t\t\tfor j, dir in enumerate(cur_dir.iterdir()):\n\t\t\t\tif dir.is_dir(): # /recapture里面还有文件夹\n\t\t\t\t\tif dir.name != 'archive':\n\t\t\t\t\t\tprint(f'find folder {dir.name}')\n\t\t\t\t\t\tdir_stack.append(dir)\n\t\t\t\t\tcontinue\n\t\t\t\telif dir.is_file(): # 检查到文件,判断是否是图片\n\t\t\t\t\tfile = dir\n\t\t\t\tif file.suffix not in ('.JPG', '.jpg', '.png', '.PNG'):\n\t\t\t\t\tprint(f'skip non image file {file}')\n\t\t\t\t\tcontinue\n\t\t\t\tif file in lbp_ws_dic and not re_gen: # 旧的lbp_ws_dic中含有当前图片lbp,读取至lbp_ws_hist_data中,然后跳至下一张图片\n\t\t\t\t\tlbp_ws_hist_data.append(lbp_ws_dic[file])\n\t\t\t\t\ttarget.append(label)\n\t\t\t\t\tfile_names.append(file)\n\t\t\t\t\tcontinue\n\t\t\t\tif use_existed:\n\t\t\t\t\tcontinue\n\t\t\t\tprint(f'start reading {j}: {file}')\n\t\t\t\timage = skimage.io.imread(file)\n\t\t\t\tif len(image) == 2:\n\t\t\t\t\timage = image[0]\n\t\t\t\t(B, G, R) = cv2.split(image)\n\t\t\t\tprint(image.shape)\n\t\t\t\tgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\t\t\t\tlbp_feature = np.concatenate([lbp_describe(gray, p, r) for p, r in lbp_param]) # 当前图片的lbp\n\t\t\t\twavelet_feature = np.concatenate([wavelet(channel) for channel in [B, G, R]])\n\t\t\t\tlbp_ws_feature = np.concatenate([lbp_feature, wavelet_feature])\n\t\t\t\tlbp_ws_dic[file] = lbp_ws_feature # lbp_ws_dic中含有file下标\n\n\t\t\t\tprint(f'dumping...')\n\t\t\t\twith open(lbp_file_path, 'wb') as cache_file:\n\t\t\t\t\tpkl.dump(lbp_ws_dic, cache_file)\n\n\t\t\t\tprint(f'lbp feature: {len(lbp_ws_feature)}: {lbp_ws_feature}')\n\n\t\t\t\t# img_resized = resize(image, dimension, anti_aliasing=True, mode='reflect')\n\t\t\t\t# print(f'size after resize {img_resized.shape}')\n\n\t\t\t\t# flat_data.append(img_resized.flatten())\n\t\t\t\t# images.append(img_resized)\n\t\t\t\tlbp_ws_hist_data.append(lbp_ws_feature) # lbp_ws_hist_data中没有file下标\n\t\t\t\ttarget.append(label)\n\t\t\t\tfile_names.append(file)\n\n\tlbp_ws_hist_data = np.array(lbp_ws_hist_data)\n\ttarget = np.array(target)\n\t# flat_data = np.array(flat_data)\n\t# images = np.array(images)\n\n\treturn Bunch(\n\t\tlbp_ws_hist_data=lbp_ws_hist_data,\n\t\ttarget=target,\n\t\ttarget_names=categories,\n\t\tfile_list=file_names,\n\t\t# images=images,\n\t\tDESCR=descr)\n\n\ndef vis_one(img_path, model_path, log_lbp=False):\n\timg_path = Path(img_path)\n\tfile_name = img_path.stem\n\tbase_path = img_path.parent.parent.parent\n\twith open(model_path, 'rb') as f:\n\t\tclf = pkl.load(f)\n\tprint(f'processing image {img_path}')\n\n\timage = skimage.io.imread(img_path)\n\tgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\tlbp_param = [(8, 1), (16, 2), (24, 3), (24, 4)]\n\tlbp_image_pair = [lbp_describe(gray, p, r, vis=True) for p, r in lbp_param]\n\tlbp_img_list = list(zip(*lbp_image_pair))\n\tlbp_feature = np.concatenate(lbp_img_list[0])\n\tif log_lbp:\n\t\twith open(f'{base_path}/vis_lbp_hist.txt', 'a') as f:\n\t\t\tf.write(f'{img_path} {lbp_feature}\\n')\n\tfor i, lbp_img in enumerate(lbp_img_list[1]):\n\t\twrite_path = os.path.join(base_path, 'res', 'vis', f'{file_name}_lbp{str(lbp_param[i])}.png')\n\t\tprint(f'writing {i}th LBP map to {write_path}')\n\t\tcv2.imwrite(write_path, lbp_img)\n\tpreds = clf.predict(np.array([lbp_feature]))\n\tprint(f'Predicted class: {class_array[int(preds)]}')\n\treturn preds\n\n\ndef clear_folder(path):\n\tif path.exists():\n\t\tos.system(f'rm -r {path}')\n\tos.makedirs(path)\n\n\n# noinspection DuplicatedCode\ndef test_all(test_path, model_path):\n\ttest_path = Path(test_path)\n\tres_path = test_path.parent.joinpath('res') # res文件夹为SVM按预测类别整理的\n\t# TODO: Change name here\n\tclass_array = ['RecapturedImage', 'SingleCapturedImage']\n\tdst_paths = []\n\tfor cls in class_array: # 此循环只用于清空上一次预测的目录\n\t\tpath = res_path.joinpath(cls)\n\t\tclear_folder(path)\n\t\tdst_paths.append(path)\n\twith open(model_path, 'rb') as f:\n\t\tclf = pkl.load(f) # clf为SVM参数\n\ttest_dataset = prepare_image_feature(test_path)\n\tpreds = clf.predict(test_dataset.lbp_ws_hist_data) # 为test文件夹所有图片的预测类别\n\tprint(preds)\n\tprint(test_dataset.target) # 为test文件夹所有图片的真实类别---[0 0 0 0 0 ... 1 1 1 1 1 ...]\n\tprint(test_dataset.target_names) # ['RecapturedImage', 'SingleCapturedImage']\n\tprint(test_dataset.file_list)\n\tprint(f'Pred: GroundTruth: filepath')\n\tfor pred_label, name, gnd in zip(preds, test_dataset.file_list, test_dataset.target):\n\t\tprint(f'{pred_label}:\\t\\t{gnd}:\\t\\t{name}') # 预测类别 实际类别 文件名\n\t# os.system(f'cp \"{name}\" \"{dst_paths[pred_label]}/\"')\n\tprint(\n\t\tf\"Classification report - \\n{metrics.classification_report(test_dataset.target, preds, target_names=class_array)}\\n\")\n\tprint(\"Confusion matrix -\\n\")\n\tprint(pd.crosstab(pd.Series(test_dataset.target, name='Actual'), pd.Series(preds, name='Predicted')))\n\treturn preds\n\n\ndef parse_args():\n\tparser = argparse.ArgumentParser(\n\t\tdescription='Train a network with Detectron'\n\t)\n\tparser.add_argument(\n\t\t'--testone',\n\t\tdest='test_img_path',\n\t\thelp='image path for test',\n\t\tdefault='',\n\t\ttype=str\n\t)\n\tparser.add_argument(\n\t\t'--testall',\n\t\tdest='test_all',\n\t\thelp='test all images',\n\t\taction='store_true'\n\t)\n\tparser.add_argument(\n\t\t'--retrain',\n\t\tdest='retrain',\n\t\thelp='retrain the model',\n\t\taction='store_true'\n\t)\n\treturn parser.parse_args()\n\n\nif __name__ == '__main__':\n\tdata_path = '/home/lyf/dataset/train'\n\ttest_data_path = '/home/lyf/dataset/test'\n\t# TODO: Change svm model name\n\tmodel_path = './svm_lbp_ws.pkl'\n\t# TODO: Change name here\n\tclass_array = ['RecapturedImage', 'SingleCapturedImage']\n\tretrain = True\n\targs = parse_args()\n\t# noinspection DuplicatedCode\n\tif args.retrain:\n\t\timage_dataset = prepare_image_feature(data_path)\n\t\tX_train, X_val, y_train, y_val = train_test_split(image_dataset.lbp_ws_hist_data, image_dataset.target,\n\t\t test_size=0.3)\n\t\tc_range = np.logspace(-5, 15, 11, base=2)\n\t\tgamma_range = np.logspace(-9, 3, 13, base=2)\n\t\tparam_grid = [{'kernel': ['rbf'], 'C': c_range, 'gamma': gamma_range}]\n\t\tsvc = svm.SVC(kernel='rbf', class_weight='balanced')\n\t\tgrid = GridSearchCV(svc, param_grid, n_jobs=-1, cv=3)\n\t\tclf = grid.fit(X_train, y_train)\n\n\t\twith open(model_path, 'wb') as f:\n\t\t\tpkl.dump(clf, f)\n\t\ty_pred = clf.predict(X_val)\n\t\tprint(\n\t\t\tf\"Classification report - \\n{clf}:\\n{metrics.classification_report(y_val, y_pred, target_names=class_array)}\\n\")\n\t\tprint(\"Confusion matrix -\\n\")\n\t\tprint(pd.crosstab(pd.Series(y_val, name='Actual'), pd.Series(y_pred, name='Predicted')))\n\tif os.path.exists(model_path):\n\t\tif args.test_img_path != '':\n\t\t\t# vis_one(os.path.join(test_data_path, 'RecapturedImages', '7 (1).jpg'), model_path)\n\t\t\tvis_one(args.test_img_path, model_path)\n\n\t\telif args.test_all:\n\t\t\tpreds = test_all(test_data_path, model_path)\n"
]
| [
[
"numpy.concatenate",
"numpy.array",
"sklearn.utils.Bunch",
"sklearn.model_selection.GridSearchCV",
"sklearn.svm.SVC",
"sklearn.metrics.classification_report",
"numpy.arange",
"pandas.Series",
"sklearn.model_selection.train_test_split",
"numpy.logspace"
]
]
|
nmningmei/METASEMA_encoding_model | [
"ce4b9b0935e5a1b04de77174236905f7d8d267f8"
]
| [
"scripts/compare word2vec and image2vec 15_roi voxel wise.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 5 10:49:55 2020\n\n@author: nmei\n\"\"\"\n\n\nimport pandas as pd\nimport numpy as np\nfrom glob import glob\nfrom tqdm import tqdm\nimport os\nfrom scipy import stats\nimport statsmodels.api as sm\nfrom statsmodels.formula.api import ols\nfrom statsmodels.stats.anova import AnovaRM\nfrom matplotlib.ticker import FormatStrFormatter\nfrom matplotlib import pyplot as plt\nfrom mne.stats import fdr_correction\nimport seaborn as sns\nsns.set_style('white')\nsns.set_context('poster')\nimport matplotlib\nfont = {'weight' : 'bold',\n 'size' : 22}\nmatplotlib.rc('font', **font)\nmatplotlib.rcParams['font.weight']= 'bold'\nfrom shutil import copyfile\ncopyfile('../../../utils.py','utils.py')\nimport utils\n\nmodel = 'Image2vec Encoding Models'\nexperiment = 'metasema'\nalpha = int(1e2)\nhere = 'encoding_model_15_ROIs_arrays'\nmodel_name = 'Ridge Regression'\ncv = 'Random Partition 300 folds'\nmultiple_correction_method = 'FDR Benjamini-Hochberg'\nworking_dir = '../../../../results/{}/RP/{}'.format(experiment,here)\n#working_dir = '/bcbl/home/home_n-z/nmei/bench_marking/results/{}/RP/{}'.format(experiment,here)\nhere = 'compare word2vec and image2vec 15 roi'\nfigure_dir = '../../../../figures/{}/RP/{}'.format(experiment,here)\nif not os.path.exists(figure_dir):\n os.makedirs(figure_dir)\n\nworking_data = glob(os.path.join(working_dir,'*.npy'))\ndf_collect = dict(\n sub_name = [],\n roi = [],\n condition = [],\n model_name = [],\n path = [],\n scores = [],\n )\ndef _append(df_collect,mapping):\n for key,values in mapping.items():\n df_collect[key].append(values)\n return df_collect\nfor f in tqdm(working_data):\n try:\n _,_,sub_name,roi,condition,model = f.split(' ')\n model = model.split('.')[0]\n except:\n _,_,sub_name,roi,condition,model1,model2 = f.split(' ')\n model = f'{model1} {model2.split(\".\")[0]}'\n df_collect = _append(df_collect,mapping = dict(\n sub_name=sub_name,\n roi=roi,\n condition=condition,\n model_name=model,\n path=f,\n scores=np.load(f).mean(0)\n ))\ndf_collect = pd.DataFrame(df_collect)\ndf_collect['model_name'] = df_collect['model_name'].map({'fast text':'Fast Text',\n 'glove':'GloVe',\n 'word2vec':'Word2Vec',\n 'concatenated_word2vec':'Word Embedding',\n 'VGG19':'VGG19',\n 'DenseNet169':'DenseNet169',\n 'MobileNetV2':'MobileNetV2'})\ndf_collect['Model'] = df_collect['model_name'].map({'Fast Text':'W2V',\n 'GloVe':'W2V',\n 'Word2Vec':'W2V',\n 'Word Embedding':'W2V',\n 'VGG19':'I2V',\n 'DenseNet169':'I2V',\n 'MobileNetV2':'I2V'})\ndf = dict(\n sub_name = [],\n roi = [],\n condition = [],\n model_type = [],\n scores = [],\n positive_voxels = [],\n )\nfor (sub_name,roi,condition,Model),df_sub in df_collect.groupby(['sub_name',\n 'roi','condition','Model']):\n temp = df_sub['scores'].values.mean(0)\n df = _append(df,\n mapping = dict(sub_name = sub_name,\n roi = roi,\n condition = condition,\n model_type = Model,\n scores = temp,\n positive_voxels = np.sum(temp >=0)))\ndf = pd.DataFrame(df)\n\ndf['roi_name'] = df['roi'].apply(lambda x:x.split('_')[-1])\ndf['roi_name'] = df['roi_name'].map({'frontpole':'Frontal Pole', \n 'fusif':'Fusirorm Gyrus', \n 'infpar':'Inferior Parietal Lobe', \n 'inftemp':'Inferior Temporal Lobe', \n 'lofc':'Lateral Orbitofrontal Cortex', \n 'mofc':'Medial Orbitfrontal Cortex', \n 'mtemp':'Medial Temporal Lobe',\n 'parsoper':'Pars Opercularis', \n 'parsorbi':'Pars Orbitalis', \n 'parstri':'Pars Triangularis', \n 'phipp':'Parahippocampal Gyrus', \n 'postcing':'Posterior Cingulate Gyrus', \n 'precun':'Precuneus',\n 'sfrontal':'Superior Frontal Gyrus', \n 'tempole':'Anterior Temporal Lobe'})\ndf['roi_name_br'] = df['roi_name'].map({'Frontal Pole':'FP', \n 'Fusirorm Gyrus':'FFG', \n 'Inferior Parietal Lobe':'IPL', \n 'Inferior Temporal Lobe':'ITL', \n 'Lateral Orbitofrontal Cortex':'LOFC', \n 'Medial Orbitfrontal Cortex':'MOFC', \n 'Medial Temporal Lobe':'MTL',\n 'Pars Opercularis':'POP', \n 'Pars Orbitalis':'POR', \n 'Pars Triangularis':'PTR', \n 'Parahippocampal Gyrus':'PHG', \n 'Posterior Cingulate Gyrus':'PCG', \n 'Precuneus':'Precuneus',\n 'Superior Frontal Gyrus':'SFG', \n 'Anterior Temporal Lobe':'ATL'})\ndf['ROIs'] = df['roi_name']\ndf['Conditions'] = df['condition']\n\nsort_by = ['sub_name','roi_name','condition']\ndf_i2v = df[df['model_type']=='I2V'].sort_values(sort_by)\ndf_w2v = df[df['model_type']=='W2V'].sort_values(sort_by)\n\nfig,ax = plt.subplots(figsize = (24,20))\nax = sns.scatterplot(df_w2v['positive_voxels'].values,\n df_i2v['positive_voxels'].values,\n hue = df_i2v['ROIs'].values,\n style = df_i2v['Conditions'].values,\n ax = ax,\n )\nax.plot([0,600],[0,600],linestyle = '--',color = 'black',alpha = .4,)\nax.set(xlim=(-10,550),\n ylim=(-10,550),\n xlabel = 'Word embedding models',\n ylabel = 'Computer vision models',\n title = 'Number of Positive Variance Explained Voxels')\nfig.savefig(os.path.join(figure_dir,'positive voxels.jpeg'),\n bbox_inches = 'tight',)\nfig.savefig(os.path.join(figure_dir,'positive voxels (high).jpeg'),\n dpi = 400,\n bbox_inches = 'tight',)\n\ndf_voxel = dict(sub_name=[],\n roi_name=[],\n condition=[],\n score_i=[],\n score_w=[],\n )\nfor ((sub_name,roi_name,condition),df_i2v_sub),(_,df_w2v_sub) in zip(df_i2v.groupby(['sub_name','roi_name','condition',]),\n df_w2v.groupby(['sub_name','roi_name','condition',])):\n for ii,ww in zip(df_i2v_sub['scores'].values[0],df_w2v_sub['scores'].values[0]):\n df_voxel = _append(df_voxel,\n mapping = dict(sub_name=sub_name,\n roi_name=roi_name,\n condition=condition,\n score_i=ii,\n score_w=ww,))\ndf_voxel = pd.DataFrame(df_voxel)\ndf_voxel['ROIs'] = df_voxel['roi_name']\ndf_voxel['Conditions'] = df_voxel['condition']\nidx = np.logical_or(df_voxel['score_i'].apply(lambda x:x>=0).values,\n df_voxel['score_w'].apply(lambda x:x>=0).values)\n\ndf_voxel_plot = df_voxel[idx]\n\nidx = np.logical_or(df_voxel['score_i'].apply(lambda x:-10<x<0).values,\n df_voxel['score_w'].apply(lambda x:-10<x<0).values)\ndf_voxel_negative = df_voxel[idx]\n\nfig,ax = plt.subplots(figsize = (24,20))\nax.scatter(df_voxel_negative['score_w'].values,\n df_voxel_negative['score_i'].values,\n marker = '*',\n s = 1,\n color = 'black',\n alpha = 0.5,\n )\nax = sns.scatterplot('score_w','score_i',\n hue='ROIs',\n style='Conditions',\n data = df_voxel_plot,\n ax = ax,\n )\nax.plot([-600,600],[-600,600],linestyle = '--',color = 'black',alpha = .4,)\nvims = df_voxel['score_i'].max() * 1.1\nax.set(xlim=(-vims,vims),\n ylim=(-vims,vims),\n xlabel = 'Word embedding models',\n ylabel = 'Computer vision models',\n title = 'Variance Explained of Individual Voxels',\n )\nfig.savefig(os.path.join(figure_dir,'voxel wise scores.jpeg'),\n bbox_inches = 'tight',)\nfig.savefig(os.path.join(figure_dir,'voxel wise scores (high).jpeg'),\n dpi = 500,\n bbox_inches = 'tight',)\nplt.close('all')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
]
| [
[
"pandas.DataFrame",
"numpy.sum",
"numpy.load",
"matplotlib.pyplot.close",
"matplotlib.pyplot.subplots",
"matplotlib.rc"
]
]
|
samuelefiorini/vrpy | [
"ad3232b9e9ee9276c9c799d16b4a4a8c2b41eef1"
]
| [
"examples/cvrp_drop.py"
]
| [
"from networkx import from_numpy_matrix, set_node_attributes, relabel_nodes, DiGraph\nfrom numpy import array\n\nfrom examples.data import DISTANCES, DEMANDS_DROP\n\nfrom vrpy import VehicleRoutingProblem\n\n# Transform distance matrix to DiGraph\nA = array(DISTANCES, dtype=[(\"cost\", int)])\nG = from_numpy_matrix(A, create_using=DiGraph())\n\n# Set demands\nset_node_attributes(G, values=DEMANDS_DROP, name=\"demand\")\n\n# Relabel depot\nG = relabel_nodes(G, {0: \"Source\", 17: \"Sink\"})\n\nif __name__ == \"__main__\":\n\n prob = VehicleRoutingProblem(G,\n load_capacity=15,\n drop_penalty=1000,\n num_vehicles=4)\n prob.solve()\n print(prob.best_value)\n print(prob.best_routes)\n print(prob.best_routes_cost)\n print(prob.best_routes_load)\n print(prob.node_load)\n assert prob.best_value == 7548\n"
]
| [
[
"numpy.array"
]
]
|
davidackerman/CNNectome | [
"bde8528ed5adc0a4aefca3b19ecc4c2144f2cbcc"
]
| [
"CNNectome/postprocessing/partner_annotations/slicefilter.py"
]
| [
"import zarr\nimport numcodecs\nimport os\nimport numpy as np\nimport scipy.ndimage\nfrom CNNectome.utils import config_loader\n\nBG_VAL1 = 0xFFFFFFFFFFFFFFFD\nBG_VAL2 = 0\n\n\ndef slicefilter(\n filename_src, dataset_src, filename_tgt, dataset_tgt, thr, dat_file=None\n):\n\n srcf = zarr.open(filename_src, mode=\"r\")\n if not os.path.exists(filename_tgt):\n os.makedirs(filename_tgt)\n tgtf = zarr.open(filename_tgt, mode=\"a\")\n tgtf.empty(\n name=dataset_tgt,\n shape=srcf[dataset_src].shape,\n compressor=numcodecs.GZip(6),\n dtype=\"uint64\",\n chunks=srcf[dataset_src].chunks,\n )\n tgt = np.array(srcf[dataset_src][:])\n\n ids, relabeled = np.unique(tgt, return_inverse=True)\n relabeled = relabeled.reshape(tgt.shape) + 1\n if BG_VAL1 in ids:\n relabeled[tgt == BG_VAL1] = 0\n if BG_VAL2 in ids:\n relabeled[tgt == BG_VAL2] = 0\n\n obj_slices = scipy.ndimage.measurements.find_objects(relabeled)\n set_to_bg = []\n for k, obs in enumerate(obj_slices):\n if not None:\n if relabeled[obs].shape[0] <= thr:\n set_to_bg.append(k + 1)\n\n tgt[np.isin(relabeled, set_to_bg)] = 0\n tgtf[dataset_tgt][:] = tgt.astype(np.uint64)\n tgtf[dataset_tgt].attrs[\"offset\"] = srcf[dataset_src].attrs[\"offset\"]\n\n\ndef main():\n thrs = [127, 63, 63]\n samples = [\"A+\", \"B+\", \"C+\"]\n # samples = ['B+', 'C+']\n slf = 1\n offsets = {\n \"A+\": (37 * 40, 1176 * 4, 955 * 4),\n \"B+\": (37 * 40, 1076 * 4, 1284 * 4),\n \"C+\": (37 * 40, 1002 * 4, 1165 * 4),\n \"A\": (38 * 40, 942 * 4, 951 * 4),\n \"B\": (37 * 40, 1165 * 4, 1446 * 4),\n \"C\": (37 * 40, 1032 * 4, 1045 * 4),\n }\n\n # segf_name = {'A+': 'sample_A+_85_aff_0.8_cf_hq_dq_dm1_mf0.81',\n # 'B+': 'sample_B+_median_aff_0.8_cf_hq_dq_dm1_mf0.87',\n # 'C+': 'sample_C+_85_aff_0.8_cf_hq_dq_dm1_mf0.75',\n # }\n\n # filename_src = '/nrs/saalfeld/heinrichl/synapses/pre_and_post/{0:}.n5'\n # dataset_src = 'main'\n # filename_tgt = '/nrs/saalfeld/heinrichl/synapses/pre_and_post/{0:}_sizefiltered750.n5'\n # dataset_tgt = 'main'\n # dat_file = '/nrs/saalfeld/heinrichl/synapses/pre_and_post/pre_and_post-v3.0/cremi/{0:}_sizefilter750.dat'\n\n # filename_src = '/groups/saalfeld/home/papec/Work/neurodata_hdd/cremi_warped/sample{0}.n5'\n # dataset_src = 'segmentations/multicut'\n # dataset_src = 'segmentations/mc_glia_global2'\n\n # filename_src = '/groups/saalfeld/saalfeldlab/larissa/data/cremi-2017/sample_{0:}_padded_20170424.aligned.0bg.n5'\n # dataset_src = 'volumes/labels/neuron_ids'\n\n # filename_src = '/groups/saalfeld/home/papec/Work/neurodata_hdd/cremi_new/sample{0:}.n5'\n # dataset_src = 'segmentation/multicut'\n # filename_tgt = '/nrs/saalfeld/heinrichl/synapses/pre_and_post/cremi/{0}.n5'\n filename = os.path.join(config_loader.get_config()[\"synapses\"][\"cremieval_path\"],\"data2016-aligned/{0:}.n5\")\n dataset_src = \"volumes/labels/neuron_ids_constis_cropped\"\n dataset_tgt = \"volumes/labels/neuron_ids_constis_slf{0:}_cropped\"\n # dat_file = '/nrs/saalfeld/heinrichl/synapses/pre_and_post/pre_and_post-v3.0/cremi/{0:}_constis_slicefilter{' \\\n # '1:}.dat'\n for sample in samples:\n print(sample)\n slicefilter(\n filename.format(sample),\n dataset_src,\n filename.format(sample),\n dataset_tgt.format(slf),\n slf,\n ) # , dat_file.format(sample, slf))\n\n\nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"numpy.array",
"numpy.unique",
"numpy.isin"
]
]
|
JochenHinz/nutils | [
"ac18dd6825b107e2e4c186ebb1598dbf0fff0f77"
]
| [
"tests/test_topology.py"
]
| [
"from nutils import *\nfrom nutils.testing import *\nimport numpy, copy, sys, pickle, subprocess, base64, itertools, os\n\ngrid = numpy.linspace(0., 1., 4)\n\ndef verify_connectivity(structure, geom):\n (e00,e01), (e10,e11) = structure\n\n a0 = geom.eval(_transforms=[e00.transform], _points=numpy.array([[0,1]]))\n a1 = geom.eval(_transforms=[e01.transform], _points=numpy.array([[0,0]]))\n numpy.testing.assert_array_almost_equal(a0, a1)\n\n b0 = geom.eval(_transforms=[e10.transform], _points=numpy.array([[1,1]]))\n b1 = geom.eval(_transforms=[e11.transform], _points=numpy.array([[1,0]]))\n numpy.testing.assert_array_almost_equal(b0, b1)\n\n c0 = geom.eval(_transforms=[e00.transform], _points=numpy.array([[1,0]]))\n c1 = geom.eval(_transforms=[e10.transform], _points=numpy.array([[0,0]]))\n numpy.testing.assert_array_almost_equal(c0, c1)\n\n d0 = geom.eval(_transforms=[e01.transform], _points=numpy.array([[1,1]]))\n d1 = geom.eval(_transforms=[e11.transform], _points=numpy.array([[0,1]]))\n numpy.testing.assert_array_almost_equal(d0, d1)\n\n x00 = geom.eval(_transforms=[e00.transform], _points=numpy.array([[1,1]]))\n x01 = geom.eval(_transforms=[e01.transform], _points=numpy.array([[1,0]]))\n x10 = geom.eval(_transforms=[e10.transform], _points=numpy.array([[0,1]]))\n x11 = geom.eval(_transforms=[e11.transform], _points=numpy.array([[0,0]]))\n numpy.testing.assert_array_almost_equal(x00, x01)\n numpy.testing.assert_array_almost_equal(x10, x11)\n numpy.testing.assert_array_almost_equal(x00, x11)\n\ndef verify_boundaries(domain, geom):\n # Test ∫_Ω f_,i = ∫_∂Ω f n_i.\n f = ((0.5 - geom)**2).sum(axis=0)\n lhs = domain.integrate(f.grad(geom)*function.J(geom), ischeme='gauss2')\n rhs = domain.boundary.integrate(f*function.normal(geom)*function.J(geom), ischeme='gauss2')\n numpy.testing.assert_array_almost_equal(lhs, rhs)\n\ndef verify_interfaces(domain, geom, periodic, interfaces=None, elemindicator=None):\n # If `periodic` is true, the domain should be a unit hypercube or this test\n # might fail. The function `f` defined below is C0 continuous on a periodic\n # hypercube and Cinf continuous inside the hypercube.\n if interfaces is None:\n interfaces = domain.interfaces\n x1, x2, n1, n2 = interfaces.sample('gauss', 2).eval([geom, function.opposite(geom), geom.normal(), function.opposite(geom.normal())])\n if not periodic:\n numpy.testing.assert_array_almost_equal(x1, x2)\n numpy.testing.assert_array_almost_equal(n1, -n2)\n\n # Test ∫_E f_,i = ∫_∂E f n_i ∀ E in `domain`.\n f = ((0.5 - geom)**2).sum(axis=0)\n if elemindicator is None:\n elemindicator = domain.basis('discont', degree=0)\n elemindicator = elemindicator.vector(domain.ndims)\n lhs = domain.integrate((elemindicator*f.grad(geom)[None]).sum(axis=1)*function.J(geom), ischeme='gauss2')\n rhs = interfaces.integrate((-function.jump(elemindicator)*f*function.normal(geom)[None]).sum(axis=1)*function.J(geom), ischeme='gauss2')\n if len(domain.boundary):\n rhs += domain.boundary.integrate((elemindicator*f*function.normal(geom)[None]).sum(axis=1)*function.J(geom), ischeme='gauss2')\n numpy.testing.assert_array_almost_equal(lhs, rhs)\n\n\n@parametrize\nclass elem_project(TestCase):\n\n def test_extraction(self):\n topo, geom = mesh.rectilinear([numpy.linspace(-1,1,4)]*self.ndims)\n\n splinebasis = topo.basis('spline', degree=self.degree)\n bezierbasis = topo.basis('spline', degree=self.degree, knotmultiplicities=[numpy.array([self.degree+1]+[self.degree]*(n-1)+[self.degree+1]) for n in topo.shape])\n\n sample = topo.sample('uniform', 2)\n splinevals, beziervals = sample.eval([splinebasis,bezierbasis])\n sextraction = topo.elem_project(splinebasis, degree=self.degree, check_exact=True)\n bextraction = topo.elem_project(bezierbasis, degree=self.degree, check_exact=True)\n self.assertEqual(len(sample.index), len(sextraction))\n self.assertEqual(len(sample.index), len(bextraction))\n for index, (sien,sext), (bien,bext) in zip(sample.index,sextraction,bextraction):\n svals, bvals = splinevals[index], beziervals[index]\n sien, bien = sien[0][0], bien[0][0]\n self.assertEqual(len(sien), len(bien))\n self.assertEqual(len(sien), sext.shape[0])\n self.assertEqual(len(sien), sext.shape[1])\n self.assertEqual(len(sien), bext.shape[0])\n self.assertEqual(len(sien), bext.shape[1])\n self.assertEqual(len(sien), (self.degree+1)**self.ndims)\n numpy.testing.assert_array_almost_equal(bext, numpy.eye((self.degree+1)**self.ndims))\n numpy.testing.assert_array_almost_equal(svals[:,sien], bvals[:,bien].dot(sext))\n\nfor ndims in range(1, 4):\n for degree in [2] if ndims == 3 else range(1, 4):\n elem_project(ndims=ndims, degree=degree)\n\n\nclass structure2d(TestCase):\n\n def test_domain(self):\n domain, geom = mesh.rectilinear([[-1,0,1]]*2)\n verify_connectivity(domain.structure, geom)\n\n def test_boundaries(self):\n domain, geom = mesh.rectilinear([[-1,0,1]]*3)\n for grp in 'left', 'right', 'top', 'bottom', 'front', 'back':\n bnd = domain.boundary[grp]\n # DISABLED: what does this check? -GJ 14/07/28\n #verify_connectivity(bnd.structure, geom)\n xn = bnd.sample('gauss', 1).eval(geom.dotnorm(geom))\n numpy.testing.assert_array_less(0, xn, 'inward pointing normals')\n\n def test_interfaces(self):\n domain, geom = mesh.rectilinear([[-1,0,1]]*3)\n verify_interfaces(domain, geom, periodic=False)\n\n\n@parametrize\nclass structured_prop_periodic(TestCase):\n\n def test(self):\n bnames = 'left', 'top', 'front'\n side = bnames[self.sdim]\n domain, geom = mesh.rectilinear([2]*self.ndim, periodic=self.periodic)\n self.assertEqual(list(domain.boundary[side].periodic), [i if i < self.sdim else i-1 for i in self.periodic if i != self.sdim])\n\nstructured_prop_periodic('2d_1_0', ndim=2, periodic=[1], sdim=0)\nstructured_prop_periodic('2d_0_1', ndim=2, periodic=[0], sdim=1)\nstructured_prop_periodic('3d_0,2_1', ndim=3, periodic=[0,2], sdim=1)\n\n\nclass picklability(TestCase):\n\n def assert_pickle_dump_load(self, data):\n script = b'from nutils import *\\nimport pickle, base64\\npickle.loads(base64.decodebytes(b\"\"\"' \\\n + base64.encodebytes(pickle.dumps(data)) \\\n + b'\"\"\"))'\n p = subprocess.Popen([sys.executable], stdin=subprocess.PIPE)\n p.communicate(script)\n self.assertEqual(p.wait(), 0, 'unpickling failed')\n\n def test_domain(self):\n domain, geom = mesh.rectilinear([[0,1,2]]*2)\n self.assert_pickle_dump_load(domain)\n\n def test_geom(self):\n domain, geom = mesh.rectilinear([[0,1,2]]*2)\n self.assert_pickle_dump_load(geom)\n\n def test_basis(self):\n domain, geom = mesh.rectilinear([[0,1,2]]*2)\n basis = domain.basis('spline', degree=2)\n self.assert_pickle_dump_load(basis)\n\n\nclass common_refine(TestCase):\n\n def test(self):\n dom, geom = mesh.rectilinear([[0,1,2],[0,1,2]])\n doms, funs, vals = {}, {}, {}\n\n doms['1'] = dom.refined_by(list(dom)[:1])\n funs['1'] = doms['1'].basis('th-std', degree=1)\n vals['1'] = 0.375,0.25,0.375,0.9375,0.5,0.25,0.5,0.25,0.0625,0.125,0.125,0.25\n\n doms['234'] = dom.refined_by(list(dom)[1:])\n funs['234'] = doms['234'].basis('th-std', degree=1)\n vals['234'] = 0.25,0.375,0.375,0.5625,0.125,0.0625,0.25,0.125,0.25,0.125,0.125,0.25,0.25,0.25,0.125,0.0625,0.125,0.125,0.125,0.0625\n\n doms['123'] = dom.refined_by(list(dom)[:-1])\n funs['123'] = doms['123'].basis('th-std', degree=1)\n vals['123'] = 0.5625,0.375,0.375,0.25,0.0625,0.125,0.125,0.125,0.0625,0.125,0.25,0.25,0.25,0.125,0.125,0.25,0.125,0.25,0.0625,0.125\n\n doms['4'] = dom.refined_by(list(dom)[-1:])\n funs['4'] = doms['4'].basis('th-std', degree=1)\n vals['4'] = 0.25,0.5,0.25,0.5,0.9375,0.375,0.25,0.375,0.25,0.125,0.125,0.0625\n\n for a, b, n in ('1', '234', 16), ('1', '4', 10), ('123', '234', 16):\n with self.subTest('ref{}vs{}'.format(a, b)):\n common = doms[a] & doms[b]\n self.assertEqual(len(common), n)\n for c in a, b:\n testvals = common.integrate(funs[c]*function.J(geom), ischeme='gauss1')\n numpy.testing.assert_array_almost_equal(testvals, vals[c])\n\n@parametrize\nclass revolved(TestCase):\n\n def setUp(self):\n super().setUp()\n if self.domtype == 'circle':\n self.domain0, self.geom0 = mesh.rectilinear([2])\n self.exact_volume = 4 * numpy.pi\n self.exact_surface = 4 * numpy.pi\n self.exact_groups = {}\n elif self.domtype == 'cylinder':\n self.domain0, self.geom0 = mesh.rectilinear([1,2])\n self.exact_volume = 2 * numpy.pi\n self.exact_surface = 6 * numpy.pi\n self.exact_groups = dict(right=4*numpy.pi, left=0)\n elif self.domtype == 'hollowcylinder':\n self.domain0, self.geom0 = mesh.rectilinear([[.5,1],2])\n self.exact_volume = 1.5 * numpy.pi\n self.exact_surface = 7.5 * numpy.pi\n self.exact_groups = dict(right=4*numpy.pi, left=2*numpy.pi)\n else:\n raise Exception('unknown domain type {!r}'.format(self.domtype))\n self.domain, self.geom, self.simplify = self.domain0.revolved(self.geom0)\n if self.refined:\n self.domain = self.domain.refined\n self.domain0 = self.domain0.refined\n\n def test_revolved(self):\n self.assertEqual(len(self.domain), len(self.domain0))\n\n def test_volume(self):\n vol = self.domain.integrate(function.J(self.geom), ischeme='gauss1')\n numpy.testing.assert_array_almost_equal(vol, self.exact_volume)\n\n def test_volume_bydiv(self):\n boundary = self.domain.boundary\n if self.domtype != 'hollowcylinder':\n boundary = boundary['bottom,right,top']\n v = boundary.integrate(self.geom.dotnorm(self.geom)*function.J(self.geom), ischeme='gauss1') / self.domain.ndims\n numpy.testing.assert_array_almost_equal(v, self.exact_volume)\n\n def test_surface(self):\n surf = self.domain.boundary.integrate(function.J(self.geom), ischeme='gauss1')\n numpy.testing.assert_array_almost_equal(surf, self.exact_surface)\n\n def test_surface_groups(self):\n for name, exact_surface in self.exact_groups.items():\n surf = self.domain.boundary[name].integrate(function.J(self.geom), ischeme='gauss1')\n numpy.testing.assert_array_almost_equal(surf, exact_surface)\n\n def test_basis(self):\n basis = self.domain.basis('std', degree=1)\n values = self.domain.sample('uniform', 2).eval(basis).sum(1)\n numpy.testing.assert_array_almost_equal(values, 1)\n\n def test_trim(self):\n r = function.norm2(self.geom[:2])\n trimmed = self.domain.trim(r - .75, maxrefine=1)\n volume = trimmed.integrate(function.J(self.geom), degree=1)\n self.assertGreater(volume, 0)\n self.assertLess(volume, self.exact_volume)\n\nfor domtype in 'circle', 'cylinder', 'hollowcylinder':\n for refined in False, True:\n revolved(domtype=domtype, refined=refined)\n\n\n_refined_refs = dict(\n line=element.LineReference(),\n quadrilateral=element.LineReference()**2,\n hexahedron=element.LineReference()**3,\n triangle=element.TriangleReference(),\n tetrahedron=element.TetrahedronReference())\n\n@parametrize\nclass refined(TestCase):\n\n def test_boundary_gradient(self):\n ref = _refined_refs[self.etype]\n elem = element.Element(ref, (transform.Identifier(ref.ndims),))\n domain = topology.ConnectedTopology(ref.ndims, (elem,), ((-1,)*ref.nedges,)).refine(self.ref0)\n geom = function.rootcoords(ref.ndims)\n basis = domain.basis('std', degree=1)\n u = domain.projection(geom.sum(), onto=basis, geometry=geom, degree=2)\n bpoints = domain.refine(self.ref1).boundary.refine(self.ref2).sample('uniform', 1)\n g = bpoints.eval(u.grad(geom))\n numpy.testing.assert_allclose(g, 1)\n\nfor etype in _refined_refs:\n for ref0 in 0, 1:\n for ref1 in 0, 1:\n for ref2 in 0, 1:\n refined(etype=etype, ref0=ref0, ref1=ref1, ref2=ref2)\n\n\n@parametrize\nclass general(TestCase):\n\n def setUp(self):\n super().setUp()\n self.domain, self.geom = mesh.rectilinear([3,4,5], periodic=[] if self.periodic is False else [self.periodic])\n if not self.isstructured:\n self.domain = topology.ConnectedTopology(self.domain.ndims, self.domain.elements, self.domain.connectivity)\n\n def test_connectivity(self):\n nboundaries = 0\n ninterfaces = 0\n for ielem, ioppelems in enumerate(self.domain.connectivity):\n for iedge, ioppelem in enumerate(ioppelems):\n if ioppelem == -1:\n nboundaries += 1\n else:\n ioppedge = tuple(self.domain.connectivity[ioppelem]).index(ielem)\n edge = self.domain.elements[ielem].edge(iedge)\n oppedge = self.domain.elements[ioppelem].edge(ioppedge)\n self.assertEqual(edge.reference, oppedge.reference)\n ninterfaces += .5\n self.assertEqual(nboundaries, len(self.domain.boundary), 'incompatible number of boundaries')\n self.assertEqual(ninterfaces, len(self.domain.interfaces), 'incompatible number of interfaces')\n\n def test_boundary(self):\n for elem in self.domain.boundary:\n ielem, tail = transform.lookup_item(elem.transform, self.domain.edict)\n etrans, = tail\n iedge = self.domain.elements[ielem].reference.edge_transforms.index(etrans)\n self.assertEqual(self.domain.connectivity[ielem][iedge], -1)\n\n def test_interfaces(self):\n for elem in self.domain.interfaces:\n ielem, tail = transform.lookup_item(elem.transform, self.domain.edict)\n etrans, = tail\n iedge = self.domain.elements[ielem].reference.edge_transforms.index(etrans)\n ioppelem, opptail = transform.lookup_item(elem.opposite, self.domain.edict)\n eopptrans, = opptail\n ioppedge = self.domain.elements[ioppelem].reference.edge_transforms.index(eopptrans)\n self.assertEqual(self.domain.connectivity[ielem][iedge], ioppelem)\n self.assertEqual(self.domain.connectivity[ioppelem][ioppedge], ielem)\n\nfor isstructured in True, False:\n for periodic in False, 0, 1, 2:\n general(isstructured=isstructured, periodic=periodic)\n\n\n@parametrize\nclass locate(TestCase):\n\n @parametrize.skip_if(lambda nprocs, **kwargs: nprocs > 1 and not hasattr(os, 'fork'), 'nprocs > 1 not supported on this platform')\n def test(self):\n with config(nprocs=self.nprocs):\n domain, geom = mesh.unitsquare(4, etype=self.etype)\n geom += .1 * function.sin(geom * numpy.pi) # non-polynomial geometry\n target = numpy.array([(.2,.3), (.1,.9), (0,1)])\n sample = domain.locate(geom, target, eps=1e-15)\n located = sample.eval(geom)\n numpy.testing.assert_array_almost_equal(located, target)\n\nfor etype in 'square', 'triangle', 'mixed':\n for nprocs in 1, 2:\n locate(etype=etype, nprocs=nprocs)\n\n\n@parametrize\nclass hierarchical(TestCase):\n\n def setUp(self):\n super().setUp()\n self.domain, self.geom = mesh.rectilinear([numpy.linspace(0, 1, 7)]*self.ndims, periodic=self.periodic)\n # Refine `self.domain` near `self.pos`.\n distance = ((self.geom-self.pos)**2).sum(0)**0.5\n for threshold in 0.3, 0.15:\n self.domain = self.domain.refined_by(elem for elem, value in zip(self.domain, self.domain.elem_mean([distance], ischeme='gauss1', geometry=self.geom)[0]) if value <= threshold)\n\n @parametrize.enable_if(lambda periodic, **params: not periodic)\n def test_boundaries(self):\n verify_boundaries(self.domain, self.geom)\n\n def test_interfaces(self):\n verify_interfaces(self.domain, self.geom, self.periodic)\n\nhierarchical('3d_l_rrr', pos=0, ndims=3, periodic=[])\nhierarchical('3d_l_rpr', pos=0, ndims=3, periodic=[1])\nhierarchical('2d_l_pp', pos=0, ndims=2, periodic=[0,1])\nhierarchical('2d_l_pr', pos=0, ndims=2, periodic=[0])\nhierarchical('2d_c_pr', pos=0.5, ndims=2, periodic=[0])\nhierarchical('2d_r_pr', pos=1, ndims=2, periodic=[0])\nhierarchical('2d_l_rr', pos=0, ndims=2, periodic=[])\nhierarchical('1d_l_p', pos=0, ndims=1, periodic=[0])\nhierarchical('1d_c_p', pos=0.5, ndims=1, periodic=[0])\n#hierarchical('1d_l_r', pos=0, ndims=1, periodic=[]) # disabled, see issue #193\n\n\n@parametrize\nclass multipatch_hyperrect(TestCase):\n\n def setUp(self):\n super().setUp()\n npatches = numpy.array(self.npatches)\n indices = numpy.arange((npatches+1).prod()).reshape(npatches+1)\n\n self.domain, self.geom = mesh.multipatch(\n patches=[indices[tuple(map(slice, i, numpy.array(i)+2))].ravel().tolist() for i in itertools.product(*map(range, npatches))],\n patchverts=tuple(itertools.product(*map(range, npatches+1))),\n nelems=4,\n )\n\n def test_spline_basis(self):\n basis = self.domain.basis('spline', degree=2)\n coeffs = self.domain.sample('gauss', 4).eval(basis.sum(0))\n numpy.testing.assert_array_almost_equal(coeffs, numpy.ones(coeffs.shape))\n\n def test_discont_basis(self):\n basis = self.domain.basis('discont', degree=2)\n coeffs = self.domain.sample('gauss', 4).eval(basis.sum(0))\n numpy.testing.assert_array_almost_equal(coeffs, numpy.ones(coeffs.shape))\n\n def test_boundaries(self):\n verify_boundaries(self.domain, self.geom)\n\n def test_interfaces(self):\n verify_interfaces(self.domain, self.geom, periodic=False)\n\n def test_interpatch_interfaces(self):\n verify_interfaces(self.domain, self.geom, periodic=False, interfaces=self.domain.interfaces['interpatch'], elemindicator=self.domain.basis('patch'))\n\nmultipatch_hyperrect('3', npatches=(3,))\nmultipatch_hyperrect('2x2', npatches=(2,2))\nmultipatch_hyperrect('3x3', npatches=(3,3))\nmultipatch_hyperrect('2x2x3', npatches=(2,2,3))\n\n\nclass multipatch_L(TestCase):\n\n def setUp(self):\n # 2---5\n # | |\n # 1---4------7\n # | | |\n # 0---3------6\n\n super().setUp()\n self.domain, self.geom = mesh.multipatch(\n patches=[[0,1,3,4], [1,2,4,5], [3,4,6,7]],\n patchverts=[[0,0], [0,1], [0,2], [1,0], [1,1], [1,2], [3,0], [3,1]],\n nelems={None: 4, (3,6): 8, (4,7): 8})\n\n def test_spline_basis(self):\n for continuity in (-1, 0):\n basis = self.domain.basis('spline', degree=2, continuity=continuity)\n with self.subTest('partition of unity', continuity=continuity):\n sample = self.domain.sample('bezier', 5)\n coeffs = sample.eval(basis.sum(0))\n numpy.testing.assert_array_almost_equal(coeffs, numpy.ones(coeffs.shape))\n with self.subTest('interpatch continuity', continuity=continuity):\n sample = self.domain.interfaces['interpatch'].sample('bezier', 5)\n jump = sample.eval(function.jump(basis))\n numpy.testing.assert_array_almost_equal(jump, numpy.zeros_like(jump))\n\n def test_nonuniform_spline_basis(self):\n knots_01 = 0, 0.25, 0.5, 0.75, 1\n mults_01 = 3, 1, 2, 1, 3\n knots_12 = 0, 0.2, 0.4, 0.6, 1\n knotvalues = {None: None, (1,2): knots_12, (5,4): knots_12[::-1], (0,1): knots_01, (3,4): knots_01, (6,7): knots_01}\n knotmultiplicities = {None: None, (0,1): mults_01, (4,3): mults_01[::-1], (6,7): mults_01}\n basis = self.domain.basis('spline', degree=2, knotvalues=knotvalues, knotmultiplicities=knotmultiplicities)\n coeffs = self.domain.project(1, onto=basis, geometry=self.geom, ischeme='gauss4')\n numpy.testing.assert_array_almost_equal(coeffs, numpy.ones(coeffs.shape))\n\n def test_discont_basis(self):\n basis = self.domain.basis('discont', degree=2)\n with self.subTest('partition of unity'):\n sample = self.domain.sample('bezier', 5)\n coeffs = sample.eval(basis.sum(0))\n numpy.testing.assert_array_almost_equal(coeffs, numpy.ones(coeffs.shape))\n\n def test_patch_basis(self):\n patch_index = self.domain.basis('patch').dot([0, 1, 2])\n for ipatch in range(3):\n with self.subTest(ipatch=ipatch):\n sample = self.domain['patch{}'.format(ipatch)].sample('gauss', 1)\n numpy.testing.assert_array_almost_equal(sample.eval(patch_index), ipatch)\n\n def test_connectivity(self):\n interfaces1 = self.domain.interfaces\n interfaces2 = topology.ConnectedTopology(self.domain.ndims, self.domain.elements, self.domain.connectivity).interfaces\n self.assertEqual(len(interfaces1), len(interfaces2))\n for iface1 in interfaces1:\n try:\n iface2 = interfaces2.elements[interfaces2.edict[iface1.transform]]\n except KeyError:\n iface2 = interfaces2.elements[interfaces2.edict[iface1.opposite]].flipped\n self.assertEqual(iface1, iface2)\n"
]
| [
[
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.zeros_like",
"numpy.ones",
"numpy.eye",
"numpy.testing.assert_array_almost_equal",
"numpy.testing.assert_array_less",
"numpy.linspace"
]
]
|
lmenou/py-pde | [
"3899cba0481657ea7b3d5c05e318d0b851bbe8cd"
]
| [
"pde/grids/boundaries/tests/test_axes_boundaries.py"
]
| [
"\"\"\"\n.. codeauthor:: David Zwicker <[email protected]>\n\"\"\"\n\nimport itertools\n\nimport numpy as np\nimport pytest\n\nfrom pde import ScalarField, UnitGrid\nfrom pde.grids.boundaries.axes import Boundaries\nfrom pde.grids.boundaries.axis import BoundaryPair, BoundaryPeriodic, get_boundary_axis\n\n\ndef test_boundaries():\n \"\"\"test setting boundaries for multiple systems\"\"\"\n b = [\"periodic\", \"value\", {\"type\": \"derivative\", \"value\": 1}]\n for bx, by in itertools.product(b, b):\n g = UnitGrid([2, 2], periodic=[b == \"periodic\" for b in (bx, by)])\n\n bcs = Boundaries.from_data(g, [bx, by])\n bc_x = get_boundary_axis(g, 0, bx)\n bc_y = get_boundary_axis(g, 1, by)\n\n assert bcs.grid.num_axes == 2\n assert bcs[0] == bc_x\n assert bcs[1] == bc_y\n assert bcs == Boundaries.from_data(g, [bc_x, bc_y])\n if bx == by:\n assert bcs == Boundaries.from_data(g, bx)\n\n bc2 = bcs.copy()\n assert bcs == bc2\n assert bcs is not bc2\n\n b1 = Boundaries.from_data(UnitGrid([2, 2]), \"auto_periodic_neumann\")\n b2 = Boundaries.from_data(UnitGrid([3, 3]), \"auto_periodic_neumann\")\n assert b1 != b2\n\n\ndef test_boundary_specifications():\n \"\"\"test different ways of specifying boundary conditions\"\"\"\n g = UnitGrid([2])\n bc1 = Boundaries.from_data(\n g, [{\"type\": \"derivative\", \"value\": 0}, {\"type\": \"value\", \"value\": 0}]\n )\n assert bc1 == Boundaries.from_data(g, [{\"type\": \"derivative\"}, {\"type\": \"value\"}])\n assert bc1 == Boundaries.from_data(g, [{\"derivative\": 0}, {\"value\": 0}])\n assert bc1 == Boundaries.from_data(g, [\"neumann\", \"dirichlet\"])\n\n\ndef test_mixed_boundary_condition():\n \"\"\"test limiting cases of the mixed boundary condition\"\"\"\n g = UnitGrid([2])\n d = np.random.random(2)\n g1 = g.make_operator(\"gradient\", bc=[{\"mixed\": 0}, {\"mixed\": np.inf}])\n g2 = g.make_operator(\"gradient\", bc=[\"derivative\", \"value\"])\n np.testing.assert_allclose(g1(d), g2(d))\n\n\[email protected](\n \"cond,is_value\",\n [\n (\"auto_periodic_neumann\", False),\n (\"auto_periodic_neumann\", False),\n (\"auto_periodic_dirichlet\", True),\n ],\n)\ndef test_natural_boundary_conditions(cond, is_value):\n \"\"\"test special automatic boundary conditions\"\"\"\n g = UnitGrid([2, 2], periodic=[True, False])\n for bc in [\n Boundaries.from_data(g, cond),\n Boundaries.from_data(g, [\"periodic\", cond]),\n ]:\n assert isinstance(bc[0], BoundaryPeriodic)\n if is_value:\n assert bc[1] == BoundaryPair.from_data(g, 1, \"value\")\n else:\n assert bc[1] == BoundaryPair.from_data(g, 1, \"derivative\")\n\n\ndef test_special_cases():\n \"\"\"test some special boundary conditions\"\"\"\n g = UnitGrid([5])\n s = ScalarField(g, np.arange(5))\n for bc in [\"extrapolate\", {\"curvature\": 0}]:\n np.testing.assert_allclose(s.laplace(bc).data, 0)\n\n\ndef test_bc_values():\n \"\"\"test setting the values of boundary conditions\"\"\"\n g = UnitGrid([5])\n bc = g.get_boundary_conditions([{\"value\": 2}, {\"derivative\": 3}])\n assert bc[0].low.value == 2 and bc[0].high.value == 3\n\n\[email protected](\"dim\", [1, 2, 3])\[email protected](\"periodic\", [True, False])\ndef test_set_ghost_cells(dim, periodic):\n \"\"\"test setting values for ghost cells\"\"\"\n grid = UnitGrid([1] * dim, periodic=periodic)\n field = ScalarField.random_uniform(grid)\n bcs = grid.get_boundary_conditions(\"auto_periodic_neumann\")\n\n arr1 = field._data_full.copy()\n bcs.set_ghost_cells(arr1)\n\n arr2 = field._data_full.copy()\n setter = bcs.make_ghost_cell_setter()\n setter(arr2)\n\n # test valid BCs:\n for n in range(dim):\n idx = [slice(1, -1)] * dim\n idx[n] = slice(None)\n np.testing.assert_allclose(arr1[tuple(idx)], arr2[tuple(idx)])\n"
]
| [
[
"numpy.random.random",
"numpy.arange"
]
]
|
tachyonicClock/avalanche | [
"6c3b84b4b9e3123c838092433f29590d955bfdf2"
]
| [
"avalanche/training/strategies/base_strategy.py"
]
| [
"################################################################################\n# Copyright (c) 2021 ContinualAI. #\n# Copyrights licensed under the MIT License. #\n# See the accompanying LICENSE file for terms. #\n# #\n# Date: 01-12-2020 #\n# Author(s): Antonio Carta #\n# E-mail: [email protected] #\n# Website: avalanche.continualai.org #\n################################################################################\nimport logging\nimport warnings\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom typing import Optional, Sequence, Union, List\n\nfrom torch.nn import Module, CrossEntropyLoss\nfrom torch.optim import Optimizer\n\nfrom avalanche.benchmarks.scenarios import Experience\nfrom avalanche.benchmarks.utils.data_loader import TaskBalancedDataLoader\nfrom avalanche.models import DynamicModule\nfrom avalanche.models.dynamic_optimizers import reset_optimizer\nfrom avalanche.models.utils import avalanche_forward\nfrom avalanche.training.plugins.clock import Clock\nfrom avalanche.training.plugins.evaluation import default_logger\nfrom typing import TYPE_CHECKING\n\nfrom avalanche.training.plugins import EvaluationPlugin\n\nif TYPE_CHECKING:\n from avalanche.core import StrategyCallbacks\n from avalanche.training.plugins import StrategyPlugin\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass BaseStrategy:\n DISABLED_CALLBACKS: Sequence[str] = ()\n\n def __init__(self, model: Module, optimizer: Optimizer,\n criterion=CrossEntropyLoss(),\n train_mb_size: int = 1, train_epochs: int = 1,\n eval_mb_size: int = 1, device='cpu',\n plugins: Optional[Sequence['StrategyPlugin']] = None,\n evaluator=default_logger, eval_every=-1):\n \"\"\"\n BaseStrategy is the super class of all task-based continual learning\n strategies. It implements a basic training loop and callback system\n that allows to execute code at each experience of the training loop.\n Plugins can be used to implement callbacks to augment the training\n loop with additional behavior (e.g. a memory buffer for replay).\n\n **Scenarios**\n This strategy supports several continual learning scenarios:\n\n * class-incremental scenarios (no task labels)\n * multi-task scenarios, where task labels are provided)\n * multi-incremental scenarios, where the same task may be revisited\n\n The exact scenario depends on the data stream and whether it provides\n the task labels.\n\n **Training loop**\n The training loop is organized as follows::\n train\n train_exp # for each experience\n adapt_train_dataset\n train_dataset_adaptation\n make_train_dataloader\n train_epoch # for each epoch\n # forward\n # backward\n # model update\n\n **Evaluation loop**\n The evaluation loop is organized as follows::\n eval\n eval_exp # for each experience\n adapt_eval_dataset\n eval_dataset_adaptation\n make_eval_dataloader\n eval_epoch # for each epoch\n # forward\n # backward\n # model update\n\n :param model: PyTorch model.\n :param optimizer: PyTorch optimizer.\n :param criterion: loss function.\n :param train_mb_size: mini-batch size for training.\n :param train_epochs: number of training epochs.\n :param eval_mb_size: mini-batch size for eval.\n :param device: PyTorch device where the model will be allocated.\n :param plugins: (optional) list of StrategyPlugins.\n :param evaluator: (optional) instance of EvaluationPlugin for logging\n and metric computations. None to remove logging.\n :param eval_every: the frequency of the calls to `eval` inside the\n training loop.\n if -1: no evaluation during training.\n if 0: calls `eval` after the final epoch of each training\n experience and before training on the first experience.\n if >0: calls `eval` every `eval_every` epochs, at the end\n of all the epochs for a single experience and before\n training on the first experience.\n \"\"\"\n self._criterion = criterion\n\n self.model: Module = model\n \"\"\" PyTorch model. \"\"\"\n\n self.optimizer = optimizer\n \"\"\" PyTorch optimizer. \"\"\"\n\n self.train_epochs: int = train_epochs\n \"\"\" Number of training epochs. \"\"\"\n\n self.train_mb_size: int = train_mb_size\n \"\"\" Training mini-batch size. \"\"\"\n\n self.eval_mb_size: int = train_mb_size if eval_mb_size is None \\\n else eval_mb_size\n \"\"\" Eval mini-batch size. \"\"\"\n\n self.device = device\n \"\"\" PyTorch device where the model will be allocated. \"\"\"\n\n self.plugins = [] if plugins is None else plugins\n \"\"\" List of `StrategyPlugin`s. \"\"\"\n\n if evaluator is None:\n evaluator = EvaluationPlugin()\n self.plugins.append(evaluator)\n self.evaluator = evaluator\n \"\"\" EvaluationPlugin used for logging and metric computations. \"\"\"\n\n self.clock = Clock()\n \"\"\" Incremental counters for strategy events. \"\"\"\n # WARNING: Clock needs to be the last plugin, otherwise\n # counters will be wrong for plugins called after it.\n self.plugins.append(self.clock)\n\n self.eval_every = eval_every\n \"\"\" Frequency of the evaluation during training. \"\"\"\n\n ###################################################################\n # State variables. These are updated during the train/eval loops. #\n ###################################################################\n self.experience = None\n \"\"\" Current experience. \"\"\"\n\n self.adapted_dataset = None\n \"\"\" Data used to train. It may be modified by plugins. Plugins can \n append data to it (e.g. for replay). \n \n .. note:: \n This dataset may contain samples from different experiences. If you \n want the original data for the current experience \n use :attr:`.BaseStrategy.experience`.\n \"\"\"\n\n self.dataloader = None\n \"\"\" Dataloader. \"\"\"\n\n self.mbatch = None\n \"\"\" Current mini-batch. \"\"\"\n\n self.mb_output = None\n \"\"\" Model's output computed on the current mini-batch. \"\"\"\n\n self.loss = None\n \"\"\" Loss of the current mini-batch. \"\"\"\n\n self.is_training: bool = False\n \"\"\" True if the strategy is in training mode. \"\"\"\n\n self.current_eval_stream = None\n \"\"\" User-provided evaluation stream on `eval` call. \"\"\"\n\n self._stop_training = False\n\n self._warn_for_disabled_plugins_callbacks()\n self._warn_for_disabled_metrics_callbacks()\n\n @property\n def training_exp_counter(self):\n \"\"\" Counts the number of training steps. +1 at the end of each\n experience. \"\"\"\n warnings.warn(\n \"Deprecated attribute. You should use self.clock.train_exp_counter\"\n \" instead.\", DeprecationWarning)\n return self.clock.train_exp_counter\n\n @property\n def epoch(self):\n \"\"\" Epoch counter. \"\"\"\n warnings.warn(\n \"Deprecated attribute. You should use self.clock.train_exp_epochs\"\n \" instead.\", DeprecationWarning)\n return self.clock.train_exp_epochs\n\n @property\n def mb_it(self):\n \"\"\" Iteration counter. Reset at the start of a new epoch. \"\"\"\n warnings.warn(\n \"Deprecated attribute. You should use \"\n \"self.clock.train_epoch_iterations\"\n \" instead.\", DeprecationWarning)\n return self.clock.train_epoch_iterations\n\n @property\n def is_eval(self):\n \"\"\" True if the strategy is in evaluation mode. \"\"\"\n return not self.is_training\n\n @property\n def mb_x(self):\n \"\"\" Current mini-batch input. \"\"\"\n return self.mbatch[0]\n\n @property\n def mb_y(self):\n \"\"\" Current mini-batch target. \"\"\"\n return self.mbatch[1]\n\n @property\n def mb_task_id(self):\n assert len(self.mbatch) >= 3\n return self.mbatch[-1]\n\n def criterion(self):\n \"\"\" Loss function. \"\"\"\n return self._criterion(self.mb_output, self.mb_y)\n\n def train(self, experiences: Union[Experience, Sequence[Experience]],\n eval_streams: Optional[Sequence[Union[Experience,\n Sequence[\n Experience]]]] = None,\n **kwargs):\n \"\"\" Training loop. if experiences is a single element trains on it.\n If it is a sequence, trains the model on each experience in order.\n This is different from joint training on the entire stream.\n It returns a dictionary with last recorded value for each metric.\n\n :param experiences: single Experience or sequence.\n :param eval_streams: list of streams for evaluation.\n If None: use training experiences for evaluation.\n Use [] if you do not want to evaluate during training.\n\n :return: dictionary containing last recorded value for\n each metric name.\n \"\"\"\n self.is_training = True\n self._stop_training = False\n\n self.model.train()\n self.model.to(self.device)\n\n # Normalize training and eval data.\n if not isinstance(experiences, Sequence):\n experiences = [experiences]\n if eval_streams is None:\n eval_streams = [experiences]\n\n self.before_training(**kwargs)\n\n self._periodic_eval(eval_streams, do_final=False, do_initial=True)\n\n for self.experience in experiences:\n self.train_exp(self.experience, eval_streams, **kwargs)\n self.after_training(**kwargs)\n\n res = self.evaluator.get_last_metrics()\n return res\n\n def train_exp(self, experience: Experience, eval_streams=None, **kwargs):\n \"\"\"\n Training loop over a single Experience object.\n\n :param experience: CL experience information.\n :param eval_streams: list of streams for evaluation.\n If None: use the training experience for evaluation.\n Use [] if you do not want to evaluate during training.\n :param kwargs: custom arguments.\n \"\"\"\n self.experience = experience\n self.model.train()\n\n if eval_streams is None:\n eval_streams = [experience]\n for i, exp in enumerate(eval_streams):\n if not isinstance(exp, Sequence):\n eval_streams[i] = [exp]\n\n # Data Adaptation (e.g. add new samples/data augmentation)\n self.before_train_dataset_adaptation(**kwargs)\n self.train_dataset_adaptation(**kwargs)\n self.after_train_dataset_adaptation(**kwargs)\n self.make_train_dataloader(**kwargs)\n\n # Model Adaptation (e.g. freeze/add new units)\n self.model_adaptation()\n self.make_optimizer()\n\n self.before_training_exp(**kwargs)\n \n do_final = True\n if self.eval_every > 0 and \\\n (self.train_epochs - 1) % self.eval_every == 0:\n do_final = False\n\n for _ in range(self.train_epochs):\n self.before_training_epoch(**kwargs)\n\n if self._stop_training: # Early stopping\n self._stop_training = False\n break\n\n self.training_epoch(**kwargs)\n self.after_training_epoch(**kwargs)\n self._periodic_eval(eval_streams, do_final=False)\n\n # Final evaluation\n self._periodic_eval(eval_streams, do_final=do_final)\n self.after_training_exp(**kwargs)\n\n def _periodic_eval(self, eval_streams, do_final, do_initial=False):\n \"\"\" Periodic eval controlled by `self.eval_every`. \"\"\"\n # Since we are switching from train to eval model inside the training\n # loop, we need to save the training state, and restore it after the\n # eval is done.\n _prev_state = (\n self.experience,\n self.adapted_dataset,\n self.dataloader,\n self.is_training)\n \n # save each layer's training mode, to restore it later\n _prev_model_training_modes = {}\n for name, layer in self.model.named_modules():\n _prev_model_training_modes[name] = layer.training\n \n curr_epoch = self.clock.train_exp_epochs\n if (self.eval_every == 0 and (do_final or do_initial)) or \\\n (self.eval_every > 0 and do_initial) or \\\n (self.eval_every > 0 and curr_epoch % self.eval_every == 0):\n # in the first case we are outside epoch loop\n # in the second case we are within epoch loop\n for exp in eval_streams:\n self.eval(exp)\n\n # restore train-state variables and training mode.\n self.experience, self.adapted_dataset = _prev_state[:2]\n self.dataloader = _prev_state[2]\n self.is_training = _prev_state[3]\n \n # restore each layer's training mode to original \n for name, layer in self.model.named_modules():\n prev_mode = _prev_model_training_modes[name]\n layer.train(mode=prev_mode)\n\n def stop_training(self):\n \"\"\" Signals to stop training at the next iteration. \"\"\"\n self._stop_training = True\n\n def train_dataset_adaptation(self, **kwargs):\n \"\"\" Initialize `self.adapted_dataset`. \"\"\"\n self.adapted_dataset = self.experience.dataset\n self.adapted_dataset = self.adapted_dataset.train()\n\n @torch.no_grad()\n def eval(self,\n exp_list: Union[Experience, Sequence[Experience]],\n **kwargs):\n \"\"\"\n Evaluate the current model on a series of experiences and\n returns the last recorded value for each metric.\n\n :param exp_list: CL experience information.\n :param kwargs: custom arguments.\n\n :return: dictionary containing last recorded value for\n each metric name\n \"\"\"\n self.is_training = False\n self.model.eval()\n\n if not isinstance(exp_list, Sequence):\n exp_list = [exp_list]\n self.current_eval_stream = exp_list\n\n self.before_eval(**kwargs)\n for self.experience in exp_list:\n # Data Adaptation\n self.before_eval_dataset_adaptation(**kwargs)\n self.eval_dataset_adaptation(**kwargs)\n self.after_eval_dataset_adaptation(**kwargs)\n self.make_eval_dataloader(**kwargs)\n\n # Model Adaptation (e.g. freeze/add new units)\n self.model_adaptation()\n\n self.before_eval_exp(**kwargs)\n self.eval_epoch(**kwargs)\n self.after_eval_exp(**kwargs)\n\n self.after_eval(**kwargs)\n\n res = self.evaluator.get_last_metrics()\n\n return res\n\n def before_training_exp(self, **kwargs):\n \"\"\"\n Called after the dataset and data loader creation and\n before the training loop.\n \"\"\"\n for p in self.plugins:\n p.before_training_exp(self, **kwargs)\n\n def make_train_dataloader(self, num_workers=0, shuffle=True,\n pin_memory=True, **kwargs):\n \"\"\"\n Called after the dataset adaptation. Initializes the data loader.\n :param num_workers: number of thread workers for the data loading.\n :param shuffle: True if the data should be shuffled, False otherwise.\n :param pin_memory: If True, the data loader will copy Tensors into CUDA\n pinned memory before returning them. Defaults to True.\n \"\"\"\n self.dataloader = TaskBalancedDataLoader(\n self.adapted_dataset,\n oversample_small_groups=True,\n num_workers=num_workers,\n batch_size=self.train_mb_size,\n shuffle=shuffle,\n pin_memory=pin_memory)\n\n def make_eval_dataloader(self, num_workers=0, pin_memory=True,\n **kwargs):\n \"\"\"\n Initializes the eval data loader.\n :param num_workers: How many subprocesses to use for data loading.\n 0 means that the data will be loaded in the main process.\n (default: 0).\n :param pin_memory: If True, the data loader will copy Tensors into CUDA\n pinned memory before returning them. Defaults to True.\n :param kwargs:\n :return:\n \"\"\"\n self.dataloader = DataLoader(\n self.adapted_dataset,\n num_workers=num_workers,\n batch_size=self.eval_mb_size,\n pin_memory=pin_memory)\n\n def after_train_dataset_adaptation(self, **kwargs):\n \"\"\"\n Called after the dataset adaptation and before the\n dataloader initialization. Allows to customize the dataset.\n :param kwargs:\n :return:\n \"\"\"\n for p in self.plugins:\n p.after_train_dataset_adaptation(self, **kwargs)\n\n def before_training_epoch(self, **kwargs):\n \"\"\"\n Called at the beginning of a new training epoch.\n :param kwargs:\n :return:\n \"\"\"\n for p in self.plugins:\n p.before_training_epoch(self, **kwargs)\n\n def training_epoch(self, **kwargs):\n \"\"\"\n Training epoch.\n :param kwargs:\n :return:\n \"\"\"\n for self.mbatch in self.dataloader:\n if self._stop_training:\n break\n\n self._unpack_minibatch()\n self.before_training_iteration(**kwargs)\n\n self.optimizer.zero_grad()\n self.loss = 0\n\n # Forward\n self.before_forward(**kwargs)\n self.mb_output = self.forward()\n self.after_forward(**kwargs)\n\n # Loss & Backward\n self.loss += self.criterion()\n\n self.before_backward(**kwargs)\n self.loss.backward()\n self.after_backward(**kwargs)\n\n # Optimization step\n self.before_update(**kwargs)\n self.optimizer.step()\n self.after_update(**kwargs)\n\n self.after_training_iteration(**kwargs)\n\n def _unpack_minibatch(self):\n \"\"\" We assume mini-batches have the form <x, y, ..., t>.\n This allows for arbitrary tensors between y and t.\n Keep in mind that in the most general case mb_task_id is a tensor\n which may contain different labels for each sample.\n \"\"\"\n assert len(self.mbatch) >= 3\n for i in range(len(self.mbatch)):\n self.mbatch[i] = self.mbatch[i].to(self.device)\n\n def before_training(self, **kwargs):\n for p in self.plugins:\n p.before_training(self, **kwargs)\n\n def after_training(self, **kwargs):\n for p in self.plugins:\n p.after_training(self, **kwargs)\n\n def before_training_iteration(self, **kwargs):\n for p in self.plugins:\n p.before_training_iteration(self, **kwargs)\n\n def before_forward(self, **kwargs):\n for p in self.plugins:\n p.before_forward(self, **kwargs)\n\n def after_forward(self, **kwargs):\n for p in self.plugins:\n p.after_forward(self, **kwargs)\n\n def before_backward(self, **kwargs):\n for p in self.plugins:\n p.before_backward(self, **kwargs)\n\n def after_backward(self, **kwargs):\n for p in self.plugins:\n p.after_backward(self, **kwargs)\n\n def after_training_iteration(self, **kwargs):\n for p in self.plugins:\n p.after_training_iteration(self, **kwargs)\n\n def before_update(self, **kwargs):\n for p in self.plugins:\n p.before_update(self, **kwargs)\n\n def after_update(self, **kwargs):\n for p in self.plugins:\n p.after_update(self, **kwargs)\n\n def after_training_epoch(self, **kwargs):\n for p in self.plugins:\n p.after_training_epoch(self, **kwargs)\n\n def after_training_exp(self, **kwargs):\n for p in self.plugins:\n p.after_training_exp(self, **kwargs)\n\n def before_eval(self, **kwargs):\n for p in self.plugins:\n p.before_eval(self, **kwargs)\n\n def before_eval_exp(self, **kwargs):\n for p in self.plugins:\n p.before_eval_exp(self, **kwargs)\n\n def eval_dataset_adaptation(self, **kwargs):\n \"\"\" Initialize `self.adapted_dataset`. \"\"\"\n self.adapted_dataset = self.experience.dataset\n self.adapted_dataset = self.adapted_dataset.eval()\n\n def before_eval_dataset_adaptation(self, **kwargs):\n for p in self.plugins:\n p.before_eval_dataset_adaptation(self, **kwargs)\n\n def after_eval_dataset_adaptation(self, **kwargs):\n for p in self.plugins:\n p.after_eval_dataset_adaptation(self, **kwargs)\n\n def eval_epoch(self, **kwargs):\n for self.mbatch in self.dataloader:\n self._unpack_minibatch()\n self.before_eval_iteration(**kwargs)\n\n self.before_eval_forward(**kwargs)\n self.mb_output = self.forward()\n self.after_eval_forward(**kwargs)\n self.loss = self.criterion()\n\n self.after_eval_iteration(**kwargs)\n\n def after_eval_exp(self, **kwargs):\n for p in self.plugins:\n p.after_eval_exp(self, **kwargs)\n\n def after_eval(self, **kwargs):\n for p in self.plugins:\n p.after_eval(self, **kwargs)\n\n def before_eval_iteration(self, **kwargs):\n for p in self.plugins:\n p.before_eval_iteration(self, **kwargs)\n\n def before_eval_forward(self, **kwargs):\n for p in self.plugins:\n p.before_eval_forward(self, **kwargs)\n\n def after_eval_forward(self, **kwargs):\n for p in self.plugins:\n p.after_eval_forward(self, **kwargs)\n\n def after_eval_iteration(self, **kwargs):\n for p in self.plugins:\n p.after_eval_iteration(self, **kwargs)\n\n def before_train_dataset_adaptation(self, **kwargs):\n for p in self.plugins:\n p.before_train_dataset_adaptation(self, **kwargs)\n\n def model_adaptation(self):\n for module in self.model.modules():\n if isinstance(module, DynamicModule):\n module.adaptation(self.experience.dataset)\n self.model = self.model.to(self.device)\n\n def forward(self):\n return avalanche_forward(self.model, self.mb_x, self.mb_task_id)\n\n def make_optimizer(self):\n # we reset the optimizer's state after each experience.\n # This allows to add new parameters (new heads) and\n # freezing old units during the model's adaptation phase.\n reset_optimizer(self.optimizer, self.model)\n\n def _warn_for_disabled_plugins_callbacks(self):\n self._warn_for_disabled_callbacks(self.plugins)\n\n def _warn_for_disabled_metrics_callbacks(self):\n self._warn_for_disabled_callbacks(self.evaluator.metrics)\n\n def _warn_for_disabled_callbacks(\n self,\n plugins: List[\"StrategyCallbacks\"]\n ):\n \"\"\"\n Will log some warnings in case some plugins appear to be using callbacks\n that have been de-activated by the strategy class.\n \"\"\"\n for disabled_callback_name in self.DISABLED_CALLBACKS:\n for plugin in plugins:\n callback = getattr(plugin, disabled_callback_name)\n callback_class = callback.__qualname__.split('.')[0]\n if callback_class not in (\n \"StrategyPlugin\",\n \"PluginMetric\",\n \"EvaluationPlugin\",\n \"GenericPluginMetric\",\n ):\n logger.warning(\n f\"{plugin.__class__.__name__} seems to use \"\n f\"the callback {disabled_callback_name} \"\n f\"which is disabled by {self.__class__.__name__}\"\n )\n\n\n__all__ = ['BaseStrategy']\n"
]
| [
[
"torch.no_grad",
"torch.nn.CrossEntropyLoss",
"torch.utils.data.DataLoader"
]
]
|
DmitryGolovin-azur/article-processing-big-numeric-arrays-in-python | [
"10eb4d4a9ada0037a589183b179caa4c55f41a50"
]
| [
"src/e10_calc_ema_naive_improved.py"
]
| [
"import xarray as xr\nimport numpy as np\nimport time\n\ndata = xr.open_dataarray('../data.nc', decode_times=True).compute()\n\ndef calc_ema_list(prices, n):\n k = 2.0 / (1 + n)\n _k = 1 - k\n ema = []\n pe = np.nan\n for e in prices:\n if not np.isnan(pe):\n if np.isnan(e):\n e = pe\n else:\n e = k * e + _k * pe\n ema.append(e)\n pe = e\n return ema\n\nema = xr.zeros_like(data)\n\nt0 = time.time()\nfor a in data.asset.values.tolist():\n for f in data.field.values.tolist():\n ema.loc[a,f] = calc_ema_list(data.loc[a,f].values.tolist(), 20)\nt1 = time.time()\n\nprint('time:', t1-t0)\n"
]
| [
[
"numpy.isnan"
]
]
|
zer0onetwothree/openpilot | [
"b8c7502d7e0e626e84bee95f3c3cd04a45a02f9f"
]
| [
"selfdrive/car/honda/interface.py"
]
| [
"#!/usr/bin/env python3\nimport numpy as np\nfrom cereal import car\nfrom common.numpy_fast import clip, interp\nfrom common.realtime import DT_CTRL\nfrom selfdrive.swaglog import cloudlog\nfrom selfdrive.config import Conversions as CV\nfrom selfdrive.controls.lib.events import ET\nfrom selfdrive.car.honda.values import CruiseButtons, CAR, HONDA_BOSCH, Ecu, ECU_FINGERPRINT, FINGERPRINTS\nfrom selfdrive.car import STD_CARGO_KG, CivicParams, scale_rot_inertia, scale_tire_stiffness, is_ecu_disconnected, gen_empty_fingerprint\nfrom selfdrive.controls.lib.planner import _A_CRUISE_MAX_V_FOLLOWING\nfrom selfdrive.car.interfaces import CarInterfaceBase\n\nA_ACC_MAX = max(_A_CRUISE_MAX_V_FOLLOWING)\n\nButtonType = car.CarState.ButtonEvent.Type\nEventName = car.CarEvent.EventName\n\ndef compute_gb_honda(accel, speed):\n creep_brake = 0.0\n creep_speed = 2.3\n creep_brake_value = 0.15\n if speed < creep_speed:\n creep_brake = (creep_speed - speed) / creep_speed * creep_brake_value\n return float(accel) / 4.8 - creep_brake\n\n\ndef get_compute_gb_acura():\n # generate a function that takes in [desired_accel, current_speed] -> [-1.0, 1.0]\n # where -1.0 is max brake and 1.0 is max gas\n # see debug/dump_accel_from_fiber.py to see how those parameters were generated\n w0 = np.array([[ 1.22056961, -0.39625418, 0.67952657],\n [ 1.03691769, 0.78210306, -0.41343188]])\n b0 = np.array([ 0.01536703, -0.14335321, -0.26932889])\n w2 = np.array([[-0.59124422, 0.42899439, 0.38660881],\n [ 0.79973811, 0.13178682, 0.08550351],\n [-0.15651935, -0.44360259, 0.76910877]])\n b2 = np.array([ 0.15624429, 0.02294923, -0.0341086 ])\n w4 = np.array([[-0.31521443],\n [-0.38626176],\n [ 0.52667892]])\n b4 = np.array([-0.02922216])\n\n def compute_output(dat, w0, b0, w2, b2, w4, b4):\n m0 = np.dot(dat, w0) + b0\n m0 = leakyrelu(m0, 0.1)\n m2 = np.dot(m0, w2) + b2\n m2 = leakyrelu(m2, 0.1)\n m4 = np.dot(m2, w4) + b4\n return m4\n\n def leakyrelu(x, alpha):\n return np.maximum(x, alpha * x)\n\n def _compute_gb_acura(accel, speed):\n # linearly extrap below v1 using v1 and v2 data\n v1 = 5.\n v2 = 10.\n dat = np.array([accel, speed])\n if speed > 5.:\n m4 = compute_output(dat, w0, b0, w2, b2, w4, b4)\n else:\n dat[1] = v1\n m4v1 = compute_output(dat, w0, b0, w2, b2, w4, b4)\n dat[1] = v2\n m4v2 = compute_output(dat, w0, b0, w2, b2, w4, b4)\n m4 = (speed - v1) * (m4v2 - m4v1) / (v2 - v1) + m4v1\n return float(m4)\n\n return _compute_gb_acura\n\n\nclass CarInterface(CarInterfaceBase):\n def __init__(self, CP, CarController, CarState):\n super().__init__(CP, CarController, CarState)\n\n self.last_enable_pressed = 0\n self.last_enable_sent = 0\n\n if self.CS.CP.carFingerprint == CAR.ACURA_ILX:\n self.compute_gb = get_compute_gb_acura()\n else:\n self.compute_gb = compute_gb_honda\n\n @staticmethod\n def compute_gb(accel, speed): # pylint: disable=method-hidden\n raise NotImplementedError\n\n @staticmethod\n def calc_accel_override(a_ego, a_target, v_ego, v_target):\n\n # normalized max accel. Allowing max accel at low speed causes speed overshoots\n max_accel_bp = [10, 20] # m/s\n max_accel_v = [0.714, 1.0] # unit of max accel\n max_accel = interp(v_ego, max_accel_bp, max_accel_v)\n\n # limit the pcm accel cmd if:\n # - v_ego exceeds v_target, or\n # - a_ego exceeds a_target and v_ego is close to v_target\n\n eA = a_ego - a_target\n valuesA = [1.0, 0.1]\n bpA = [0.3, 1.1]\n\n eV = v_ego - v_target\n valuesV = [1.0, 0.1]\n bpV = [0.0, 0.5]\n\n valuesRangeV = [1., 0.]\n bpRangeV = [-1., 0.]\n\n # only limit if v_ego is close to v_target\n speedLimiter = interp(eV, bpV, valuesV)\n accelLimiter = max(interp(eA, bpA, valuesA), interp(eV, bpRangeV, valuesRangeV))\n\n # accelOverride is more or less the max throttle allowed to pcm: usually set to a constant\n # unless aTargetMax is very high and then we scale with it; this help in quicker restart\n\n return float(max(max_accel, a_target / A_ACC_MAX)) * min(speedLimiter, accelLimiter)\n\n @staticmethod\n def get_params(candidate, fingerprint=gen_empty_fingerprint(), has_relay=False, car_fw=[]): # pylint: disable=dangerous-default-value\n ret = CarInterfaceBase.get_std_params(candidate, fingerprint, has_relay)\n ret.carName = \"honda\"\n\n if candidate in HONDA_BOSCH:\n ret.safetyModel = car.CarParams.SafetyModel.hondaBoschHarness if has_relay else car.CarParams.SafetyModel.hondaBoschGiraffe\n rdr_bus = 0 if has_relay else 2\n ret.enableCamera = is_ecu_disconnected(fingerprint[rdr_bus], FINGERPRINTS, ECU_FINGERPRINT, candidate, Ecu.fwdCamera) or has_relay\n ret.radarOffCan = True\n ret.openpilotLongitudinalControl = False\n else:\n ret.safetyModel = car.CarParams.SafetyModel.hondaNidec\n ret.enableCamera = True #Clarity: We need to force this to True to make OpenPilot happy. -wirelessnet2\n ret.enableGasInterceptor = 0x201 in fingerprint[0]\n ret.openpilotLongitudinalControl = ret.enableCamera\n\n cloudlog.warning(\"ECU Camera Simulated: %r\", ret.enableCamera)\n cloudlog.warning(\"ECU Gas Interceptor: %r\", ret.enableGasInterceptor)\n\n ret.enableCruise = not ret.enableGasInterceptor\n ret.communityFeature = ret.enableGasInterceptor\n\n # Certain Hondas have an extra steering sensor at the bottom of the steering rack,\n # which improves controls quality as it removes the steering column torsion from feedback.\n # Tire stiffness factor fictitiously lower if it includes the steering column torsion effect.\n # For modeling details, see p.198-200 in \"The Science of Vehicle Dynamics (2014), M. Guiggiani\"\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0], [0]]\n ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0.], [0.]]\n ret.lateralTuning.pid.kf = 0.00004 # conservative feed-forward\n ret.steerRatioV = 0.0045 #Random Convervative Value -wirelessnet2\n\n eps_modified = False\n eps_modified_3x = False\n for fw in car_fw:\n if fw.ecu == \"eps\" and b\"-\" not in fw.fwVersion and b\",\" in fw.fwVersion:\n eps_modified_3x = True\n print(\"3x MODIFIED EPS DETECTED\")\n elif fw.ecu == \"eps\" and b\"-\" in fw.fwVersion and b\",\" in fw.fwVersion:\n eps_modified = True\n print(\"2x MODIFIED EPS DETECTED\")\n\n if candidate == CAR.CIVIC:\n stop_and_go = True\n ret.mass = CivicParams.MASS\n ret.wheelbase = CivicParams.WHEELBASE\n ret.centerToFront = CivicParams.CENTER_TO_FRONT\n ret.steerRatio = 15.38 # 10.93 is end-to-end spec\n if eps_modified:\n # stock request input values: 0x0000, 0x00DE, 0x014D, 0x01EF, 0x0290, 0x0377, 0x0454, 0x0610, 0x06EE\n # stock request output values: 0x0000, 0x0917, 0x0DC5, 0x1017, 0x119F, 0x140B, 0x1680, 0x1680, 0x1680\n # modified request output values: 0x0000, 0x0917, 0x0DC5, 0x1017, 0x119F, 0x140B, 0x1680, 0x2880, 0x3180\n # stock filter output values: 0x009F, 0x0108, 0x0108, 0x0108, 0x0108, 0x0108, 0x0108, 0x0108, 0x0108\n # modified filter output values: 0x009F, 0x0108, 0x0108, 0x0108, 0x0108, 0x0108, 0x0108, 0x0400, 0x0480\n # note: max request allowed is 4096, but request is capped at 3840 in firmware, so modifications result in 2x max\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 2560, 8000], [0, 2560, 3840]]\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.3], [0.1]]\n else:\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 2560], [0, 2560]]\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[1.1], [0.33]]\n tire_stiffness_factor = 1.\n\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [3.6, 2.4, 1.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.54, 0.36]\n\n elif candidate in (CAR.CIVIC_BOSCH, CAR.CIVIC_BOSCH_DIESEL):\n stop_and_go = True\n ret.mass = CivicParams.MASS\n ret.wheelbase = CivicParams.WHEELBASE\n ret.centerToFront = CivicParams.CENTER_TO_FRONT\n ret.steerRatio = 15.38 # 10.93 is end-to-end spec\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 4096], [0, 4096]] # TODO: determine if there is a dead zone at the top end\n tire_stiffness_factor = 1.\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.8], [0.24]]\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [1.2, 0.8, 0.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.18, 0.12]\n\n elif candidate in (CAR.ACCORD, CAR.ACCORD_15, CAR.ACCORDH):\n stop_and_go = True\n if not candidate == CAR.ACCORDH: # Hybrid uses same brake msg as hatch\n ret.safetyParam = 1 # Accord and CRV 5G use an alternate user brake msg\n ret.mass = 3279. * CV.LB_TO_KG + STD_CARGO_KG\n ret.wheelbase = 2.83\n ret.centerToFront = ret.wheelbase * 0.39\n ret.steerRatio = 16.33 # 11.82 is spec end-to-end\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 4096], [0, 4096]] # TODO: determine if there is a dead zone at the top end\n tire_stiffness_factor = 0.8467\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [1.2, 0.8, 0.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.18, 0.12]\n\n if eps_modified:\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.3], [0.09]]\n else:\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.6], [0.18]]\n \n elif candidate == CAR.CLARITY: #Clarity\n stop_and_go = True\n ret.mass = 4052. * CV.LB_TO_KG + STD_CARGO_KG\n ret.wheelbase = 2.75\n ret.centerToFront = ret.wheelbase * 0.4\n ret.steerRatio = 16.50 # was 17.03, 12.72 is end-to-end spec\n if eps_modified_3x:\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 0xA00, 0x3C00], [0, 2560, 3840]]\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.175], [0.0575]]\n print(\"clarity.brUHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\") # @clarity.bru: Hello =P -wirelessnet2\n elif eps_modified:\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 0xA00, 0x2800], [0, 2560, 3840]]\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.32], [0.1]]\n print(\"!!!!!!!!!!!!!!!!!!2x MODIFIED TUNING VALUES USED!!!!!!!!!!!!!!!!!!\")\n else:\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 2560], [0, 2560]]\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.775], [0.23]]\n print(\"------------------UNMODIFIED TUNING VALUES USED------------------\")\n tire_stiffness_factor = 1.\n\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [3.6, 2.4, 1.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.54, 0.36]\n\n elif candidate == CAR.ACURA_ILX:\n stop_and_go = False\n ret.mass = 3095. * CV.LB_TO_KG + STD_CARGO_KG\n ret.wheelbase = 2.67\n ret.centerToFront = ret.wheelbase * 0.37\n ret.steerRatio = 18.61 # 15.3 is spec end-to-end\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 3840], [0, 3840]] # TODO: determine if there is a dead zone at the top end\n tire_stiffness_factor = 0.72\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.8], [0.24]]\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [1.2, 0.8, 0.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.18, 0.12]\n\n elif candidate in (CAR.CRV, CAR.CRV_EU):\n stop_and_go = False\n ret.mass = 3572. * CV.LB_TO_KG + STD_CARGO_KG\n ret.wheelbase = 2.62\n ret.centerToFront = ret.wheelbase * 0.41\n ret.steerRatio = 16.89 # as spec\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 1000], [0, 1000]] # TODO: determine if there is a dead zone at the top end\n tire_stiffness_factor = 0.444\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.8], [0.24]]\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [1.2, 0.8, 0.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.18, 0.12]\n\n elif candidate == CAR.CRV_5G:\n stop_and_go = True\n ret.safetyParam = 1 # Accord and CRV 5G use an alternate user brake msg\n ret.mass = 3410. * CV.LB_TO_KG + STD_CARGO_KG\n ret.wheelbase = 2.66\n ret.centerToFront = ret.wheelbase * 0.41\n ret.steerRatio = 16.0 # 12.3 is spec end-to-end\n if eps_modified:\n # stock request input values: 0x0000, 0x00DB, 0x01BB, 0x0296, 0x0377, 0x0454, 0x0532, 0x0610, 0x067F\n # stock request output values: 0x0000, 0x0500, 0x0A15, 0x0E6D, 0x1100, 0x1200, 0x129A, 0x134D, 0x1400\n # modified request output values: 0x0000, 0x0500, 0x0A15, 0x0E6D, 0x1100, 0x1200, 0x1ACD, 0x239A, 0x2800\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 2560, 10000], [0, 2560, 3840]]\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.3], [0.1]]\n else:\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 3840], [0, 3840]]\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.64], [0.192]]\n tire_stiffness_factor = 0.677\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [1.2, 0.8, 0.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.18, 0.12]\n\n elif candidate == CAR.CRV_HYBRID:\n stop_and_go = True\n ret.safetyParam = 1 # Accord and CRV 5G use an alternate user brake msg\n ret.mass = 1667. + STD_CARGO_KG # mean of 4 models in kg\n ret.wheelbase = 2.66\n ret.centerToFront = ret.wheelbase * 0.41\n ret.steerRatio = 16.0 # 12.3 is spec end-to-end\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 4096], [0, 4096]] # TODO: determine if there is a dead zone at the top end\n tire_stiffness_factor = 0.677\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.6], [0.18]]\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [1.2, 0.8, 0.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.18, 0.12]\n\n elif candidate == CAR.FIT:\n stop_and_go = False\n ret.mass = 2644. * CV.LB_TO_KG + STD_CARGO_KG\n ret.wheelbase = 2.53\n ret.centerToFront = ret.wheelbase * 0.39\n ret.steerRatio = 13.06\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 4096], [0, 4096]] # TODO: determine if there is a dead zone at the top end\n tire_stiffness_factor = 0.75\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.25], [0.06]]\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [1.2, 0.8, 0.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.18, 0.12]\n\n elif candidate == CAR.HRV:\n stop_and_go = False\n ret.mass = 3125 * CV.LB_TO_KG + STD_CARGO_KG\n ret.wheelbase = 2.61\n ret.centerToFront = ret.wheelbase * 0.41\n ret.steerRatio = 15.2\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 4096], [0, 4096]]\n tire_stiffness_factor = 0.5\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.16], [0.025]]\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [1.2, 0.8, 0.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.18, 0.12]\n\n elif candidate == CAR.ACURA_RDX:\n stop_and_go = False\n ret.mass = 3935. * CV.LB_TO_KG + STD_CARGO_KG\n ret.wheelbase = 2.68\n ret.centerToFront = ret.wheelbase * 0.38\n ret.steerRatio = 15.0 # as spec\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 1000], [0, 1000]] # TODO: determine if there is a dead zone at the top end\n tire_stiffness_factor = 0.444\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.8], [0.24]]\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [1.2, 0.8, 0.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.18, 0.12]\n\n elif candidate == CAR.ODYSSEY:\n stop_and_go = False\n ret.mass = 4471. * CV.LB_TO_KG + STD_CARGO_KG\n ret.wheelbase = 3.00\n ret.centerToFront = ret.wheelbase * 0.41\n ret.steerRatio = 14.35 # as spec\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 4096], [0, 4096]] # TODO: determine if there is a dead zone at the top end\n tire_stiffness_factor = 0.82\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.45], [0.135]]\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [1.2, 0.8, 0.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.18, 0.12]\n\n elif candidate == CAR.ODYSSEY_CHN:\n stop_and_go = False\n ret.mass = 1849.2 + STD_CARGO_KG # mean of 4 models in kg\n ret.wheelbase = 2.90\n ret.centerToFront = ret.wheelbase * 0.41 # from CAR.ODYSSEY\n ret.steerRatio = 14.35\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 32767], [0, 32767]] # TODO: determine if there is a dead zone at the top end\n tire_stiffness_factor = 0.82\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.45], [0.135]]\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [1.2, 0.8, 0.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.18, 0.12]\n\n elif candidate in (CAR.PILOT, CAR.PILOT_2019):\n stop_and_go = False\n ret.mass = 4204. * CV.LB_TO_KG + STD_CARGO_KG # average weight\n ret.wheelbase = 2.82\n ret.centerToFront = ret.wheelbase * 0.428\n ret.steerRatio = 17.25 # as spec\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 4096], [0, 4096]] # TODO: determine if there is a dead zone at the top end\n tire_stiffness_factor = 0.444\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.38], [0.11]]\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [1.2, 0.8, 0.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.18, 0.12]\n\n elif candidate == CAR.RIDGELINE:\n stop_and_go = False\n ret.mass = 4515. * CV.LB_TO_KG + STD_CARGO_KG\n ret.wheelbase = 3.18\n ret.centerToFront = ret.wheelbase * 0.41\n ret.steerRatio = 15.59 # as spec\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 4096], [0, 4096]] # TODO: determine if there is a dead zone at the top end\n tire_stiffness_factor = 0.444\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.38], [0.11]]\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [1.2, 0.8, 0.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.18, 0.12]\n\n elif candidate == CAR.INSIGHT:\n stop_and_go = True\n ret.mass = 2987. * CV.LB_TO_KG + STD_CARGO_KG\n ret.wheelbase = 2.7\n ret.centerToFront = ret.wheelbase * 0.39\n ret.steerRatio = 15.0 # 12.58 is spec end-to-end\n ret.lateralParams.torqueBP, ret.lateralParams.torqueV = [[0, 4096], [0, 4096]] # TODO: determine if there is a dead zone at the top end\n tire_stiffness_factor = 0.82\n ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.6], [0.18]]\n ret.longitudinalTuning.kpBP = [0., 5., 35.]\n ret.longitudinalTuning.kpV = [1.2, 0.8, 0.5]\n ret.longitudinalTuning.kiBP = [0., 35.]\n ret.longitudinalTuning.kiV = [0.18, 0.12]\n\n else:\n raise ValueError(\"unsupported car %s\" % candidate)\n\n # min speed to enable ACC. if car can do stop and go, then set enabling speed\n # to a negative value, so it won't matter. Otherwise, add 0.5 mph margin to not\n # conflict with PCM acc\n ret.minEnableSpeed = -1. if (stop_and_go or ret.enableGasInterceptor) else 25.5 * CV.MPH_TO_MS\n\n # TODO: get actual value, for now starting with reasonable value for\n # civic and scaling by mass and wheelbase\n ret.rotationalInertia = scale_rot_inertia(ret.mass, ret.wheelbase)\n\n # TODO: start from empirically derived lateral slip stiffness for the civic and scale by\n # mass and CG position, so all cars will have approximately similar dyn behaviors\n ret.tireStiffnessFront, ret.tireStiffnessRear = scale_tire_stiffness(ret.mass, ret.wheelbase, ret.centerToFront,\n tire_stiffness_factor=tire_stiffness_factor)\n\n ret.gasMaxBP = [0.] # m/s\n ret.gasMaxV = [0.6] if ret.enableGasInterceptor else [0.] # max gas allowed\n ret.brakeMaxBP = [5., 20.] # m/s\n ret.brakeMaxV = [1., 0.8] # max brake allowed\n\n ret.stoppingControl = True\n ret.startAccel = 0.5\n\n ret.steerActuatorDelay = 0.1\n ret.steerRateCost = 0.4\n ret.steerLimitTimer = 0.8\n\n return ret\n\n # returns a car.CarState\n def update(self, c, can_strings):\n # ******************* do can recv *******************\n self.cp.update_strings(can_strings)\n #self.cp_cam.update_strings(can_strings) #Clarity: cp_cam is the CAN parser for the Factory Camera CAN. Since we've disconnected the factory camera, this is not needed. -wirelessnet2\n if self.cp_body:\n self.cp_body.update_strings(can_strings)\n\n ret = self.CS.update(self.cp, self.cp_body) #Clarity: cp_cam is the CAN parser for the Factory Camera CAN. Since we've disconnected the factory camera, this is not needed. -wirelessnet2\n\n ret.canValid = self.cp.can_valid and (self.cp_body is None or self.cp_body.can_valid) #Clarity: cp_cam is the CAN parser for the Factory Camera CAN. Since we've disconnected the factory camera, this is not needed. -wirelessnet2\n ret.yawRate = self.VM.yaw_rate(ret.steeringAngle * CV.DEG_TO_RAD, ret.vEgo)\n # FIXME: read sendcan for brakelights\n brakelights_threshold = 0.02 if self.CS.CP.carFingerprint == CAR.CIVIC else 0.1\n ret.brakeLights = bool(self.CS.brake_switch or\n c.actuators.brake > brakelights_threshold)\n\n ret.readdistancelines = self.CS.read_distance_lines\n ret.lkMode = self.CS.lkMode\n ret.engineRPM = self.CS.engineRPM\n ret.brakeToggle = self.CS.brakeToggle\n buttonEvents = []\n\n if self.CS.cruise_buttons != self.CS.prev_cruise_buttons:\n be = car.CarState.ButtonEvent.new_message()\n be.type = ButtonType.unknown\n if self.CS.cruise_buttons != 0:\n be.pressed = True\n but = self.CS.cruise_buttons\n else:\n be.pressed = False\n but = self.CS.prev_cruise_buttons\n if but == CruiseButtons.RES_ACCEL:\n be.type = ButtonType.accelCruise\n elif but == CruiseButtons.DECEL_SET:\n be.type = ButtonType.decelCruise\n elif but == CruiseButtons.CANCEL:\n be.type = ButtonType.cancel\n elif but == CruiseButtons.MAIN:\n be.type = ButtonType.altButton3\n buttonEvents.append(be)\n\n if self.CS.cruise_setting != self.CS.prev_cruise_setting:\n be = car.CarState.ButtonEvent.new_message()\n be.type = ButtonType.unknown\n if self.CS.cruise_setting != 0:\n be.pressed = True\n but = self.CS.cruise_setting\n else:\n be.pressed = False\n but = self.CS.prev_cruise_setting\n if but == 1:\n be.type = ButtonType.altButton1\n # TODO: more buttons?\n buttonEvents.append(be)\n ret.buttonEvents = buttonEvents\n\n # events\n events = self.create_common_events(ret, pcm_enable=False)\n if self.CS.brake_error:\n events.add(EventName.brakeUnavailable)\n if self.CS.brake_hold and self.CS.CP.carFingerprint not in HONDA_BOSCH:\n events.add(EventName.brakeHold)\n if self.CS.park_brake:\n events.add(EventName.parkBrake)\n\n if self.CP.enableCruise and ret.vEgo < self.CP.minEnableSpeed:\n events.add(EventName.belowEngageSpeed)\n\n # it can happen that car cruise disables while comma system is enabled: need to\n # keep braking if needed or if the speed is very low\n if self.CS.preEnableAlert:\n events.add(EventName.longPreEnable)\n elif (self.CP.enableCruise and not ret.cruiseState.enabled):\n if self.CS.brakeToggle:\n events.add(EventName.acceleratorDisabled)\n else:\n events.add(EventName.lkasOnly) #If PCM is not taking computer_gas requests and user has pressed the gas pedal (which disables braking) -wirelessnet2\n\n cur_time = self.frame * DT_CTRL\n enable_pressed = False\n # handle button presses\n for b in ret.buttonEvents:\n\n # do enable on both accel and decel buttons\n if b.type in [ButtonType.accelCruise, ButtonType.decelCruise] and not b.pressed:\n self.last_enable_pressed = cur_time\n enable_pressed = True\n\n # do disable on button down\n if b.type == \"cancel\" and b.pressed:\n events.add(EventName.buttonCancel)\n\n if self.CP.enableCruise:\n # KEEP THIS EVENT LAST! send enable event if button is pressed and there are\n # NO_ENTRY events, so controlsd will display alerts. Also not send enable events\n # too close in time, so a no_entry will not be followed by another one.\n # TODO: button press should be the only thing that triggers enable\n if ((cur_time - self.last_enable_pressed) < 0.2 and\n (cur_time - self.last_enable_sent) > 0.2 and\n ret.cruiseState.enabled) or \\\n (enable_pressed and events.any(ET.NO_ENTRY)):\n events.add(EventName.buttonEnable)\n self.last_enable_sent = cur_time\n elif enable_pressed:\n events.add(EventName.buttonEnable)\n\n ret.events = events.to_msg()\n\n self.CS.out = ret.as_reader()\n return self.CS.out\n\n # pass in a car.CarControl\n # to be called @ 100hz\n def apply(self, c):\n if c.hudControl.speedVisible:\n hud_v_cruise = c.hudControl.setSpeed * CV.MS_TO_KPH\n else:\n hud_v_cruise = 255\n\n pcm_accel = int(clip(c.cruiseControl.accelOverride, 0, 1) * 0xc6) if self.CS.gasToggle else 0\n\n can_sends = self.CC.update(c.enabled, self.CS, self.frame,\n c.actuators,\n c.cruiseControl.speedOverride,\n c.cruiseControl.override,\n c.cruiseControl.cancel,\n pcm_accel,\n hud_v_cruise,\n c.hudControl.lanesVisible,\n hud_show_car=c.hudControl.leadVisible,\n hud_alert=c.hudControl.visualAlert)\n\n self.frame += 1\n return can_sends\n"
]
| [
[
"numpy.array",
"numpy.dot",
"numpy.maximum"
]
]
|
cosminacho/Helmet.AI | [
"f3aee1c8ffc2fd01094218524870d41c9761e7f8"
]
| [
"src/utils/tfrecords/create_helmet_tfrecord.py"
]
| [
"import os\n\nimport lxml.etree\n\nimport tensorflow as tf\nimport numpy as np\nimport cv2\n\n\ndef parse_xml(xml):\n if not len(xml):\n return {xml.tag: xml.text}\n result = {}\n for child in xml:\n child_result = parse_xml(child)\n if child.tag != 'object':\n result[child.tag] = child_result[child.tag]\n else:\n if child.tag not in result:\n result[child.tag] = []\n result[child.tag].append(child_result[child.tag])\n return {xml.tag: result}\n\n\ndef extract_boxes_from_voc(voc_obj):\n\n boxes = []\n\n if 'object' in voc_obj['annotation']:\n for obj in voc_obj['annotation']['object']:\n\n xmin = int(obj['bndbox']['xmin'])\n ymin = int(obj['bndbox']['ymin'])\n xmax = int(obj['bndbox']['xmax'])\n ymax = int(obj['bndbox']['ymax'])\n if obj['name'] in ['person', 'head', 'none']:\n obj_class = 0\n elif obj['name'] in ['hat', 'helmet', 'red', 'yellow', 'white', 'blue']:\n obj_class = 1\n # elif obj['name'] == 'red':\n # obj_class = 1\n # elif obj['name'] == 'yellow':\n # obj_class = 2\n # elif obj['name'] == 'blue':\n # obj_class = 3\n # elif obj['name'] == 'white':\n # obj_class = 4\n boxes.append([xmin, ymin, xmax, ymax, obj_class])\n\n return boxes\n\n\ndef flip_image(index, image_filename, boxes):\n image = cv2.imread(image_filename)\n height, width, _ = image.shape\n flipped_image = cv2.flip(image, 1)\n flipped_boxes = []\n for box in boxes:\n flipped_box = [width-box[2], box[1], width-box[0], box[3], box[4]]\n flipped_boxes.append(flipped_box)\n\n flipped_image_filename = f\"flipped_images/{index}.jpg\"\n cv2.imwrite(flipped_image_filename, flipped_image)\n return (flipped_image_filename, flipped_boxes)\n\n\ndef build_sample(image_filename, boxes):\n raw_image = open(image_filename, 'rb').read()\n\n image = cv2.imread(image_filename)\n img_height, img_width, _ = image.shape\n\n xmins = []\n ymins = []\n xmaxs = []\n ymaxs = []\n classes = []\n\n for box in boxes:\n xmins.append(box[0] / img_width)\n ymins.append(box[1] / img_height)\n xmaxs.append(box[2] / img_width)\n ymaxs.append(box[3] / img_height)\n classes.append(box[4])\n\n example = tf.train.Example(features=tf.train.Features(feature={\n \"xmins\": tf.train.Feature(float_list=tf.train.FloatList(value=xmins)),\n \"ymins\": tf.train.Feature(float_list=tf.train.FloatList(value=ymins)),\n \"xmaxs\": tf.train.Feature(float_list=tf.train.FloatList(value=xmaxs)),\n \"ymaxs\": tf.train.Feature(float_list=tf.train.FloatList(value=ymaxs)),\n \"classes\": tf.train.Feature(int64_list=tf.train.Int64List(value=classes)),\n \"image\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[raw_image]))\n }))\n return example\n\n\ndef parse_voc_dataset(images_dir, annotations_dir):\n files = os.listdir(annotations_dir)\n result = []\n for filename in files:\n xml_string = lxml.etree.fromstring(\n open(annotations_dir + filename, encoding='utf-8').read())\n\n voc_obj = parse_xml(xml_string)\n boxes = extract_boxes_from_voc(voc_obj)\n image_filename = images_dir + filename[:-4] + '.jpg'\n result.append([image_filename, boxes])\n\n return result\n\n\ndef check_sample(image_filename, boxes):\n if not os.path.isfile(image_filename):\n return False\n\n image = cv2.imread(image_filename)\n height, width, channels = image.shape\n if channels != 3:\n return False\n\n for box in boxes:\n if box[4] not in [0, 1]:\n return False\n if (box[0] < box[2]) and (0 <= box[0]) and (box[2] <= width):\n pass\n else:\n return False\n if (box[1] < box[3]) and (0 <= box[1]) and (box[3] <= height):\n pass\n else:\n return False\n\n return True\n\n\ndef main():\n images_dir1 = \"datasets/colored_helmet_dataset/JPEGImages/\"\n images_dir2 = \"datasets/helmet_dataset_1/JPEGImages/\"\n images_dir3_1 = \"datasets/helmet_dataset_2/Train/JPEGImage/\"\n images_dir3_2 = \"datasets/helmet_dataset_2/Test/JPEGImage/\"\n\n annotations_dir1 = \"datasets/colored_helmet_dataset/Annotations/\"\n annotations_dir2 = \"datasets/helmet_dataset_1/Annotations/\"\n annotations_dir3_1 = \"datasets/helmet_dataset_2/Train/Annotation/\"\n annotations_dir3_2 = \"datasets/helmet_dataset_2/Test/Annotation/\"\n\n items = []\n items.extend(parse_voc_dataset(images_dir1, annotations_dir1))\n items.extend(parse_voc_dataset(images_dir2, annotations_dir2))\n items.extend(parse_voc_dataset(images_dir3_1, annotations_dir3_1))\n items.extend(parse_voc_dataset(images_dir3_2, annotations_dir3_2))\n\n flipped_items = []\n for index, item in enumerate(items):\n flipped_image_filename, flipped_boxes = flip_image(\n index+1, item[0], item[1])\n flipped_items.append([flipped_image_filename, flipped_boxes])\n\n items.extend(flipped_items)\n\n np.random.shuffle(items)\n items.reverse()\n np.random.shuffle(items)\n items.reverse()\n np.random.shuffle(items)\n\n with tf.io.TFRecordWriter(\"helmet_train.tfrecord\") as writer:\n for i in range(len(items) - 800):\n item = items[i]\n sample = build_sample(item[0], item[1])\n writer.write(sample.SerializeToString())\n\n with tf.io.TFRecordWriter(\"helmet_valid.tfrecord\") as writer:\n for i in range(len(items) - 800, len(items)):\n item = items[i]\n sample = build_sample(item[0], item[1])\n writer.write(sample.SerializeToString())\n\n\nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"tensorflow.train.BytesList",
"tensorflow.train.FloatList",
"tensorflow.train.Int64List",
"numpy.random.shuffle",
"tensorflow.io.TFRecordWriter"
]
]
|
ishaan27chaturvedi/Frozen-Lake | [
"7664ad8474fe502e8313b90333036fae2475b53e"
]
| [
"Environment.py"
]
| [
"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport random\nfrom itertools import product\nimport contextlib\n\n\n# ### Defining Print Options\n\n# In[2]:\n\n\n# Configures numpy print options\[email protected]\ndef _printoptions(*args, **kwargs):\n original = np.get_printoptions()\n np.set_printoptions(*args, **kwargs)\n try:\n yield\n finally:\n np.set_printoptions(**original)\n\n\n# # Enviornment Model Class\n\n# In[4]:\n\n\nclass EnvironmentModel:\n def __init__(self, n_states, n_actions, seed=None):\n self.n_states = n_states\n self.n_actions = n_actions\n\n self.random_state = np.random.RandomState(seed)\n\n def p(self, next_state, state, action):\n raise NotImplementedError()\n\n def r(self, next_state, state, action):\n raise NotImplementedError()\n\n def draw(self, state, action):\n p = [self.p(ns, state, action) for ns in range(self.n_states)]\n next_state = self.random_state.choice(self.n_states, p=p)\n reward = self.r(next_state, state, action)\n\n return next_state, reward\n\n\n# # Environment Class\n\n# In[5]:\n\n\nclass Environment(EnvironmentModel):\n def __init__(self, n_states, n_actions, max_steps, pi, seed=None):\n EnvironmentModel.__init__(self, n_states, n_actions, seed)\n\n self.max_steps = max_steps\n\n self.pi = pi\n if self.pi is None:\n self.pi = np.full(n_states, 1. / n_states)\n\n def reset(self):\n self.n_steps = 0\n self.state = self.random_state.choice(self.n_states, p=self.pi)\n\n return self.state\n\n def step(self, action):\n if action < 0 or action >= self.n_actions:\n raise Exception('Invalid action.')\n\n self.n_steps += 1\n done = (self.n_steps >= self.max_steps)\n\n self.state, reward = self.draw(self.state, action)\n\n return self.state, reward, done\n\n def render(self, policy=None, value=None):\n raise NotImplementedError()\n\n\n# # Frozen Lake Environment Class\n\n# In[6]:\n\n\nclass FrozenLake(Environment):\n def __init__(self, lake, slip, max_steps, seed=None):\n \"\"\"\n lake: A matrix that represents the lake. For example:\n lake = [['&', '.', '.', '.'],\n ['.', '#', '.', '#'],\n ['.', '.', '.', '#'],\n ['#', '.', '.', '$']]\n slip: The probability that the agent will slip\n max_steps: The maximum number of time steps in an episode\n seed: A seed to control the random number generator (optional)\n \"\"\"\n\n # start (&), frozen (.), hole (#), goal ($)\n self.lake = np.array(lake)\n self.lake_flat = self.lake.reshape(-1)\n\n self.slip = slip # parameterizable slip probability, initially 0.1\n\n n_states = self.lake.size + 1 # + 1 to include the absorption state\n n_actions = 4\n\n pi = np.zeros(n_states, dtype=float) # initial p\n pi[np.where(self.lake_flat == '&')[0]] = 1.0 # setting start state p to 1\n\n self.absorbing_state = n_states - 1 # set to 16 - outside lake_flat, ranging from 0-15\n print(self.absorbing_state)\n # Initializing environment\n Environment.__init__(self, n_states, n_actions, max_steps, pi, seed)\n\n # Up, down, left, right\n self.actions = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n #up, left, down, and right.\n #self.actions = [(-1, 0), (0, -1), (1, 0), (0, 1)]\n\n self.transition_probas = np.zeros((self.n_states, self.n_states, self.n_actions))\n #Iterate over all combinations\n self.all_states = list(product(range(self.lake.shape[0]), range(self.lake.shape[1])))\n for state_index in range(n_states):\n for other_state_index in range(n_states):\n for action_index, action in enumerate(self.actions):\n \n if state_index != self.absorbing_state:\n character = self.lake_flat[state_index]\n \n if character == '$' or character == '#':\n if other_state_index == self.absorbing_state:\n self.transition_probas[other_state_index, state_index, action_index]=1.0\n \n elif character != '$' and character != '#': \n \n if other_state_index != self.absorbing_state: \n \n state = self.all_states[state_index]\n other_state = self.all_states[other_state_index]\n if self.apply_action(state,action) == other_state:\n self.transition_probas[other_state_index, state_index, action_index]=1.0 - self.slip\n \n\n self.transition_probas[other_state_index, state_index, action_index]+= self.slip_multiplyer(other_state,state)*(self.slip/n_actions)\n \n if state_index == self.absorbing_state and other_state_index == self.absorbing_state:\n self.transition_probas[other_state_index, state_index, action_index]=1.0\n\n \n def apply_action(self,state,action):\n new_state = (state[0]+action[0],state[1]+action[1])\n if self.valid_state(new_state):\n return new_state\n return state\n\n \n def valid_state(self, state):\n if state[0] >= 0 and state[0] <self.lake.shape[0] and state[1] >= 0 and state[1] <self.lake.shape[1]:\n return True\n return False\n \n\n def slip_multiplyer(self,state,goal_state):\n count = 0\n for action in self.actions:\n if self.apply_action(state,action) == goal_state:\n count+=1\n return count\n \n def get_index(self, state):\n return state[0]*self.lake.shape[0] + state[1]\n \n \n def step(self, action):\n state, reward, done = Environment.step(self, action) # else, transition normally\n done = (state == self.absorbing_state) or done\n return state, reward, done\n\n\n def p(self, next_state, state, action):\n #return self.transition_probas[state, next_state, action]\n return self.transition_probas[next_state, state, action]\n \n \n def r(self, next_state, state, action):\n # if within env boundaries\n if(state < self.n_states-1):\n if self.lake_flat[state] == '$': # get char of state in environment\n return 1\n return 0\n\n\n def render(self, policy=None, value=None):\n if policy is None:\n lake = np.array(self.lake_flat)\n\n if self.state < self.absorbing_state:\n lake[self.state] = '@'\n\n print(lake.reshape(self.lake.shape))\n else:\n # UTF-8 arrows look nicer, but cannot be used in LaTeX\n # https://www.w3schools.com/charsets/ref_utf_arrows.asp\n actions = ['↑', '↓', '←', '→']\n\n print('Lake:')\n print(self.lake)\n\n print('Policy:')\n policy = np.array([actions[a] for a in policy[:-1]])\n print(policy.reshape(self.lake.shape))\n\n print('Value:')\n with _printoptions(precision=3, suppress=True):\n print(value[:-1].reshape(self.lake.shape))\n\n\n def play(self):\n actions = ['w', 's', 'a', 'd']\n\n state = self.reset()\n self.render()\n\n done = False\n while not done:\n c = input('\\nMove: ')\n if c not in actions:\n raise Exception('Invalid action')\n\n state, r, done = self.step(actions.index(c))\n\n self.render()\n print('Reward: {0}.'.format(r))\n\n\n# ## Small and Big Lakes\n\n# In[7]:\n\n\nseed = 0\n\nsmall_lake = [['&', '.', '.', '.'],\n ['.', '#', '.', '#'],\n ['.', '.', '.', '#'],\n ['#', '.', '.', '$']]\n\nbig_lake = [['&', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '#', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '#', '.', '.'],\n ['.', '.', '.', '#', '.', '.', '.', '.'],\n ['.', '#', '#', '.', '.', '.', '#', '.'],\n ['.', '#', '.', '.', '#', '.', '#', '.'],\n ['.', '.', '.', '#', '.', '.', '.', '$']]\n\n\n# ### Play on small lake\n\n# In[8]:\n\n\nlake = small_lake\nsize = len(lake) * len(lake[0])\nenv = FrozenLake(lake, slip=0.1, max_steps=size, seed=seed)\n\n#env.play()\n\n\n# ### Play on Big lake\n\n# In[10]:\n\n\n#lake = big_lake\n#size = len(lake) * len(lake[0])\n#env = FrozenLake(lake, slip=0.1, max_steps=size, seed=seed)\n\n#env.play()\n\n\n# In[ ]:\n\n\n\n\n"
]
| [
[
"numpy.full",
"numpy.array",
"numpy.zeros",
"numpy.random.RandomState",
"numpy.set_printoptions",
"numpy.get_printoptions",
"numpy.where"
]
]
|
gcunhase/tensorflow-onnx | [
"8a61c99fbc39c36d70781f95e2c7c582f46ba2db",
"8a61c99fbc39c36d70781f95e2c7c582f46ba2db"
]
| [
"tf2onnx/tflite_utils.py",
"tf2onnx/tflite_handlers/tfl_math.py"
]
| [
"# SPDX-License-Identifier: Apache-2.0\n\n\n\"\"\"\ntf2onnx.tflite_utils - utilities for parsing tflite files into onnx graph\n\"\"\"\n\nimport collections\nimport importlib\nimport logging\nimport struct\n\nfrom onnx import helper, onnx_pb, numpy_helper\nfrom tensorflow.core.framework import types_pb2, tensor_pb2, node_def_pb2\nfrom tensorflow.python.framework import tensor_util\nimport tensorflow as tf\nimport numpy as np\nfrom tf2onnx.tflite.TensorType import TensorType as TFLiteTensorType\nfrom tf2onnx.tflite.Model import Model\nfrom tf2onnx.flexbuffers import read_flexbuffer\nfrom tf2onnx.tf_utils import read_tf_node_def_attrs\nfrom tf2onnx import utils\n\nlogger = logging.getLogger(__name__)\n\nTFLITE_TO_ONNX_DTYPE = {\n TFLiteTensorType.FLOAT32: onnx_pb.TensorProto.FLOAT,\n TFLiteTensorType.FLOAT16: onnx_pb.TensorProto.FLOAT16,\n TFLiteTensorType.INT32: onnx_pb.TensorProto.INT32,\n TFLiteTensorType.UINT8: onnx_pb.TensorProto.UINT8,\n TFLiteTensorType.INT64: onnx_pb.TensorProto.INT64,\n TFLiteTensorType.STRING: onnx_pb.TensorProto.STRING,\n TFLiteTensorType.BOOL: onnx_pb.TensorProto.BOOL,\n TFLiteTensorType.INT16: onnx_pb.TensorProto.INT16,\n TFLiteTensorType.COMPLEX64: onnx_pb.TensorProto.COMPLEX64,\n TFLiteTensorType.INT8: onnx_pb.TensorProto.INT8,\n TFLiteTensorType.FLOAT64: onnx_pb.TensorProto.DOUBLE,\n TFLiteTensorType.COMPLEX128: onnx_pb.TensorProto.COMPLEX128,\n TFLiteTensorType.UINT64: onnx_pb.TensorProto.UINT64,\n TFLiteTensorType.UINT32: onnx_pb.TensorProto.UINT32,\n TFLiteTensorType.RESOURCE: onnx_pb.TensorProto.UNDEFINED,\n TFLiteTensorType.VARIANT: onnx_pb.TensorProto.UNDEFINED,\n}\n\n\nTFLITE_TO_TF_DTYPE = {\n TFLiteTensorType.FLOAT32: types_pb2.DT_FLOAT,\n TFLiteTensorType.FLOAT16: types_pb2.DT_HALF,\n TFLiteTensorType.INT32: types_pb2.DT_INT32,\n TFLiteTensorType.UINT8: types_pb2.DT_UINT8,\n TFLiteTensorType.INT64: types_pb2.DT_INT64,\n TFLiteTensorType.STRING: types_pb2.DT_STRING,\n TFLiteTensorType.BOOL: types_pb2.DT_BOOL,\n TFLiteTensorType.INT16: types_pb2.DT_INT16,\n TFLiteTensorType.COMPLEX64: types_pb2.DT_COMPLEX64,\n TFLiteTensorType.INT8: types_pb2.DT_INT8,\n TFLiteTensorType.FLOAT64: types_pb2.DT_DOUBLE,\n TFLiteTensorType.COMPLEX128: types_pb2.DT_COMPLEX128,\n TFLiteTensorType.UINT64: types_pb2.DT_UINT64,\n TFLiteTensorType.UINT32: types_pb2.DT_UINT32,\n TFLiteTensorType.RESOURCE: types_pb2.DT_RESOURCE,\n TFLiteTensorType.VARIANT: types_pb2.DT_VARIANT,\n}\n\n\ndef map_tflite_dtype_to_onnx(dtype):\n return TFLITE_TO_ONNX_DTYPE[dtype]\n\n\ndef map_tflite_dtype_to_tf(dtype):\n return TFLITE_TO_TF_DTYPE[dtype]\n\n\n# The tflite schema uses snake case, but the python bindings use proper case\ndef snake_to_proper_case(name):\n return ''.join(n.capitalize() for n in name.split('_'))\n\n\ndef proper_to_snake_case(name):\n res = ''\n for c in name:\n if c.isupper() and res:\n res += '_'\n res += c.lower()\n return res\n\n# Pulled from the tflite schema.fbs file. Needed to decode enum numbers into strings.\nNODE_ATTR_NAME_TO_ENUM_TYPE = {\n 'fused_activation_function': 'ActivationFunctionType',\n 'padding': 'Padding',\n 'type': 'LSHProjectionType',\n 'weights_format': 'FullyConnectedOptionsWeightsFormat',\n 'kernel_type': 'LSTMKernelType',\n 'combiner': 'CombinerType',\n 'in_data_type': 'TensorType',\n 'out_data_type': 'TensorType',\n 'output_type': 'TensorType',\n 'out_type': 'TensorType',\n 'mode': 'MirrorPadMode',\n 'idx_out_type': 'TensorType',\n}\nNODE_ATTR_NAME_TO_ENUM_TYPE = {snake_to_proper_case(key): value for key, value in NODE_ATTR_NAME_TO_ENUM_TYPE.items()}\n\n# Pulled from the tflite schema.fbs file.\nFUNCTION_ATTRS = ['then_subgraph_index', 'else_subgraph_index', 'cond_subgraph_index',\n 'body_subgraph_index', 'subgraph']\nFUNCTION_ATTRS = [snake_to_proper_case(attr) for attr in FUNCTION_ATTRS]\n\n\nenum_cache = {}\ndef lookup_enum(idx, enum_name):\n \"\"\"Given the name of a tflite enum class and an index, return a string with the name of the enum value\"\"\"\n if enum_name == 'TensorType':\n return map_tflite_dtype_to_onnx(idx)\n if enum_name in enum_cache:\n return enum_cache[enum_name][idx]\n module = importlib.import_module('tf2onnx.tflite.' + enum_name)\n enum_class = getattr(module, enum_name)\n idx_to_name = {value: key for key, value in enum_class.__dict__.items() if not key.startswith('_')}\n enum_cache[enum_name] = idx_to_name\n return idx_to_name[idx]\n\n\ndef get_options_class(name):\n \"\"\"Each tflite optype has a flatbuffer Options class (ex: AddOptions). Returns the options class given its name.\"\"\"\n if name == \"NONE\":\n return None\n module = importlib.import_module('tf2onnx.tflite.' + name)\n return getattr(module, name)\n\n\ndef read_tflite_model(tflite_path):\n \"\"\"\n Given the path to a tflite model, returns tuple (tflite_graphs, opcodes_map, model)\n Graphs are topologically sorted and the main graph is last\n Pass these to parse_tflite_graph\n \"\"\"\n with open(tflite_path, 'rb') as f:\n buf = f.read()\n buf = bytearray(buf)\n model = Model.GetRootAsModel(buf, 0)\n # To save space, each op in the model indicates its opcode as an index into the model's opcode map.\n opcodes_map = {}\n for i in range(model.OperatorCodesLength()):\n op_code = model.OperatorCodes(i)\n # TFlite ran out of opcodes since they only used a byte. Old models store opcodes in DeprecatedBuiltinCode.\n # New models put PLACEHOLDER_FOR_GREATER_OP_CODES in this field to signify that BuiltinCode should be used.\n code = lookup_enum(op_code.DeprecatedBuiltinCode(), 'BuiltinOperator')\n if code == 'PLACEHOLDER_FOR_GREATER_OP_CODES':\n code = lookup_enum(op_code.BuiltinCode(), 'BuiltinOperator')\n if code == 'CUSTOM':\n code = op_code.CustomCode().decode()\n opcodes_map[i] = code\n # Shapes stored in tflite models are not always reliable so we get them from the interpreter if possible.\n tensor_shapes = {}\n try:\n interpreter = tf.lite.Interpreter(tflite_path)\n interpreter.allocate_tensors()\n tensor_cnt = model.Subgraphs(0).TensorsLength()\n for i in range(tensor_cnt):\n name = model.Subgraphs(0).Tensors(i).Name().decode()\n details = interpreter._get_tensor_details(i) # pylint: disable=protected-access\n if \"shape_signature\" in details:\n tensor_shapes[name] = details[\"shape_signature\"].tolist()\n elif \"shape\" in details:\n tensor_shapes[name] = details[\"shape\"].tolist()\n except Exception as e: # pylint: disable=broad-except\n logger.warning(\"Error loading model into tflite interpreter: %s\", e)\n tflite_graphs = get_model_subgraphs(model)\n return tflite_graphs, opcodes_map, model, tensor_shapes\n\n\ndef get_subgraph_dependencies(model, graph_idx):\n \"\"\"Returns a list of subgraph indices referenced by the indicated graph\"\"\"\n dependencies = []\n g = model.Subgraphs(graph_idx)\n for i in range(g.OperatorsLength()):\n op = g.Operators(i)\n options_type_name = lookup_enum(op.BuiltinOptionsType(), 'BuiltinOptions')\n option_class = get_options_class(options_type_name)\n if option_class is not None:\n options = option_class()\n options.Init(op.BuiltinOptions().Bytes, op.BuiltinOptions().Pos)\n for attr in FUNCTION_ATTRS:\n if hasattr(options, attr):\n value = getattr(options, attr)()\n dependencies.append(value)\n return dependencies\n\n\ndef get_model_subgraphs(model):\n \"\"\"Returns topologically sorted subgraphs of a model. Guarantees main graph is placed at the end.\"\"\"\n main_g = 0\n dependencies = {}\n idx_to_graph = {}\n for i in range(model.SubgraphsLength()):\n idx_to_graph[i] = model.Subgraphs(i)\n ds = get_subgraph_dependencies(model, i)\n utils.make_sure(main_g not in ds, \"Main graph %s is a dependency of subgraph %s\", main_g, i)\n dependencies[i] = ds\n\n ordered = []\n visited = set()\n visiting = set()\n def visit(g):\n utils.make_sure(g not in visiting, \"Subgraphs have cyclic dependencies: %r\", dependencies)\n if g in visited:\n return\n visiting.add(g)\n for d in dependencies[g]:\n visit(d)\n visited.add(g)\n ordered.append(g)\n visiting.remove(g)\n\n for g in reversed(range(model.SubgraphsLength())):\n visit(g)\n\n return [idx_to_graph[i] for i in ordered]\n\n\ndef get_quantization_attr(quant_params):\n attr = {}\n attr['scale'] = quant_params.ScaleAsNumpy().tolist()\n attr['zero_point'] = quant_params.ZeroPointAsNumpy().tolist()\n attr['quantized_dimension'] = quant_params.QuantizedDimension()\n if not quant_params.MaxIsNone():\n attr['max'] = quant_params.MaxAsNumpy().tolist()\n if not quant_params.MinIsNone():\n attr['min'] = quant_params.MinAsNumpy().tolist()\n return attr\n\n\ndef parse_tflite_string_tensor(buffer_bytes, shape):\n \"\"\"Returns an onnx tensor with the string data encoded in the tflite tensor data buffer\"\"\"\n def read_int(offset):\n return struct.unpack('<i', buffer_bytes[offset:offset+4])[0]\n offset = 0\n count = read_int(offset)\n offset += 4\n offset_list = []\n for i in range(count):\n offset_list.append(read_int(offset))\n offset += 4\n offset_list.append(len(buffer_bytes))\n string_list = []\n for i in range(count):\n string_list.append(buffer_bytes[offset_list[i]:offset_list[i+1]].decode(\"utf-8\"))\n return numpy_helper.from_array(np.array(string_list, dtype=np.object).reshape(shape))\n\n\ndef op_has_scalar_output(input_shapes, optype, attr):\n \"\"\"\n TFLite uses [] to denote both scalars and unknown output shapes. Return True if an op can have scalar outputs\n despite having non-scalar inputs. Otherwise, we will replace [] with None\n \"\"\"\n if optype in [\"TFL_STRIDED_SLICE\", \"StridedSlice\"]:\n inp_rank = len(input_shapes[0])\n return attr['shrink_axis_mask'] == 2 ** inp_rank - 1\n if (optype.startswith(\"TFL_REDUCE\") or optype in ['All']) and len(input_shapes) == 2:\n inp_rank = len(input_shapes[0])\n keep_dims = attr.get('keep_dims', True)\n # axes input can be a scalar for a single axis\n num_axes = 1 if input_shapes[1] == [] else input_shapes[1][0]\n return not keep_dims and inp_rank == num_axes\n if optype == \"TFL_RESHAPE\":\n return input_shapes[1] == [0]\n if optype == \"Size\":\n # Op from TF\n return True\n return False\n\n\ndef parse_tflite_graph(tflite_g, opcodes_map, model, input_prefix='', tensor_shapes_override=None):\n \"\"\"\n Returns a Graph object along with some op count stats. All tflite op types are prefixed with \"TFL_\".\n Names of graph inputs are optionally prefixed with a string to prevent name conflicts in subgraphs.\n Quantizatized tensors are surrounded with quantize/dequantize ops\n \"\"\"\n op_cnt = collections.Counter()\n attr_cnt = collections.Counter()\n onnx_nodes = []\n output_shapes = {}\n dtypes = {}\n tensor_names = {}\n if tensor_shapes_override is None:\n tensor_shapes_override = {}\n # Map tensor name to tflite Tensor object so we can fetch quantization info as needed\n name_to_tensor = {}\n # If a node takes a quantized tensor as input, we must add a dequantize op after it.\n # Store a mapping so we only need to make at most one dequantize op per tensor.\n tensor_name_to_dequant_output = {}\n\n # tflite uses generic names (arg0, arg1, etc.) for inputs but full names for other tensors, so\n # prefixing just the inputs should be fine. Other tensors are prefixed when we do inlining.\n input_indices = {tflite_g.Inputs(i) for i in range(tflite_g.InputsLength())}\n\n for i in range(tflite_g.TensorsLength()):\n tensor = tflite_g.Tensors(i)\n name = tensor.Name().decode()\n if i in input_indices:\n name = input_prefix + name\n tensor_names[i] = name\n name_to_tensor[name] = tensor\n\n if name in tensor_shapes_override:\n output_shapes[name] = tensor_shapes_override[name]\n elif tensor.ShapeIsNone():\n output_shapes[name] = None\n elif tensor.ShapeSignatureIsNone():\n # The shape signature uses -1 to signify unknown dims. Old models don't have this and use Shape instead.\n output_shapes[name] = tensor.ShapeAsNumpy().tolist()\n else:\n output_shapes[name] = tensor.ShapeSignatureAsNumpy().tolist()\n buf = model.Buffers(tensor.Buffer())\n dtypes[name] = map_tflite_dtype_to_onnx(tensor.Type())\n if not buf.DataIsNone() and tensor.Buffer() > 0:\n # For const values we use TF to decode the binary data from the buffer\n t = tensor_pb2.TensorProto()\n t.tensor_content = buf.DataAsNumpy().tobytes()\n if output_shapes[name] is None:\n output_shapes[name] = []\n for d in output_shapes[name]:\n t.tensor_shape.dim.add().size = d\n t.dtype = map_tflite_dtype_to_tf(tensor.Type())\n if t.dtype == tf.string:\n onnx_tensor = parse_tflite_string_tensor(t.tensor_content, output_shapes[name])\n else:\n np_data = tensor_util.MakeNdarray(t)\n onnx_tensor = numpy_helper.from_array(np_data, name=name)\n onnx_node = helper.make_node(\"Const\", [], outputs=[name], name=name, value=onnx_tensor)\n onnx_nodes.append(onnx_node)\n op_cnt[\"Const\"] += 1\n\n def get_dequant(tensor_name):\n \"\"\"Creates a dequantize op for the provided tensor if needed and returns the output of the op, or\n the original tensor name if no dequantization is needed\"\"\"\n quant = name_to_tensor[tensor_name].Quantization()\n if quant is None or quant.ScaleIsNone() or quant.ZeroPointIsNone():\n return tensor_name\n if tensor_name in tensor_name_to_dequant_output:\n return tensor_name_to_dequant_output[tensor_name]\n dequant_name = tensor_name + \"_dequant\"\n attr = get_quantization_attr(quant)\n onnx_node = helper.make_node(\"TFL_DEQUANTIZE\", [tensor_name], [dequant_name], name=dequant_name, **attr)\n onnx_nodes.append(onnx_node)\n tensor_name_to_dequant_output[tensor_name] = dequant_name\n output_shapes[dequant_name] = output_shapes[tensor_name].copy()\n dtypes[dequant_name] = onnx_pb.TensorProto.FLOAT\n return dequant_name\n\n def get_prequant(tensor_name):\n \"\"\"Called by nodes with the name of the tensor they must output.\n If the output is supposed to be quantized, creates a Quantize op outputting the tensor.\n Returns the name that should be used for the \"prequantized\" tensor, or the original tensor if no quantization\n is needed\"\"\"\n quant = name_to_tensor[tensor_name].Quantization()\n if quant is None or quant.ScaleIsNone() or quant.ZeroPointIsNone():\n return tensor_name\n prequant_name = tensor_name + \"_prequant\"\n quantize_name = tensor_name + \"_quantize\"\n attr = get_quantization_attr(quant)\n onnx_node = helper.make_node(\"TFL_QUANTIZE\", [prequant_name], [tensor_name], name=quantize_name, **attr)\n onnx_nodes.append(onnx_node)\n output_shapes[prequant_name] = output_shapes[tensor_name].copy()\n dtypes[prequant_name] = onnx_pb.TensorProto.FLOAT\n return prequant_name\n\n for i in range(tflite_g.OperatorsLength()):\n op = tflite_g.Operators(i)\n optype = 'TFL_' + opcodes_map[op.OpcodeIndex()]\n op_cnt[optype] += 1\n attr = {}\n options_type_name = lookup_enum(op.BuiltinOptionsType(), 'BuiltinOptions')\n option_class = get_options_class(options_type_name)\n wants_dequantized_input = True\n has_prequantized_output = True\n if optype == 'TFL_QUANTIZE':\n out_tensor = tflite_g.Tensors(op.Outputs(0))\n quant = out_tensor.Quantization()\n has_prequantized_output = False\n if quant is not None and not quant.ScaleIsNone() and not quant.ZeroPointIsNone():\n attr.update(get_quantization_attr(quant))\n elif optype == 'TFL_DEQUANTIZE':\n in_tensor = tflite_g.Tensors(op.Inputs(0))\n quant = in_tensor.Quantization()\n wants_dequantized_input = False\n if quant is not None and not quant.ScaleIsNone() and not quant.ZeroPointIsNone():\n attr.update(get_quantization_attr(quant))\n input_names = [tensor_names[op.Inputs(i)] for i in range(op.InputsLength()) if op.Inputs(i) != -1]\n output_names = [tensor_names[op.Outputs(i)] for i in range(op.OutputsLength()) if op.Outputs(i) != -1]\n if optype.startswith(\"TFL_Flex\"):\n data = read_flexbuffer(op.CustomOptionsAsNumpy().tobytes(), decode_strings=False)\n utils.make_sure(isinstance(data, list), \"Flex ops are expected to store data as a flexbuffer list\")\n tf_op = data[0].decode(\"utf-8\")\n tf_node_def = node_def_pb2.NodeDef()\n tf_node_def.ParseFromString(data[1])\n input_tf_dtypes = [map_tflite_dtype_to_tf(name_to_tensor[inp].Type()) for inp in input_names]\n def shape_to_tf_shape(dims):\n return [None if d < 0 else d for d in dims] if dims is not None else None\n input_shapes = [shape_to_tf_shape(output_shapes[inp]) for inp in input_names]\n tf_attrs, _ = read_tf_node_def_attrs(tf_node_def, input_tf_dtypes, input_shapes)\n attr.update(tf_attrs)\n optype = tf_op\n elif not op.CustomOptionsIsNone():\n custom_ops_format = lookup_enum(op.CustomOptionsFormat(), 'CustomOptionsFormat')\n if custom_ops_format == 'FLEXBUFFERS':\n data = None\n try:\n data = read_flexbuffer(op.CustomOptionsAsNumpy().tobytes())\n except Exception as e: # pylint: disable=broad-except\n logger.warning(\"Could not parse attributes for custom op '%s': %s\", optype, e)\n if isinstance(data, dict):\n attr.update(data)\n if option_class is not None:\n options = option_class()\n options.Init(op.BuiltinOptions().Bytes, op.BuiltinOptions().Pos)\n # All flatbuffer objects have these properties.\n block_list = [options_type_name + 'BufferHasIdentifier', 'Init', 'GetRootAs' + options_type_name]\n # The rest of the properties of the options class provide its attribute names\n attr_names = {opt for opt in dir(options) if not opt.startswith('_') and opt not in block_list}\n for a in list(attr_names):\n # Flatbufffer list properties have 3 functions: *Length, *IsNone, and *AsNumpy\n if a + 'Length' in attr_names:\n attr_names.remove(a + 'Length')\n attr_names.remove(a + 'IsNone')\n attr_names.remove(a)\n for a in attr_names:\n if a.endswith('AsNumpy'):\n value = getattr(options, a)().tolist()\n a = a[:-len('AsNumpy')]\n else:\n # For enums we use a string with the value name, not enum index\n value = getattr(options, a)()\n if a in NODE_ATTR_NAME_TO_ENUM_TYPE:\n value = lookup_enum(value, NODE_ATTR_NAME_TO_ENUM_TYPE[a])\n elif a in FUNCTION_ATTRS:\n value = model.Subgraphs(value).Name().decode()\n attr_cnt[a] += 1\n attr[proper_to_snake_case(a)] = value\n if wants_dequantized_input:\n input_names = [get_dequant(inp) for inp in input_names]\n if optype == \"TFL_TFLite_Detection_PostProcess\":\n # There's a bug in tflite for the output shapes of this op\n for out, shape in zip(output_names, [[-1, -1, 4], [-1, -1], [-1, -1], [-1]]):\n if len(output_shapes[out]) != len(shape):\n output_shapes[out] = shape\n if all(output_shapes[out] == [] for out in output_names):\n # tflite uses [] to represent both scalars and completely unknown shapes\n # If an op has non-scalar inputs and all scalar outputs, it is very likely the shapes are actually unknown.\n inp_shapes = [output_shapes[inp] for inp in input_names]\n if not all(s == [] for s in inp_shapes):\n if any(s is None for s in inp_shapes) or not op_has_scalar_output(inp_shapes, optype, attr):\n for out in output_names:\n logger.warning(\"Replacing scalar output shape of %s with unknown shape\", out)\n output_shapes[out] = None\n if has_prequantized_output:\n output_names = [get_prequant(out) for out in output_names]\n onnx_node = helper.make_node(optype, input_names, output_names, name=output_names[0], **attr)\n onnx_nodes.append(onnx_node)\n\n inputs = [tensor_names[tflite_g.Inputs(i)] for i in range(tflite_g.InputsLength())]\n outputs = [tensor_names[tflite_g.Outputs(i)] for i in range(tflite_g.OutputsLength())]\n # TODO: Allow input/outputs to be overridden\n\n for inp in inputs:\n onnx_node = helper.make_node(\"Placeholder\", [], outputs=[inp], name=inp)\n onnx_nodes.append(onnx_node)\n\n graph_name = (tflite_g.Name() or b'tflite graph').decode()\n return onnx_nodes, op_cnt, attr_cnt, output_shapes, dtypes, inputs, outputs, graph_name\n",
"# SPDX-License-Identifier: Apache-2.0\n\n\n\"\"\"\ntfl_math\n\"\"\"\n\nimport logging\nimport numpy as np\nfrom onnx.onnx_pb import TensorProto\nfrom tf2onnx.handler import tfl_op\nfrom tf2onnx import utils\n\nlogger = logging.getLogger(__name__)\n\n\n# pylint: disable=unused-argument,missing-docstring,unused-variable,pointless-string-statement,invalid-name\n\n\ndef separate_fused_activation_function(ctx, node):\n activation_fn = node.attr['fused_activation_function'].s\n del node.attr['fused_activation_function']\n if activation_fn == b'RELU':\n ctx.insert_new_node_on_output(\"Relu\", node.output[0])\n elif activation_fn == b'RELU6':\n # This is a TF op. We will convert it on the 2nd pass.\n shape = ctx.get_shape(node.output[0])\n dtype = ctx.get_dtype(node.output[0])\n new_node = ctx.make_node(\"Relu6\", [node.output[0]], skip_conversion=False, shapes=[shape], dtypes=[dtype])\n ctx.insert_node_on_output(new_node, node.output[0])\n elif activation_fn == b'TANH':\n ctx.insert_new_node_on_output(\"Tanh\", node.output[0])\n else:\n # TODO: SIGN_BIT and RELU_N1_TO_1 not supported yet\n utils.make_sure(activation_fn == b'NONE', \"Unsupported fused activation function %s on node %s\",\n activation_fn, node.name)\n\n@tfl_op([\"TFL_ADD\"], tf_op=\"Add\")\nclass TflAdd:\n @classmethod\n def to_tf(cls, ctx, node, **kwargs):\n separate_fused_activation_function(ctx, node)\n\n@tfl_op([\"TFL_SUB\"], tf_op=\"Sub\")\nclass TflSub:\n @classmethod\n def to_tf(cls, ctx, node, **kwargs):\n separate_fused_activation_function(ctx, node)\n\n@tfl_op([\"TFL_MUL\"], tf_op=\"Mul\")\nclass TflMul:\n @classmethod\n def to_tf(cls, ctx, node, **kwargs):\n separate_fused_activation_function(ctx, node)\n\n@tfl_op([\"TFL_DIV\"], tf_op=\"Div\")\nclass TflDiv:\n @classmethod\n def to_tf(cls, ctx, node, **kwargs):\n separate_fused_activation_function(ctx, node)\n\n@tfl_op([\"TFL_LOGISTIC\"], tf_op=\"Sigmoid\")\nclass TflLogistic:\n @classmethod\n def to_tf(cls, ctx, node, **kwargs):\n pass\n\n@tfl_op([\"TFL_REDUCE_MAX\"], tf_op=\"Max\")\n@tfl_op([\"TFL_REDUCE_MIN\"], tf_op=\"Min\")\n@tfl_op([\"TFL_REDUCE_ANY\"], tf_op=\"Any\")\n@tfl_op([\"TFL_REDUCE_PROD\"], tf_op=\"Prod\")\nclass TflReduceOp:\n @classmethod\n def to_tf(cls, ctx, node, **kwargs):\n pass\n\n@tfl_op([\"TFL_LOCAL_RESPONSE_NORMALIZATION\"], tf_op=\"LRN\")\nclass TFlLocalResponseNormalizationOp:\n @classmethod\n def to_tf(cls, ctx, node, **kwargs):\n node.attr[\"depth_radius\"] = node.attr[\"radius\"]\n del node.attr[\"radius\"]\n\n@tfl_op([\"TFL_RANGE\"], tf_op=\"Range\")\nclass TflRangeOp:\n @classmethod\n def to_tf(cls, ctx, node, **kwargs):\n node.set_attr(\"Tidx\", ctx.get_dtype(node.output[0]))\n\n@tfl_op([\"TFL_QUANTIZE\"], onnx_op=\"QuantizeLinear\")\nclass TflQuantizeOp:\n @classmethod\n def version_1(cls, ctx, node, dequantize=False, **kwargs):\n # We could just let the TFL_QUANTIZE fall through as an unconverted op, but they are added programmatically\n # so that might be confusing.\n raise ValueError(\"Opset 10 is required for quantization. Consider using the --dequantize flag or --opset 10.\")\n\n @classmethod\n def version_10(cls, ctx, node, **kwargs):\n scale = node.get_attr_value('scale')\n zero_point = node.get_attr_value('zero_point')\n axis = node.get_attr_value('quantized_dimension')\n np_q_type = utils.map_onnx_to_numpy_type(ctx.get_dtype(node.output[0]))\n if len(scale) > 1 or len(zero_point) > 1:\n utils.make_sure(ctx.opset >= 13, \"Opset 13 is required for per-axis quantization for node %s\", node.name)\n node.set_attr(\"axis\", axis)\n scale_node = ctx.make_const(utils.make_name(\"scale\"), np.array(scale[0], dtype=np.float32))\n zero_point_node = ctx.make_const(utils.make_name(\"zero_point\"), np.array(zero_point[0], dtype=np_q_type))\n ctx.replace_inputs(node, [node.input[0], scale_node.output[0], zero_point_node.output[0]])\n del node.attr[\"scale\"]\n del node.attr[\"zero_point\"]\n del node.attr[\"quantized_dimension\"]\n if \"min\" in node.attr:\n del node.attr[\"min\"]\n if \"max\" in node.attr:\n del node.attr[\"max\"]\n\n@tfl_op([\"TFL_DEQUANTIZE\"], onnx_op=\"DequantizeLinear\")\nclass TflDequantizeOp:\n @classmethod\n def version_1(cls, ctx, node, **kwargs):\n if 'scale' not in node.attr:\n # Somtimes tflite uses a Dequantize to go from fp16 to fp32\n node.type = \"Cast\"\n node.set_attr('to', ctx.get_dtype(node.output[0]))\n return\n scale = np.array(node.get_attr_value('scale'), dtype=np.float32)\n zero_point = np.array(node.get_attr_value('zero_point'), dtype=np.float32)\n axis = node.get_attr_value('quantized_dimension')\n in_rank = ctx.get_rank(node.input[0])\n def expand_tensor(t):\n if t.shape == (1,):\n return t[0]\n utils.make_sure(in_rank is not None, \"Cannot dequantize node %s with unknown input rank\", node.name)\n new_shape = [1] * in_rank\n new_shape[axis] = t.shape[0]\n return t.reshape(new_shape)\n scale = expand_tensor(scale)\n zero_point = expand_tensor(zero_point)\n if node.inputs[0].is_const():\n x_val = node.inputs[0].get_tensor_value(as_list=False).astype(np.float32)\n new_val = (x_val - zero_point) * scale\n dequant_const = ctx.make_const(utils.make_name(node.name), new_val)\n ctx.replace_all_inputs(node.output[0], dequant_const.output[0])\n ctx.remove_node(node.name)\n else:\n scale_const = ctx.make_const(utils.make_name(node.name + \"_scale\"), scale).output[0]\n zero_point_const = ctx.make_const(utils.make_name(node.name + \"_zero_point\"), zero_point).output[0]\n cast_node = ctx.make_node(\"Cast\", [node.input[0]], attr={'to': TensorProto.FLOAT},\n op_name_scope=node.name).output[0]\n sub_node = ctx.make_node(\"Sub\", [cast_node, zero_point_const], op_name_scope=node.name).output[0]\n mul_node = ctx.make_node(\"Mul\", [sub_node, scale_const], op_name_scope=node.name).output[0]\n ctx.replace_all_inputs(node.output[0], mul_node)\n ctx.remove_node(node.name)\n\n @classmethod\n def version_10(cls, ctx, node, dequantize=False, **kwargs):\n if dequantize or 'scale' not in node.attr:\n cls.version_1(ctx, node, dequantize=True, **kwargs)\n return\n scale = node.get_attr_value('scale')\n zero_point = node.get_attr_value('zero_point')\n axis = node.get_attr_value('quantized_dimension')\n np_q_type = utils.map_onnx_to_numpy_type(ctx.get_dtype(node.input[0]))\n if len(scale) > 1 or len(zero_point) > 1:\n utils.make_sure(ctx.opset >= 13, \"Opset 13 is required for per-axis quantization for node %s\", node.name)\n node.set_attr(\"axis\", axis)\n scale_node = ctx.make_const(utils.make_name(\"scale\"), np.array(scale, dtype=np.float32))\n zero_point_node = ctx.make_const(utils.make_name(\"zero_point\"), np.array(zero_point, dtype=np_q_type))\n else:\n scale_node = ctx.make_const(utils.make_name(\"scale\"), np.array(scale[0], dtype=np.float32))\n zero_point_node = ctx.make_const(utils.make_name(\"zero_point\"), np.array(zero_point[0], dtype=np_q_type))\n ctx.replace_inputs(node, [node.input[0], scale_node.output[0], zero_point_node.output[0]])\n del node.attr[\"scale\"]\n del node.attr[\"zero_point\"]\n del node.attr[\"quantized_dimension\"]\n if \"min\" in node.attr:\n del node.attr[\"min\"]\n if \"max\" in node.attr:\n del node.attr[\"max\"]\n\ndef dynamic_quantize_inputs(ctx, node):\n if ctx.opset < 11:\n logger.warning(\"Opset 11 is required for asymmetric_quantize_inputs of node %s\", node.name)\n return\n for i in range(len(node.input)):\n # Don't quantize inputs that are already quantized\n if node.inputs[i].type in [\"DequantizeLinear\", \"TFL_DEQUANTIZE\"]:\n continue\n dyn_quant = ctx.make_node(\"DynamicQuantizeLinear\", [node.input[i]], output_count=3, op_name_scope=node.name)\n dyn_quant.skip_conversion = True\n dequant = ctx.make_node(\"DequantizeLinear\", dyn_quant.output, op_name_scope=node.name)\n dequant.skip_conversion = True\n ctx.replace_input(node, node.input[i], dequant.output[0], input_index=i)\n\n@tfl_op([\"TFL_FULLY_CONNECTED\"])\nclass TflFullyConnectedOp:\n @classmethod\n def to_tf(cls, ctx, node, **kwargs):\n separate_fused_activation_function(ctx, node)\n utils.make_sure(node.attr['weights_format'].s == b'DEFAULT',\n \"Only default weights format supported for fully connected op\")\n utils.make_sure(node.attr['keep_num_dims'].i == 0,\n \"Only keep_num_dims=False supported for fully connected op\")\n if node.attr['asymmetric_quantize_inputs'].i == 1:\n dynamic_quantize_inputs(ctx, node)\n\n if ctx.get_rank(node.input[0]) != 2:\n # When a fullyconnected node has keep_num_dims=0 and input[0] rank > 2, the extra dims must be compressed\n utils.make_sure(ctx.get_rank(node.input[1]) == 2, \"weights for FullyConnected must have rank 2\")\n weights_shape = ctx.get_shape(node.input[1])[1]\n utils.make_sure(weights_shape != -1, \"weights for FullyConnected must have known shape\")\n shape_const = ctx.make_const(utils.make_name(\"reshape_shape\"), np.array([-1, weights_shape], np.int64))\n reshape_node = ctx.make_node(\"Reshape\", [node.input[0], shape_const.output[0]])\n reshape_node.skip_conversion = True\n ctx.replace_inputs(node, [reshape_node.output[0], node.input[1]])\n\n transpose_node = ctx.insert_new_node_on_input(node, \"Transpose\", node.input[1],\n name=None, input_index=1, perm=[1, 0])\n transpose_node.skip_conversion = True\n node.set_attr(\"transpose_a\", 0)\n node.set_attr(\"transpose_b\", 0)\n node.type = \"MatMul\"\n\n if len(node.input) == 3:\n # FIXME: Add a test for this\n bias_inp = node.input[2]\n ctx.replace_inputs(node, node.input[:2])\n add_node = ctx.insert_new_node_on_output(\"Add\", node.output[0], inputs=[node.output[0], bias_inp])\n add_node.skip_conversion = True\n\n del node.attr[\"weights_format\"]\n del node.attr[\"keep_num_dims\"]\n del node.attr[\"asymmetric_quantize_inputs\"]\n\n@tfl_op([\"TFL_SOFTMAX\"], tf_op=\"Softmax\")\nclass TFlSoftmaxOp:\n @classmethod\n def to_tf(cls, ctx, node, **kwargs):\n beta = node.get_attr_value(\"beta\")\n if beta != 1:\n beta_node = ctx.make_const(utils.make_name(\"beta\"), np.array(beta, dtype=np.float32))\n mul_node = ctx.insert_new_node_on_output(\"Mul\", node.output[0], name=utils.make_name(node.name))\n ctx.replace_inputs(mul_node, [node.output[0], beta_node.output[0]])\n\n@tfl_op([\"TFL_PRELU\"], onnx_op=\"PRelu\")\nclass TflPreluOp:\n @classmethod\n def version_7(cls, ctx, node, **kwargs):\n pass\n"
]
| [
[
"tensorflow.core.framework.tensor_pb2.TensorProto",
"numpy.array",
"tensorflow.lite.Interpreter",
"tensorflow.python.framework.tensor_util.MakeNdarray",
"tensorflow.core.framework.node_def_pb2.NodeDef"
],
[
"numpy.array"
]
]
|
mayankpadhi/AI_Codes | [
"8631f18cd9d1bba9ffc142b1ede0197b512157e2"
]
| [
"Week 6/storing_values_in_CSV.py"
]
| [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport csv\nlist=[]\n\nmean =[0,0]\ncov=[[1 ,0.7 ],[0.7, 1]]\nx, y = np.random.multivariate_normal(mean, cov,40).T\nlist=[]\nprint(x,y)\nfor i in range(0,40):\n list.append([x[i],y[i]])\n\nprint(list)\n\n\nmean =[4,4]\ncov=[[1 ,0.25 ],[0.25, 0.5]]\nx1, y1 = np.random.multivariate_normal(mean, cov,30).T\nprint(x1,y1)\nfor i in range(0,30):\n list.append([x1[i],y1[i]])\n\nprint(list)\n\n\n\nmean =[0,3]\ncov=[[0.5 ,0.1],[ 1, 0.1]]\nx2, y2 = np.random.multivariate_normal(mean, cov,20).T\nprint(x2,y2)\nfor i in range(0,20):\n list.append([x2[i],y2[i]])\n\nprint(list)\n\n\n\nmean =[4,0]\ncov=[[0.25 ,0],[0, 0.35]]\nx3, y3 = np.random.multivariate_normal(mean, cov,10).T\nprint(x1,y1)\nfor i in range(0,10):\n list.append([x3[i],y3[i]])\n\nprint(list)\n\n\nwith open('names.csv', 'w') as csvfile:\n fieldnames = ['x', 'y']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n\n writer.writeheader()\n for i in range (0,100):\n\n writer.writerow({'x': list[i][0] ,'y': list[i][1]})"
]
| [
[
"numpy.random.multivariate_normal"
]
]
|
ziyan0302/Multiverse | [
"3b2f590a7d99758b6a8795070ca25a9698b767a9"
]
| [
"forking_paths_dataset/code/plot_traj_carla.py"
]
| [
"# coding=utf-8\n# plot world traj on the carla ground\nimport argparse\nimport glob\nimport math\nimport os\nimport sys\n\nscript_path = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(glob.glob(\"%s/carla*.egg\" % script_path)[0])\n\nimport carla\n\nimport numpy as np\nfrom visualize_real_data import load_traj\nfrom visualize_real_data import get_traj\nfrom visualize_real_data import rotate\nfrom visualize_real_data import get_scene\n\nparser = argparse.ArgumentParser()\n\n# params for getting the trajectory\nparser.add_argument(\"traj_world_file\")\nparser.add_argument(\"start_frame_idx\", type=int)\n\n# carla mapping\nparser.add_argument(\"origin_x\", type=float)\nparser.add_argument(\"origin_y\", type=float)\nparser.add_argument(\"origin_z\", type=float)\nparser.add_argument(\"carla_rotation\", type=float,\n help=\"rotate degrees before translate to origin.\")\n\n# actev will also get the vehicle traj\nparser.add_argument(\"--is_actev\", action=\"store_true\")\nparser.add_argument(\"--vehicle_world_traj_file\", default=None)\nparser.add_argument(\"--save_vehicle_carla_traj_file\", default=None,\n help=\"if set this, will save ALL the 3D carla coor instead\")\n\nparser.add_argument(\"--world_rotate\", type=float, default=0.0,\n help=\"rotation in degrees\")\nparser.add_argument(\"--scale\", type=float, default=1.0,\n help=\"scaling the meters\")\n# carla param\nparser.add_argument(\"--host\", default=\"127.0.0.1\")\nparser.add_argument(\"--port\", default=2000, type=int)\n\nparser.add_argument(\"--obs_length\", type=int, default=8)\nparser.add_argument(\"--pred_length\", type=int, default=12)\n\nparser.add_argument(\"--line_time\", type=float, default=30,\n help=\"how long does the traj stays, -1 is perminent\")\n\nparser.add_argument(\"--save_carla_traj_file\", default=None,\n help=\"if set this, will save ALL the 3D carla coor instead\")\n\n\ndef plot_trajs_carla(world, trajs, carla_color, z, line_time=30.0,\n show_person_id=False):\n\n for person_id, traj in trajs:\n points = zip(traj[:-1], traj[1:])\n for p1, p2 in points:\n p1 = carla.Location(x=p1[0], y=p1[1], z=z)\n p2 = carla.Location(x=p2[0], y=p2[1], z=z)\n\n world.debug.draw_arrow(\n p1, p2,\n thickness=0.1,\n arrow_size=0.1, color=carla_color, life_time=line_time)\n if show_person_id:\n world.debug.draw_string(\n carla.Location(x=traj[0][0], y=traj[0][1], z=z), \"# %s\" % person_id,\n draw_shadow=False, color=carla.Color(r=255, g=0, b=0),\n life_time=line_time, persistent_lines=False)\n\n\n# computed using compute_actev_world_norm.py\n# min -> max\nactev_norm = {\n \"0400\": {\n \"x\": [-113.339996, 15.906000], \"y\": [-51.101002, 82.049004]\n },\n \"0401\": {\n \"x\": [-76.031998, 28.722000], \"y\": [-3.993000, 90.141998]\n },\n \"0000\": {\n \"x\": [-7.510000, 48.320000], \"y\": [-7.984000, 14.305000]\n },\n \"0002\": {\n \"x\": [-38.488998, 67.762001], \"y\": [-29.208000, 128.421005]\n },\n \"0500\": {\n \"x\": [-25.212000, -0.499000], \"y\": [-25.396999, 35.426998]\n },\n}\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n\n traj_world_data = load_traj(args.traj_world_file)\n # 1. preprocess world trajectory\n if args.world_rotate != 0:\n traj_world_data = rotate(\n traj_world_data, (0, 0), math.radians(args.world_rotate))\n\n # translate to 0, 0, but keeping the meters unit\n if args.is_actev:\n assert args.vehicle_world_traj_file is not None\n vehicle_traj_world_data = load_traj(args.vehicle_world_traj_file)\n if args.world_rotate != 0:\n vehicle_traj_world_data = rotate(\n vehicle_traj_world_data, (0, 0), math.radians(args.world_rotate))\n videoname = os.path.splitext(os.path.basename(args.traj_world_file))[0]\n scene = get_scene(videoname)\n min_x, max_x = actev_norm[scene][\"x\"]\n min_y, max_y = actev_norm[scene][\"y\"]\n # prepare the vehicle trajectory # scaling up or down\n # since the meter unit in the carla might be off\n vehicle_traj_stage1 = vehicle_traj_world_data.copy()\n vehicle_traj_stage1[:, 2] = (vehicle_traj_stage1[:, 2] - min_x) * args.scale\n vehicle_traj_stage1[:, 3] = (vehicle_traj_stage1[:, 3] - min_y) * args.scale\n\n # rotate and translate into designated carla space\n vehicle_traj_stage2 = rotate(\n vehicle_traj_stage1, (0, 0), math.radians(args.carla_rotation))\n vehicle_traj_stage2[:, 2] = vehicle_traj_stage2[:, 2] + args.origin_x\n vehicle_traj_stage2[:, 3] = vehicle_traj_stage2[:, 3] + args.origin_y\n\n vehicle_ids = np.unique(\n vehicle_traj_world_data[\n vehicle_traj_world_data[:, 0] == args.start_frame_idx, 1])\n vehicle_ids = vehicle_ids.tolist()\n else:\n min_x = np.amin(np.array(traj_world_data)[:, 2])\n max_x = np.amax(np.array(traj_world_data)[:, 2])\n min_y = np.amin(np.array(traj_world_data)[:, 3])\n max_y = np.amax(np.array(traj_world_data)[:, 3])\n\n # scaling up or down\n # since the meter unit in the carla might be off\n traj_world_stage1 = traj_world_data.copy()\n traj_world_stage1[:, 2] = (traj_world_stage1[:, 2] - min_x) * args.scale\n traj_world_stage1[:, 3] = (traj_world_stage1[:, 3] - min_y) * args.scale\n\n # rotate and translate into designated carla space\n traj_world_stage2 = rotate(\n traj_world_stage1, (0, 0), math.radians(args.carla_rotation))\n traj_world_stage2[:, 2] = traj_world_stage2[:, 2] + args.origin_x\n traj_world_stage2[:, 3] = traj_world_stage2[:, 3] + args.origin_y\n\n if args.save_carla_traj_file is not None:\n with open(args.save_carla_traj_file, \"w\") as f:\n for frame_id, person_id, x, y in traj_world_stage2:\n f.writelines(\"%d\\t%d\\t%.6f\\t%.6f\\t%.6f\\n\" % (\n frame_id, person_id, x, y, args.origin_z))\n if args.is_actev:\n assert args.save_vehicle_carla_traj_file is not None\n with open(args.save_vehicle_carla_traj_file, \"w\") as f:\n for frame_id, vehicle_id, x, y in vehicle_traj_stage2:\n f.writelines(\"%d\\t%d\\t%.6f\\t%.6f\\t%.6f\\n\" % (\n frame_id, vehicle_id, x, y, args.origin_z))\n sys.exit()\n\n # get the specific trajectories\n frame_ids = np.unique(traj_world_data[:, 0]).tolist()\n frame_ids.sort()\n f_idx = frame_ids.index(args.start_frame_idx)\n # we will draw pred_frame first then obs frame traj so there is 2 color?\n obs_frame_ids = frame_ids[f_idx:f_idx + args.obs_length]\n full_frame_ids = frame_ids[f_idx:f_idx + args.obs_length + args.pred_length]\n\n # all the person in frame_ids\n person_ids = np.unique(\n traj_world_data[np.isin(traj_world_data[:, 0], full_frame_ids), 1])\n person_ids = person_ids.tolist()\n\n # (person_id, list of xy)\n obs_person_trajs = [get_traj(\n traj_world_stage2, obs_frame_ids, person_id) for person_id in person_ids]\n full_person_trajs = [get_traj(\n traj_world_stage2, full_frame_ids, person_id) for person_id in person_ids]\n\n if args.is_actev:\n full_vehicle_trajs = [get_traj(\n vehicle_traj_stage2, full_frame_ids, vehicle_id)\n for vehicle_id in vehicle_ids]\n\n # plot the trajectories and the person Id\n try:\n client = carla.Client(args.host, args.port)\n client.set_timeout(2.0)\n world = client.get_world()\n\n green = carla.Color(r=0, g=255, b=0)\n yellow = carla.Color(r=255, g=255, b=0)\n plot_trajs_carla(world, full_person_trajs, green, args.origin_z,\n show_person_id=True, line_time=args.line_time)\n plot_trajs_carla(world, obs_person_trajs, yellow, args.origin_z,\n line_time=args.line_time)\n\n if args.is_actev:\n blue = carla.Color(r=0, g=0, b=255)\n plot_trajs_carla(world, full_vehicle_trajs, blue, args.origin_z,\n line_time=args.line_time, show_person_id=True)\n\n finally:\n pass\n"
]
| [
[
"numpy.array",
"numpy.unique",
"numpy.isin"
]
]
|
abdulazizali77/tensorflow | [
"f7d07f5d9683a7d5ce91b108c6c31a47e1372eaa"
]
| [
"tensorflow/python/ops/data_flow_ops.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\n\"\"\"Data Flow Operations.\"\"\"\n# pylint: disable=g-bad-name\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport hashlib\nimport re\nimport threading\n\nimport six\n\nfrom tensorflow.python.framework import dtypes as _dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import random_seed\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gen_data_flow_ops\nfrom tensorflow.python.ops import math_ops\n# go/tf-wildcard-import\n# pylint: disable=wildcard-import\nfrom tensorflow.python.ops.gen_data_flow_ops import *\n# pylint: enable=wildcard-import\nfrom tensorflow.python.util.deprecation import deprecated\n\n\ndef _as_type_list(dtypes):\n \"\"\"Convert dtypes to a list of types.\"\"\"\n assert dtypes is not None\n if not (isinstance(dtypes, list) or isinstance(dtypes, tuple)):\n # We have a single type.\n return [dtypes]\n else:\n # We have a list or tuple of types.\n return list(dtypes)\n\n\ndef _as_shape_list(shapes, dtypes, unknown_dim_allowed=False,\n unknown_rank_allowed=False):\n \"\"\"Convert shapes to a list of tuples of int (or None).\"\"\"\n if unknown_dim_allowed:\n if (not isinstance(shapes, collections.Sequence)\n or not shapes\n or any(shape is None or isinstance(shape, int) for shape in shapes)):\n raise ValueError(\n \"When providing partial shapes, a list of shapes must be provided.\")\n if shapes is None: return None\n if isinstance(shapes, tensor_shape.TensorShape):\n shapes = [shapes]\n if not isinstance(shapes, (tuple, list)):\n raise TypeError(\n \"shapes must be a TensorShape or a list or tuple of TensorShapes.\")\n if all(shape is None or isinstance(shape, int) for shape in shapes):\n # We have a single shape.\n shapes = [shapes]\n shapes = [tensor_shape.as_shape(shape) for shape in shapes]\n if not unknown_dim_allowed:\n if any([not shape.is_fully_defined() for shape in shapes]):\n raise ValueError(\"All shapes must be fully defined: %s\" % shapes)\n if not unknown_rank_allowed:\n if any([shape.dims is None for shape in shapes]):\n raise ValueError(\"All shapes must have a defined rank: %s\" % shapes)\n\n return shapes\n\n\ndef _as_name_list(names, dtypes):\n if names is None:\n return None\n if not isinstance(names, (list, tuple)):\n names = [names]\n if len(names) != len(dtypes):\n raise ValueError(\"List of names must have the same length as the list \"\n \"of dtypes\")\n return list(names)\n\n\ndef _shape_common(s1, s2):\n \"\"\"The greatest lower bound (ordered by specificity) TensorShape.\"\"\"\n s1 = tensor_shape.TensorShape(s1)\n s2 = tensor_shape.TensorShape(s2)\n if s1.ndims is None or s2.ndims is None or s1.ndims != s2.ndims:\n return tensor_shape.unknown_shape()\n d = [\n d1 if d1 is not None and d1 == d2 else None\n for (d1, d2) in zip(s1.as_list(), s2.as_list())]\n return tensor_shape.TensorShape(d)\n\n\n# pylint: disable=protected-access\nclass QueueBase(object):\n \"\"\"Base class for queue implementations.\n\n A queue is a TensorFlow data structure that stores tensors across\n multiple steps, and exposes operations that enqueue and dequeue\n tensors.\n\n Each queue element is a tuple of one or more tensors, where each\n tuple component has a static dtype, and may have a static shape. The\n queue implementations support versions of enqueue and dequeue that\n handle single elements, versions that support enqueuing and\n dequeuing a batch of elements at once.\n\n See [`tf.FIFOQueue`](#FIFOQueue) and\n [`tf.RandomShuffleQueue`](#RandomShuffleQueue) for concrete\n implementations of this class, and instructions on how to create\n them.\n\n @@enqueue\n @@enqueue_many\n\n @@dequeue\n @@dequeue_many\n\n @@size\n\n @@close\n\n \"\"\"\n\n def __init__(self, dtypes, shapes, names, queue_ref):\n \"\"\"Constructs a queue object from a queue reference.\n\n The two optional lists, `shapes` and `names`, must be of the same length\n as `dtypes` if provided. The values at a given index `i` indicate the\n shape and name to use for the corresponding queue component in `dtypes`.\n\n Args:\n dtypes: A list of types. The length of dtypes must equal the number\n of tensors in each element.\n shapes: Constraints on the shapes of tensors in an element:\n A list of shape tuples or None. This list is the same length\n as dtypes. If the shape of any tensors in the element are constrained,\n all must be; shapes can be None if the shapes should not be constrained.\n names: Optional list of names. If provided, the `enqueue()` and\n `dequeue()` methods will use dictionaries with these names as keys.\n Must be None or a list or tuple of the same length as `dtypes`.\n queue_ref: The queue reference, i.e. the output of the queue op.\n\n Raises:\n ValueError: If one of the arguments is invalid.\n \"\"\"\n self._dtypes = dtypes\n if shapes is not None:\n if len(shapes) != len(dtypes):\n raise ValueError(\"Queue shapes must have the same length as dtypes\")\n self._shapes = [tensor_shape.TensorShape(s) for s in shapes]\n else:\n self._shapes = [tensor_shape.unknown_shape() for _ in self._dtypes]\n if names is not None:\n if len(names) != len(dtypes):\n raise ValueError(\"Queue names must have the same length as dtypes\")\n self._names = names\n else:\n self._names = None\n self._queue_ref = queue_ref\n self._name = self._queue_ref.op.name.split(\"/\")[-1]\n\n @staticmethod\n def from_list(index, queues):\n \"\"\"Create a queue using the queue reference from `queues[index]`.\n\n Args:\n index: An integer scalar tensor that determines the input that gets\n selected.\n queues: A list of `QueueBase` objects.\n\n Returns:\n A `QueueBase` object.\n\n Raises:\n TypeError: When `queues` is not a list of `QueueBase` objects,\n or when the data types of `queues` are not all the same.\n \"\"\"\n if ((not queues) or\n (not isinstance(queues, list)) or\n (not all(isinstance(x, QueueBase) for x in queues))):\n raise TypeError(\"A list of queues expected\")\n\n dtypes = queues[0].dtypes\n if not all([dtypes == q.dtypes for q in queues[1:]]):\n raise TypeError(\"Queues do not have matching component dtypes.\")\n\n names = queues[0].names\n if not all([names == q.names for q in queues[1:]]):\n raise TypeError(\"Queues do not have matching component names.\")\n\n queue_shapes = [q.shapes for q in queues]\n reduced_shapes = [\n six.moves.reduce(_shape_common, s) for s in zip(*queue_shapes)]\n\n queue_refs = array_ops.stack([x.queue_ref for x in queues])\n selected_queue = array_ops.gather(queue_refs, index)\n return QueueBase(dtypes=dtypes, shapes=reduced_shapes, names=names,\n queue_ref=selected_queue)\n\n @property\n def queue_ref(self):\n \"\"\"The underlying queue reference.\"\"\"\n return self._queue_ref\n\n @property\n def name(self):\n \"\"\"The name of the underlying queue.\"\"\"\n return self._queue_ref.op.name\n\n @property\n def dtypes(self):\n \"\"\"The list of dtypes for each component of a queue element.\"\"\"\n return self._dtypes\n\n @property\n def shapes(self):\n \"\"\"The list of shapes for each component of a queue element.\"\"\"\n return self._shapes\n\n @property\n def names(self):\n \"\"\"The list of names for each component of a queue element.\"\"\"\n return self._names\n\n def _check_enqueue_dtypes(self, vals):\n \"\"\"Validate and convert `vals` to a list of `Tensor`s.\n\n The `vals` argument can be a Tensor, a list or tuple of tensors, or a\n dictionary with tensor values.\n\n If it is a dictionary, the queue must have been constructed with a\n `names` attribute and the dictionary keys must match the queue names.\n If the queue was constructed with a `names` attribute, `vals` must\n be a dictionary.\n\n Args:\n vals: A tensor, a list or tuple of tensors, or a dictionary..\n\n Returns:\n A list of `Tensor` objects.\n\n Raises:\n ValueError: If `vals` is invalid.\n \"\"\"\n if isinstance(vals, dict):\n if not self._names:\n raise ValueError(\"Queue must have names to enqueue a dictionary\")\n if sorted(self._names) != sorted(vals.keys()):\n raise ValueError(\"Keys in dictionary to enqueue do not match \"\n \"names of Queue. Dictionary: (%s), Queue: (%s)\" %\n (sorted(vals.keys()), sorted(self._names)))\n # The order of values in `self._names` indicates the order in which the\n # tensors in the dictionary `vals` must be listed.\n vals = [vals[k] for k in self._names]\n else:\n if self._names:\n raise ValueError(\"You must enqueue a dictionary in a Queue with names\")\n if not isinstance(vals, (list, tuple)):\n vals = [vals]\n\n tensors = []\n for i, (val, dtype) in enumerate(zip(vals, self._dtypes)):\n tensors.append(ops.convert_to_tensor(val, dtype=dtype,\n name=\"component_%d\" % i))\n\n return tensors\n\n def _scope_vals(self, vals):\n \"\"\"Return a list of values to pass to `name_scope()`.\n\n Args:\n vals: A tensor, a list or tuple of tensors, or a dictionary.\n\n Returns:\n The values in vals as a list.\n \"\"\"\n if isinstance(vals, (list, tuple)):\n return vals\n elif isinstance(vals, dict):\n return vals.values()\n else:\n return [vals]\n\n def enqueue(self, vals, name=None):\n \"\"\"Enqueues one element to this queue.\n\n If the queue is full when this operation executes, it will block\n until the element has been enqueued.\n\n At runtime, this operation may raise an error if the queue is\n [closed](#QueueBase.close) before or during its execution. If the\n queue is closed before this operation runs,\n `tf.errors.CancelledError` will be raised. If this operation is\n blocked, and either (i) the queue is closed by a close operation\n with `cancel_pending_enqueues=True`, or (ii) the session is\n [closed](../../api_docs/python/client.md#Session.close),\n `tf.errors.CancelledError` will be raised.\n\n Args:\n vals: A tensor, a list or tuple of tensors, or a dictionary containing\n the values to enqueue.\n name: A name for the operation (optional).\n\n Returns:\n The operation that enqueues a new tuple of tensors to the queue.\n \"\"\"\n with ops.name_scope(name, \"%s_enqueue\" % self._name,\n self._scope_vals(vals)) as scope:\n vals = self._check_enqueue_dtypes(vals)\n\n # NOTE(mrry): Not using a shape function because we need access to\n # the `QueueBase` object.\n for val, shape in zip(vals, self._shapes):\n val.get_shape().assert_is_compatible_with(shape)\n\n if self._queue_ref.dtype == _dtypes.resource:\n return gen_data_flow_ops._queue_enqueue_v2(\n self._queue_ref, vals, name=scope)\n else:\n return gen_data_flow_ops._queue_enqueue(\n self._queue_ref, vals, name=scope)\n\n def enqueue_many(self, vals, name=None):\n \"\"\"Enqueues zero or more elements to this queue.\n\n This operation slices each component tensor along the 0th dimension to\n make multiple queue elements. All of the tensors in `vals` must have the\n same size in the 0th dimension.\n\n If the queue is full when this operation executes, it will block\n until all of the elements have been enqueued.\n\n At runtime, this operation may raise an error if the queue is\n [closed](#QueueBase.close) before or during its execution. If the\n queue is closed before this operation runs,\n `tf.errors.CancelledError` will be raised. If this operation is\n blocked, and either (i) the queue is closed by a close operation\n with `cancel_pending_enqueues=True`, or (ii) the session is\n [closed](../../api_docs/python/client.md#Session.close),\n `tf.errors.CancelledError` will be raised.\n\n Args:\n vals: A tensor, a list or tuple of tensors, or a dictionary\n from which the queue elements are taken.\n name: A name for the operation (optional).\n\n Returns:\n The operation that enqueues a batch of tuples of tensors to the queue.\n \"\"\"\n with ops.name_scope(name, \"%s_EnqueueMany\" % self._name,\n self._scope_vals(vals)) as scope:\n vals = self._check_enqueue_dtypes(vals)\n\n # NOTE(mrry): Not using a shape function because we need access to\n # the `QueueBase` object.\n batch_dim = vals[0].get_shape().with_rank_at_least(1)[0]\n for val, shape in zip(vals, self._shapes):\n batch_dim = batch_dim.merge_with(\n val.get_shape().with_rank_at_least(1)[0])\n val.get_shape()[1:].assert_is_compatible_with(shape)\n\n return gen_data_flow_ops._queue_enqueue_many_v2(\n self._queue_ref, vals, name=scope)\n\n def _dequeue_return_value(self, tensors):\n \"\"\"Return the value to return from a dequeue op.\n\n If the queue has names, return a dictionary with the\n names as keys. Otherwise return either a single tensor\n or a list of tensors depending on the length of `tensors`.\n\n Args:\n tensors: List of tensors from the dequeue op.\n\n Returns:\n A single tensor, a list of tensors, or a dictionary\n of tensors.\n \"\"\"\n if self._names:\n # The returned values in `tensors` are in the same order as\n # the names in `self._names`.\n return {n: tensors[i] for i, n in enumerate(self._names)}\n elif len(tensors) == 1:\n return tensors[0]\n else:\n return tensors\n\n def dequeue(self, name=None):\n \"\"\"Dequeues one element from this queue.\n\n If the queue is empty when this operation executes, it will block\n until there is an element to dequeue.\n\n At runtime, this operation may raise an error if the queue is\n [closed](#QueueBase.close) before or during its execution. If the\n queue is closed, the queue is empty, and there are no pending\n enqueue operations that can fulfill this request,\n `tf.errors.OutOfRangeError` will be raised. If the session is\n [closed](../../api_docs/python/client.md#Session.close),\n `tf.errors.CancelledError` will be raised.\n\n Args:\n name: A name for the operation (optional).\n\n Returns:\n The tuple of tensors that was dequeued.\n \"\"\"\n if name is None:\n name = \"%s_Dequeue\" % self._name\n if self._queue_ref.dtype == _dtypes.resource:\n ret = gen_data_flow_ops._queue_dequeue_v2(\n self._queue_ref, self._dtypes, name=name)\n else:\n ret = gen_data_flow_ops._queue_dequeue(\n self._queue_ref, self._dtypes, name=name)\n\n # NOTE(mrry): Not using a shape function because we need access to\n # the `QueueBase` object.\n op = ret[0].op\n for output, shape in zip(op.values(), self._shapes):\n output.set_shape(shape)\n\n return self._dequeue_return_value(ret)\n\n def dequeue_many(self, n, name=None):\n \"\"\"Dequeues and concatenates `n` elements from this queue.\n\n This operation concatenates queue-element component tensors along\n the 0th dimension to make a single component tensor. All of the\n components in the dequeued tuple will have size `n` in the 0th dimension.\n\n If the queue is closed and there are less than `n` elements left, then an\n `OutOfRange` exception is raised.\n\n At runtime, this operation may raise an error if the queue is\n [closed](#QueueBase.close) before or during its execution. If the\n queue is closed, the queue contains fewer than `n` elements, and\n there are no pending enqueue operations that can fulfill this\n request, `tf.errors.OutOfRangeError` will be raised. If the\n session is [closed](../../api_docs/python/client.md#Session.close),\n `tf.errors.CancelledError` will be raised.\n\n Args:\n n: A scalar `Tensor` containing the number of elements to dequeue.\n name: A name for the operation (optional).\n\n Returns:\n The tuple of concatenated tensors that was dequeued.\n \"\"\"\n if name is None:\n name = \"%s_DequeueMany\" % self._name\n\n ret = gen_data_flow_ops._queue_dequeue_many_v2(\n self._queue_ref, n=n, component_types=self._dtypes, name=name)\n\n # NOTE(mrry): Not using a shape function because we need access to\n # the Queue object.\n op = ret[0].op\n batch_dim = tensor_shape.Dimension(tensor_util.constant_value(op.inputs[1]))\n for output, shape in zip(op.values(), self._shapes):\n output.set_shape(tensor_shape.TensorShape([batch_dim]).concatenate(shape))\n\n return self._dequeue_return_value(ret)\n\n def dequeue_up_to(self, n, name=None):\n \"\"\"Dequeues and concatenates `n` elements from this queue.\n\n **Note** This operation is not supported by all queues. If a queue does not\n support DequeueUpTo, then a `tf.errors.UnimplementedError` is raised.\n\n This operation concatenates queue-element component tensors along\n the 0th dimension to make a single component tensor. If the queue\n has not been closed, all of the components in the dequeued tuple\n will have size `n` in the 0th dimension.\n\n If the queue is closed and there are more than `0` but fewer than\n `n` elements remaining, then instead of raising a\n `tf.errors.OutOfRangeError` like [`dequeue_many`](#QueueBase.dequeue_many),\n less than `n` elements are returned immediately. If the queue is\n closed and there are `0` elements left in the queue, then a\n `tf.errors.OutOfRangeError` is raised just like in `dequeue_many`.\n Otherwise the behavior is identical to `dequeue_many`.\n\n Args:\n n: A scalar `Tensor` containing the number of elements to dequeue.\n name: A name for the operation (optional).\n\n Returns:\n The tuple of concatenated tensors that was dequeued.\n \"\"\"\n if name is None:\n name = \"%s_DequeueUpTo\" % self._name\n\n ret = gen_data_flow_ops._queue_dequeue_up_to_v2(\n self._queue_ref, n=n, component_types=self._dtypes, name=name)\n\n # NOTE(mrry): Not using a shape function because we need access to\n # the Queue object.\n op = ret[0].op\n for output, shape in zip(op.values(), self._shapes):\n output.set_shape(tensor_shape.TensorShape([None]).concatenate(shape))\n\n return self._dequeue_return_value(ret)\n\n def close(self, cancel_pending_enqueues=False, name=None):\n \"\"\"Closes this queue.\n\n This operation signals that no more elements will be enqueued in\n the given queue. Subsequent `enqueue` and `enqueue_many`\n operations will fail. Subsequent `dequeue` and `dequeue_many`\n operations will continue to succeed if sufficient elements remain\n in the queue. Subsequent `dequeue` and `dequeue_many` operations\n that would block will fail immediately.\n\n If `cancel_pending_enqueues` is `True`, all pending requests will also\n be cancelled.\n\n Args:\n cancel_pending_enqueues: (Optional.) A boolean, defaulting to\n `False` (described above).\n name: A name for the operation (optional).\n\n Returns:\n The operation that closes the queue.\n \"\"\"\n if name is None:\n name = \"%s_Close\" % self._name\n if self._queue_ref.dtype == _dtypes.resource:\n return gen_data_flow_ops._queue_close_v2(\n self._queue_ref, cancel_pending_enqueues=cancel_pending_enqueues,\n name=name)\n else:\n return gen_data_flow_ops._queue_close(\n self._queue_ref, cancel_pending_enqueues=cancel_pending_enqueues,\n name=name)\n\n def size(self, name=None):\n \"\"\"Compute the number of elements in this queue.\n\n Args:\n name: A name for the operation (optional).\n\n Returns:\n A scalar tensor containing the number of elements in this queue.\n \"\"\"\n if name is None:\n name = \"%s_Size\" % self._name\n if self._queue_ref.dtype == _dtypes.resource:\n return gen_data_flow_ops._queue_size_v2(self._queue_ref, name=name)\n else:\n return gen_data_flow_ops._queue_size(self._queue_ref, name=name)\n\n\nclass RandomShuffleQueue(QueueBase):\n \"\"\"A queue implementation that dequeues elements in a random order.\n\n See [`tf.QueueBase`](#QueueBase) for a description of the methods on\n this class.\n\n @@__init__\n \"\"\"\n\n def __init__(self, capacity, min_after_dequeue, dtypes, shapes=None,\n names=None, seed=None, shared_name=None,\n name=\"random_shuffle_queue\"):\n \"\"\"Create a queue that dequeues elements in a random order.\n\n A `RandomShuffleQueue` has bounded capacity; supports multiple\n concurrent producers and consumers; and provides exactly-once\n delivery.\n\n A `RandomShuffleQueue` holds a list of up to `capacity`\n elements. Each element is a fixed-length tuple of tensors whose\n dtypes are described by `dtypes`, and whose shapes are optionally\n described by the `shapes` argument.\n\n If the `shapes` argument is specified, each component of a queue\n element must have the respective fixed shape. If it is\n unspecified, different queue elements may have different shapes,\n but the use of `dequeue_many` is disallowed.\n\n The `min_after_dequeue` argument allows the caller to specify a\n minimum number of elements that will remain in the queue after a\n `dequeue` or `dequeue_many` operation completes, to ensure a\n minimum level of mixing of elements. This invariant is maintained\n by blocking those operations until sufficient elements have been\n enqueued. The `min_after_dequeue` argument is ignored after the\n queue has been closed.\n\n Args:\n capacity: An integer. The upper bound on the number of elements\n that may be stored in this queue.\n min_after_dequeue: An integer (described above).\n dtypes: A list of `DType` objects. The length of `dtypes` must equal\n the number of tensors in each queue element.\n shapes: (Optional.) A list of fully-defined `TensorShape` objects\n with the same length as `dtypes`, or `None`.\n names: (Optional.) A list of string naming the components in the queue\n with the same length as `dtypes`, or `None`. If specified the dequeue\n methods return a dictionary with the names as keys.\n seed: A Python integer. Used to create a random seed. See\n [`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)\n for behavior.\n shared_name: (Optional.) If non-empty, this queue will be shared under\n the given name across multiple sessions.\n name: Optional name for the queue operation.\n \"\"\"\n dtypes = _as_type_list(dtypes)\n shapes = _as_shape_list(shapes, dtypes)\n names = _as_name_list(names, dtypes)\n seed1, seed2 = random_seed.get_seed(seed)\n if seed1 is None and seed2 is None:\n seed1, seed2 = 0, 0\n elif seed is None and shared_name is not None:\n # This means that graph seed is provided but op seed is not provided.\n # If shared_name is also provided, make seed2 depend only on the graph\n # seed and shared_name. (seed2 from get_seed() is generally dependent on\n # the id of the last op created.)\n string = (str(seed1) + shared_name).encode(\"utf-8\")\n seed2 = int(hashlib.md5(string).hexdigest()[:8], 16) & 0x7FFFFFFF\n queue_ref = gen_data_flow_ops._random_shuffle_queue_v2(\n component_types=dtypes, shapes=shapes, capacity=capacity,\n min_after_dequeue=min_after_dequeue, seed=seed1, seed2=seed2,\n shared_name=shared_name, name=name)\n\n super(RandomShuffleQueue, self).__init__(dtypes, shapes, names, queue_ref)\n\n\nclass FIFOQueue(QueueBase):\n \"\"\"A queue implementation that dequeues elements in first-in first-out order.\n\n See [`tf.QueueBase`](#QueueBase) for a description of the methods on\n this class.\n\n @@__init__\n \"\"\"\n\n def __init__(self, capacity, dtypes, shapes=None, names=None,\n shared_name=None, name=\"fifo_queue\"):\n \"\"\"Creates a queue that dequeues elements in a first-in first-out order.\n\n A `FIFOQueue` has bounded capacity; supports multiple concurrent\n producers and consumers; and provides exactly-once delivery.\n\n A `FIFOQueue` holds a list of up to `capacity` elements. Each\n element is a fixed-length tuple of tensors whose dtypes are\n described by `dtypes`, and whose shapes are optionally described\n by the `shapes` argument.\n\n If the `shapes` argument is specified, each component of a queue\n element must have the respective fixed shape. If it is\n unspecified, different queue elements may have different shapes,\n but the use of `dequeue_many` is disallowed.\n\n Args:\n capacity: An integer. The upper bound on the number of elements\n that may be stored in this queue.\n dtypes: A list of `DType` objects. The length of `dtypes` must equal\n the number of tensors in each queue element.\n shapes: (Optional.) A list of fully-defined `TensorShape` objects\n with the same length as `dtypes`, or `None`.\n names: (Optional.) A list of string naming the components in the queue\n with the same length as `dtypes`, or `None`. If specified the dequeue\n methods return a dictionary with the names as keys.\n shared_name: (Optional.) If non-empty, this queue will be shared under\n the given name across multiple sessions.\n name: Optional name for the queue operation.\n \"\"\"\n dtypes = _as_type_list(dtypes)\n shapes = _as_shape_list(shapes, dtypes)\n names = _as_name_list(names, dtypes)\n queue_ref = gen_data_flow_ops._fifo_queue_v2(\n component_types=dtypes, shapes=shapes, capacity=capacity,\n shared_name=shared_name, name=name)\n\n super(FIFOQueue, self).__init__(dtypes, shapes, names, queue_ref)\n\n\nclass PaddingFIFOQueue(QueueBase):\n \"\"\"A FIFOQueue that supports batching variable-sized tensors by padding.\n\n A `PaddingFIFOQueue` may contain components with dynamic shape, while also\n supporting `dequeue_many`. See the constructor for more details.\n\n See [`tf.QueueBase`](#QueueBase) for a description of the methods on\n this class.\n\n @@__init__\n \"\"\"\n\n def __init__(self, capacity, dtypes, shapes, names=None, shared_name=None,\n name=\"padding_fifo_queue\"):\n \"\"\"Creates a queue that dequeues elements in a first-in first-out order.\n\n A `PaddingFIFOQueue` has bounded capacity; supports multiple concurrent\n producers and consumers; and provides exactly-once delivery.\n\n A `PaddingFIFOQueue` holds a list of up to `capacity` elements. Each\n element is a fixed-length tuple of tensors whose dtypes are\n described by `dtypes`, and whose shapes are described by the `shapes`\n argument.\n\n The `shapes` argument must be specified; each component of a queue\n element must have the respective shape. Shapes of fixed\n rank but variable size are allowed by setting any shape dimension to None.\n In this case, the inputs' shape may vary along the given dimension, and\n `dequeue_many` will pad the given dimension with zeros up to the maximum\n shape of all elements in the given batch.\n\n Args:\n capacity: An integer. The upper bound on the number of elements\n that may be stored in this queue.\n dtypes: A list of `DType` objects. The length of `dtypes` must equal\n the number of tensors in each queue element.\n shapes: A list of `TensorShape` objects, with the same length as\n `dtypes`. Any dimension in the `TensorShape` containing value\n `None` is dynamic and allows values to be enqueued with\n variable size in that dimension.\n names: (Optional.) A list of string naming the components in the queue\n with the same length as `dtypes`, or `None`. If specified the dequeue\n methods return a dictionary with the names as keys.\n shared_name: (Optional.) If non-empty, this queue will be shared under\n the given name across multiple sessions.\n name: Optional name for the queue operation.\n\n Raises:\n ValueError: If shapes is not a list of shapes, or the lengths of dtypes\n and shapes do not match, or if names is specified and the lengths of\n dtypes and names do not match.\n \"\"\"\n dtypes = _as_type_list(dtypes)\n shapes = _as_shape_list(shapes, dtypes, unknown_dim_allowed=True)\n names = _as_name_list(names, dtypes)\n if len(dtypes) != len(shapes):\n raise ValueError(\"Shapes must be provided for all components, \"\n \"but received %d dtypes and %d shapes.\"\n % (len(dtypes), len(shapes)))\n\n queue_ref = gen_data_flow_ops._padding_fifo_queue_v2(\n component_types=dtypes, shapes=shapes, capacity=capacity,\n shared_name=shared_name, name=name)\n\n super(PaddingFIFOQueue, self).__init__(dtypes, shapes, names, queue_ref)\n\n\nclass PriorityQueue(QueueBase):\n \"\"\"A queue implementation that dequeues elements in prioritized order.\n\n See [`tf.QueueBase`](#QueueBase) for a description of the methods on\n this class.\n\n @@__init__\n \"\"\"\n\n def __init__(self, capacity, types, shapes=None, names=None, shared_name=None,\n name=\"priority_queue\"):\n \"\"\"Creates a queue that dequeues elements in a first-in first-out order.\n\n A `PriorityQueue` has bounded capacity; supports multiple concurrent\n producers and consumers; and provides exactly-once delivery.\n\n A `PriorityQueue` holds a list of up to `capacity` elements. Each\n element is a fixed-length tuple of tensors whose dtypes are\n described by `types`, and whose shapes are optionally described\n by the `shapes` argument.\n\n If the `shapes` argument is specified, each component of a queue\n element must have the respective fixed shape. If it is\n unspecified, different queue elements may have different shapes,\n but the use of `dequeue_many` is disallowed.\n\n Enqueues and Dequeues to the `PriorityQueue` must include an additional\n tuple entry at the beginning: the `priority`. The priority must be\n an int64 scalar (for `enqueue`) or an int64 vector (for `enqueue_many`).\n\n Args:\n capacity: An integer. The upper bound on the number of elements\n that may be stored in this queue.\n types: A list of `DType` objects. The length of `types` must equal\n the number of tensors in each queue element, except the first priority\n element. The first tensor in each element is the priority,\n which must be type int64.\n shapes: (Optional.) A list of fully-defined `TensorShape` objects,\n with the same length as `types`, or `None`.\n names: (Optional.) A list of strings naming the components in the queue\n with the same length as `dtypes`, or `None`. If specified, the dequeue\n methods return a dictionary with the names as keys.\n shared_name: (Optional.) If non-empty, this queue will be shared under\n the given name across multiple sessions.\n name: Optional name for the queue operation.\n \"\"\"\n types = _as_type_list(types)\n shapes = _as_shape_list(shapes, types)\n\n queue_ref = gen_data_flow_ops._priority_queue_v2(\n component_types=types, shapes=shapes, capacity=capacity,\n shared_name=shared_name, name=name)\n\n priority_dtypes = [_dtypes.int64] + types\n priority_shapes = [()] + shapes if shapes else shapes\n\n super(PriorityQueue, self).__init__(\n priority_dtypes, priority_shapes, names, queue_ref)\n\n\n# TODO(josh11b): class BatchQueue(QueueBase):\n\n\nclass Barrier(object):\n \"\"\"Represents a key-value map that persists across graph executions.\"\"\"\n\n def __init__(self, types, shapes=None, shared_name=None, name=\"barrier\"):\n \"\"\"Creates a barrier that persists across different graph executions.\n\n A barrier represents a key-value map, where each key is a string, and\n each value is a tuple of tensors.\n\n At runtime, the barrier contains 'complete' and 'incomplete'\n elements. A complete element has defined tensors for all\n components of its value tuple, and may be accessed using\n take_many. An incomplete element has some undefined components in\n its value tuple, and may be updated using insert_many.\n\n The barrier call `take_many` outputs values in a particular order.\n First, it only outputs completed values. Second, the order in which\n completed values are returned matches the order in which their very\n first component was inserted into the barrier. So, for example, for this\n sequence of insertions and removals:\n\n barrier = Barrier((tf.string, tf.int32), shapes=((), ()))\n barrier.insert_many(0, keys=[\"k1\", \"k2\"], values=[\"a\", \"b\"]).run()\n barrier.insert_many(1, keys=[\"k1\"], values=[1]).run()\n barrier.insert_many(0, keys=[\"k3\"], values=[\"c\"]).run()\n barrier.insert_many(1, keys=[\"k3\"], values=[3]).run()\n barrier.insert_many(1, keys=[\"k2\"], values=[2]).run()\n\n (indices, keys, values) = barrier.take_many(2)\n (indices_val, keys_val, values0_val, values1_val) =\n session.run([indices, keys, values[0], values[1]])\n\n The output will be (up to permutation of \"k1\" and \"k2\"):\n\n indices_val == (-2**63, -2**63)\n keys_val == (\"k1\", \"k2\")\n values0_val == (\"a\", \"b\")\n values1_val == (1, 2)\n\n Note the key \"k2\" was inserted into the barrier before \"k3\". Even though\n \"k3\" was completed first, both are complete by the time\n take_many is called. As a result, \"k2\" is prioritized and \"k1\" and \"k2\"\n are returned first. \"k3\" remains in the barrier until the next execution\n of `take_many`. Since \"k1\" and \"k2\" had their first insertions into\n the barrier together, their indices are the same (-2**63). The index\n of \"k3\" will be -2**63 + 1, because it was the next new inserted key.\n\n Args:\n types: A single dtype or a tuple of dtypes, corresponding to the\n dtypes of the tensor elements that comprise a value in this barrier.\n shapes: Optional. Constraints on the shapes of tensors in the values:\n a single tensor shape tuple; a tuple of tensor shape tuples\n for each barrier-element tuple component; or None if the shape should\n not be constrained.\n shared_name: Optional. If non-empty, this barrier will be shared under\n the given name across multiple sessions.\n name: Optional name for the barrier op.\n\n Raises:\n ValueError: If one of the `shapes` indicate no elements.\n \"\"\"\n self._types = _as_type_list(types)\n\n if shapes is not None:\n shapes = _as_shape_list(shapes, self._types)\n self._shapes = [tensor_shape.TensorShape(s) for s in shapes]\n for i, shape in enumerate(self._shapes):\n if shape.num_elements() == 0:\n raise ValueError(\"Empty tensors are not supported, but received \"\n \"shape '%s' at index %d\" % (shape, i))\n else:\n self._shapes = [tensor_shape.unknown_shape() for _ in self._types]\n\n self._barrier_ref = gen_data_flow_ops._barrier(\n component_types=self._types, shapes=self._shapes,\n shared_name=shared_name, name=name)\n self._name = self._barrier_ref.op.name.split(\"/\")[-1]\n\n @property\n def barrier_ref(self):\n \"\"\"Get the underlying barrier reference.\"\"\"\n return self._barrier_ref\n\n @property\n def name(self):\n \"\"\"The name of the underlying barrier.\"\"\"\n return self._barrier_ref.op.name\n\n def insert_many(self, component_index, keys, values, name=None):\n \"\"\"For each key, assigns the respective value to the specified component.\n\n This operation updates each element at component_index.\n\n Args:\n component_index: The component of the value that is being assigned.\n keys: A vector of keys, with length n.\n values: An any-dimensional tensor of values, which are associated with the\n respective keys. The first dimension must have length n.\n name: Optional name for the op.\n\n Returns:\n The operation that performs the insertion.\n Raises:\n InvalidArgumentsError: If inserting keys and values without elements.\n \"\"\"\n if name is None:\n name = \"%s_BarrierInsertMany\" % self._name\n return gen_data_flow_ops._barrier_insert_many(\n self._barrier_ref, keys, values, component_index, name=name)\n\n def take_many(self,\n num_elements,\n allow_small_batch=False,\n timeout=None,\n name=None):\n \"\"\"Takes the given number of completed elements from this barrier.\n\n This operation concatenates completed-element component tensors along\n the 0th dimension to make a single component tensor.\n\n If barrier has no completed elements, this operation will block\n until there are 'num_elements' elements to take.\n\n Args:\n num_elements: The number of elements to take.\n allow_small_batch: If the barrier is closed, don't block if there are less\n completed elements than requested, but instead return all available\n completed elements.\n TODO(b/25743580): the semantics of `allow_small_batch` are experimental\n and may be extended to other cases in the future.\n TODO(ebrevdo): If a take_many(allow_small_batch=True) is blocking\n already when the barrier is closed, it will block for ever. Fix this\n by using asynchronous operations.\n timeout: This specifies the number of milliseconds to block\n before returning with DEADLINE_EXCEEDED. (This option is not\n supported yet.)\n name: A name for the operation (optional).\n\n Returns:\n A tuple of (index, key, value_list).\n \"index\" is a int64 tensor of length num_elements containing the\n index of the insert_many call for which the very first component of\n the given element was inserted into the Barrier, starting with\n the value -2**63. Note, this value is different from the\n index of the insert_many call for which the element was completed.\n \"key\" is a string tensor of length num_elements containing the keys.\n \"value_list\" is a tuple of tensors, each one with size num_elements\n in the 0th dimension for each component in the barrier's values.\n\n \"\"\"\n if name is None:\n name = \"%s_BarrierTakeMany\" % self._name\n ret = gen_data_flow_ops._barrier_take_many(self._barrier_ref,\n num_elements,\n self._types,\n allow_small_batch,\n timeout,\n name=name)\n\n # NOTE(mrry): Not using a shape function because we need access to\n # the Barrier object.\n op = ret[0].op\n if allow_small_batch:\n batch_dim = None\n else:\n batch_dim = tensor_shape.Dimension(\n tensor_util.constant_value(op.inputs[1]))\n op.outputs[0].set_shape(tensor_shape.vector(batch_dim)) # indices\n op.outputs[1].set_shape(tensor_shape.vector(batch_dim)) # keys\n for output, shape in zip(op.outputs[2:], self._shapes): # value_list\n output.set_shape(tensor_shape.TensorShape([batch_dim]).concatenate(shape))\n\n return ret\n\n def close(self, cancel_pending_enqueues=False, name=None):\n \"\"\"Closes this barrier.\n\n This operation signals that no more new key values will be inserted in the\n given barrier. Subsequent InsertMany operations with new keys will fail.\n InsertMany operations that just complement already existing keys with other\n components, will continue to succeed. Subsequent TakeMany operations will\n continue to succeed if sufficient elements remain in the barrier. Subsequent\n TakeMany operations that would block will fail immediately.\n\n If `cancel_pending_enqueues` is `True`, all pending requests to the\n underlying queue will also be cancelled, and completing of already\n started values is also not acceptable anymore.\n\n Args:\n cancel_pending_enqueues: (Optional.) A boolean, defaulting to\n `False` (described above).\n name: Optional name for the op.\n\n Returns:\n The operation that closes the barrier.\n \"\"\"\n if name is None:\n name = \"%s_BarrierClose\" % self._name\n return gen_data_flow_ops._barrier_close(\n self._barrier_ref,\n cancel_pending_enqueues=cancel_pending_enqueues,\n name=name)\n\n def ready_size(self, name=None):\n \"\"\"Compute the number of complete elements in the given barrier.\n\n Args:\n name: A name for the operation (optional).\n\n Returns:\n A single-element tensor containing the number of complete elements in the\n given barrier.\n \"\"\"\n if name is None:\n name = \"%s_BarrierReadySize\" % self._name\n return gen_data_flow_ops._barrier_ready_size(self._barrier_ref, name=name)\n\n def incomplete_size(self, name=None):\n \"\"\"Compute the number of incomplete elements in the given barrier.\n\n Args:\n name: A name for the operation (optional).\n\n Returns:\n A single-element tensor containing the number of incomplete elements in\n the given barrier.\n \"\"\"\n if name is None:\n name = \"%s_BarrierIncompleteSize\" % self._name\n return gen_data_flow_ops._barrier_incomplete_size(\n self._barrier_ref, name=name)\n\n\n@deprecated(\"2017-03-02\", \"Use `tf.tables_initializer` instead.\")\ndef initialize_all_tables(name=\"init_all_tables\"):\n \"\"\"Returns an Op that initializes all tables of the default graph.\n\n Args:\n name: Optional name for the initialization op.\n\n Returns:\n An Op that initializes all tables. Note that if there are\n not tables the returned Op is a NoOp.\n \"\"\"\n return tables_initializer(name)\n\n\ndef tables_initializer(name=\"init_all_tables\"):\n \"\"\"Returns an Op that initializes all tables of the default graph.\n\n Args:\n name: Optional name for the initialization op.\n\n Returns:\n An Op that initializes all tables. Note that if there are\n not tables the returned Op is a NoOp.\n \"\"\"\n initializers = ops.get_collection(ops.GraphKeys.TABLE_INITIALIZERS)\n if initializers:\n return control_flow_ops.group(*initializers, name=name)\n return control_flow_ops.no_op(name=name)\n\n\nops.NotDifferentiable(\"LookupTableFind\")\nops.NotDifferentiable(\"LookupTableInsert\")\nops.NotDifferentiable(\"LookupTableSize\")\nops.NotDifferentiable(\"HashTable\")\nops.NotDifferentiable(\"InitializeTable\")\nops.NotDifferentiable(\"InitializeTableFromTextFile\")\nops.NotDifferentiable(\"MutableDenseHashTable\")\nops.NotDifferentiable(\"MutableHashTable\")\nops.NotDifferentiable(\"MutableHashTableOfTensors\")\n\n\nclass ConditionalAccumulatorBase(object):\n \"\"\"A conditional accumulator for aggregating gradients.\n\n Up-to-date gradients (i.e., time step at which gradient was computed is\n equal to the accumulator's time step) are added to the accumulator.\n\n Extraction of the average gradient is blocked until the required number of\n gradients has been accumulated.\n \"\"\"\n\n def __init__(self, dtype, shape, accumulator_ref):\n \"\"\"Creates a new ConditionalAccumulator.\n\n Args:\n dtype: Datatype of the accumulated gradients.\n shape: Shape of the accumulated gradients.\n accumulator_ref: A handle to the conditional accumulator, created by sub-\n classes\n \"\"\"\n self._dtype = dtype\n if shape is not None:\n self._shape = tensor_shape.TensorShape(shape)\n else:\n self._shape = tensor_shape.unknown_shape()\n self._accumulator_ref = accumulator_ref\n self._name = self._accumulator_ref.op.name.split(\"/\")[-1]\n\n @property\n def accumulator_ref(self):\n \"\"\"The underlying accumulator reference.\"\"\"\n return self._accumulator_ref\n\n @property\n def name(self):\n \"\"\"The name of the underlying accumulator.\"\"\"\n return self._name\n\n @property\n def dtype(self):\n \"\"\"The datatype of the gradients accumulated by this accumulator.\"\"\"\n return self._dtype\n\n def num_accumulated(self, name=None):\n \"\"\"Number of gradients that have currently been aggregated in accumulator.\n\n Args:\n name: Optional name for the operation.\n\n Returns:\n Number of accumulated gradients currently in accumulator.\n \"\"\"\n if name is None:\n name = \"%s_NumAccumulated\" % self._name\n return gen_data_flow_ops.accumulator_num_accumulated(\n self._accumulator_ref, name=name)\n\n def set_global_step(self, new_global_step, name=None):\n \"\"\"Sets the global time step of the accumulator.\n\n The operation logs a warning if we attempt to set to a time step that is\n lower than the accumulator's own time step.\n\n Args:\n new_global_step: Value of new time step. Can be a variable or a constant\n name: Optional name for the operation.\n\n Returns:\n Operation that sets the accumulator's time step.\n \"\"\"\n return gen_data_flow_ops.accumulator_set_global_step(\n self._accumulator_ref,\n math_ops.to_int64(ops.convert_to_tensor(new_global_step)),\n name=name)\n\n\nclass ConditionalAccumulator(ConditionalAccumulatorBase):\n \"\"\"A conditional accumulator for aggregating gradients.\n\n Up-to-date gradients (i.e., time step at which gradient was computed is\n equal to the accumulator's time step) are added to the accumulator.\n\n Extraction of the average gradient is blocked until the required number of\n gradients has been accumulated.\n \"\"\"\n\n def __init__(self,\n dtype,\n shape=None,\n shared_name=None,\n name=\"conditional_accumulator\"):\n \"\"\"Creates a new ConditionalAccumulator.\n\n Args:\n dtype: Datatype of the accumulated gradients.\n shape: Shape of the accumulated gradients.\n shared_name: Optional. If non-empty, this accumulator will be shared under\n the given name across multiple sessions.\n name: Optional name for the accumulator.\n \"\"\"\n accumulator_ref = gen_data_flow_ops.conditional_accumulator(\n dtype=dtype, shape=shape, shared_name=shared_name, name=name)\n super(ConditionalAccumulator, self).__init__(dtype, shape, accumulator_ref)\n\n def apply_grad(self, grad, local_step=0, name=None):\n \"\"\"Attempts to apply a gradient to the accumulator.\n\n The attempt is silently dropped if the gradient is stale, i.e., local_step\n is less than the accumulator's global time step.\n\n Args:\n grad: The gradient tensor to be applied.\n local_step: Time step at which the gradient was computed.\n name: Optional name for the operation.\n\n Returns:\n The operation that (conditionally) applies a gradient to the accumulator.\n\n Raises:\n ValueError: If grad is of the wrong shape\n \"\"\"\n grad = ops.convert_to_tensor(grad, self._dtype)\n grad.get_shape().assert_is_compatible_with(self._shape)\n local_step = math_ops.to_int64(ops.convert_to_tensor(local_step))\n return gen_data_flow_ops.accumulator_apply_gradient(\n self._accumulator_ref, local_step=local_step, gradient=grad, name=name)\n\n def take_grad(self, num_required, name=None):\n \"\"\"Attempts to extract the average gradient from the accumulator.\n\n The operation blocks until sufficient number of gradients have been\n successfully applied to the accumulator.\n\n Once successful, the following actions are also triggered:\n - Counter of accumulated gradients is reset to 0.\n - Aggregated gradient is reset to 0 tensor.\n - Accumulator's internal time step is incremented by 1.\n\n Args:\n num_required: Number of gradients that needs to have been aggregated\n name: Optional name for the operation\n\n Returns:\n A tensor holding the value of the average gradient.\n\n Raises:\n InvalidArgumentError: If num_required < 1\n \"\"\"\n return gen_data_flow_ops.accumulator_take_gradient(\n self._accumulator_ref, num_required, dtype=self._dtype, name=name)\n\n\nclass SparseConditionalAccumulator(ConditionalAccumulatorBase):\n \"\"\"A conditional accumulator for aggregating sparse gradients.\n\n Sparse gradients are represented by IndexedSlices.\n\n Up-to-date gradients (i.e., time step at which gradient was computed is\n equal to the accumulator's time step) are added to the accumulator.\n\n Extraction of the average gradient is blocked until the required number of\n gradients has been accumulated.\n\n Args:\n dtype: Datatype of the accumulated gradients.\n shape: Shape of the accumulated gradients.\n shared_name: Optional. If non-empty, this accumulator will be shared under\n the given name across multiple sessions.\n name: Optional name for the accumulator.\n \"\"\"\n\n def __init__(self,\n dtype,\n shape=None,\n shared_name=None,\n name=\"sparse_conditional_accumulator\"):\n accumulator_ref = gen_data_flow_ops.sparse_conditional_accumulator(\n dtype=dtype, shape=shape, shared_name=shared_name, name=name)\n super(SparseConditionalAccumulator,\n self).__init__(dtype, shape, accumulator_ref)\n\n def apply_indexed_slices_grad(self, grad, local_step=0, name=None):\n \"\"\"Attempts to apply a gradient to the accumulator.\n\n The attempt is silently dropped if the gradient is stale, i.e., local_step\n is less than the accumulator's global time step.\n\n Args:\n grad: The gradient IndexedSlices to be applied.\n local_step: Time step at which the gradient was computed.\n name: Optional name for the operation.\n\n Returns:\n The operation that (conditionally) applies a gradient to the accumulator.\n\n Raises:\n InvalidArgumentError: If grad is of the wrong shape\n \"\"\"\n return self.apply_grad(\n grad_indices=grad.indices,\n grad_values=grad.values,\n grad_shape=grad.dense_shape,\n local_step=local_step,\n name=name)\n\n def apply_grad(self,\n grad_indices,\n grad_values,\n grad_shape=None,\n local_step=0,\n name=None):\n \"\"\"Attempts to apply a sparse gradient to the accumulator.\n\n The attempt is silently dropped if the gradient is stale, i.e., local_step\n is less than the accumulator's global time step.\n\n A sparse gradient is represented by its indices, values and possibly empty\n or None shape. Indices must be a vector representing the locations of\n non-zero entries in the tensor. Values are the non-zero slices of the\n gradient, and must have the same first dimension as indices, i.e., the nnz\n represented by indices and values must be consistent. Shape, if not empty or\n None, must be consistent with the accumulator's shape (if also provided).\n\n Example:\n A tensor [[0, 0], [0. 1], [2, 3]] can be represented\n indices: [1,2]\n values: [[0,1],[2,3]]\n shape: [3, 2]\n\n Args:\n grad_indices: Indices of the sparse gradient to be applied.\n grad_values: Values of the sparse gradient to be applied.\n grad_shape: Shape of the sparse gradient to be applied.\n local_step: Time step at which the gradient was computed.\n name: Optional name for the operation.\n\n Returns:\n The operation that (conditionally) applies a gradient to the accumulator.\n\n Raises:\n InvalidArgumentError: If grad is of the wrong shape\n \"\"\"\n local_step = math_ops.to_int64(ops.convert_to_tensor(local_step))\n return gen_data_flow_ops.sparse_accumulator_apply_gradient(\n self._accumulator_ref,\n local_step=local_step,\n gradient_indices=math_ops.to_int64(grad_indices),\n gradient_values=grad_values,\n gradient_shape=math_ops.to_int64([] if grad_shape is None else\n grad_shape),\n has_known_shape=(grad_shape is not None),\n name=name)\n\n def take_grad(self, num_required, name=None):\n \"\"\"Attempts to extract the average gradient from the accumulator.\n\n The operation blocks until sufficient number of gradients have been\n successfully applied to the accumulator.\n\n Once successful, the following actions are also triggered:\n - Counter of accumulated gradients is reset to 0.\n - Aggregated gradient is reset to 0 tensor.\n - Accumulator's internal time step is incremented by 1.\n\n Args:\n num_required: Number of gradients that needs to have been aggregated\n name: Optional name for the operation\n\n Returns:\n A tuple of indices, values, and shape representing the average gradient.\n\n Raises:\n InvalidArgumentError: If num_required < 1\n \"\"\"\n return gen_data_flow_ops.sparse_accumulator_take_gradient(\n self._accumulator_ref, num_required, dtype=self._dtype, name=name)\n\n def take_indexed_slices_grad(self, num_required, name=None):\n \"\"\"Attempts to extract the average gradient from the accumulator.\n\n The operation blocks until sufficient number of gradients have been\n successfully applied to the accumulator.\n\n Once successful, the following actions are also triggered:\n - Counter of accumulated gradients is reset to 0.\n - Aggregated gradient is reset to 0 tensor.\n - Accumulator's internal time step is incremented by 1.\n\n Args:\n num_required: Number of gradients that needs to have been aggregated\n name: Optional name for the operation\n\n Returns:\n An IndexedSlices holding the value of the average gradient.\n\n Raises:\n InvalidArgumentError: If num_required < 1\n \"\"\"\n return_val = gen_data_flow_ops.sparse_accumulator_take_gradient(\n self._accumulator_ref, num_required, dtype=self._dtype, name=name)\n return ops.IndexedSlices(\n indices=return_val.indices,\n values=return_val.values,\n dense_shape=return_val.shape)\n\n\nclass StagingArea(object):\n \"\"\"Class for staging inputs. No ordering guarantees.\n\n A `StagingArea` is a TensorFlow data structure that stores tensors across\n multiple steps, and exposes operations that can put and get\n tensors.\n\n Each `StagingArea` element is a tuple of one or more tensors, where each\n tuple component has a static dtype, and may have a static shape.\n\n The capacity of a `StagingArea` is unbounded and supports multiple\n concurrent producers and consumers; and provides exactly-once delivery.\n\n Each element of a `StagingArea` is a fixed-length tuple of tensors whose\n dtypes are described by `dtypes`, and whose shapes are optionally described\n by the `shapes` argument.\n\n If the `shapes` argument is specified, each component of a staging area\n element must have the respective fixed shape. If it is\n unspecified, different elements may have different shapes,\n \"\"\"\n\n _identifier = 0\n _lock = threading.Lock()\n\n def __init__(self, dtypes, shapes=None, names=None, shared_name=None):\n \"\"\"Constructs a staging area object.\n\n The two optional lists, `shapes` and `names`, must be of the same length\n as `dtypes` if provided. The values at a given index `i` indicate the\n shape and name to use for the corresponding queue component in `dtypes`.\n\n Args:\n dtypes: A list of types. The length of dtypes must equal the number\n of tensors in each element.\n shapes: (Optional.) Constraints on the shapes of tensors in an element.\n A list of shape tuples or None. This list is the same length\n as dtypes. If the shape of any tensors in the element are constrained,\n all must be; shapes can be None if the shapes should not be constrained.\n names: (Optional.) If provided, the `get()` and\n `put()` methods will use dictionaries with these names as keys.\n Must be None or a list or tuple of the same length as `dtypes`.\n shared_name: (Optional.) A name to be used for the shared object. By\n passing the same name to two different python objects they will share\n the underlying staging area. Must be a string.\n\n Raises:\n ValueError: If one of the arguments is invalid.\n \"\"\"\n if shared_name is None:\n self._name = ops.get_default_graph().unique_name(\"StagingArea\")\n elif isinstance(shared_name, six.string_types):\n self._name = shared_name\n else:\n raise ValueError(\"shared_name must be a string\")\n self._dtypes = dtypes\n if shapes is not None:\n if len(shapes) != len(dtypes):\n raise ValueError(\"StagingArea shapes must be the same length as dtypes\")\n self._shapes = [tensor_shape.TensorShape(s) for s in shapes]\n else:\n self._shapes = [tensor_shape.unknown_shape() for _ in self._dtypes]\n if names is not None:\n if len(names) != len(dtypes):\n raise ValueError(\"StagingArea names must be the same length as dtypes\")\n self._names = names\n else:\n self._names = None\n\n @property\n def name(self):\n \"\"\"The name of the staging area.\"\"\"\n return self._name\n\n @property\n def dtypes(self):\n \"\"\"The list of dtypes for each component of a staging area element.\"\"\"\n return self._dtypes\n\n @property\n def shapes(self):\n \"\"\"The list of shapes for each component of a staging area element.\"\"\"\n return self._shapes\n\n @property\n def names(self):\n \"\"\"The list of names for each component of a staging area element.\"\"\"\n return self._names\n\n def _check_put_dtypes(self, vals):\n \"\"\"Validate and convert `vals` to a list of `Tensor`s.\n\n The `vals` argument can be a Tensor, a list or tuple of tensors, or a\n dictionary with tensor values.\n\n If it is a dictionary, the staging area must have been constructed with a\n `names` attribute and the dictionary keys must match the staging area names.\n If the staging area was constructed with a `names` attribute, `vals` must\n be a dictionary.\n\n Args:\n vals: A tensor, a list or tuple of tensors, or a dictionary..\n\n Returns:\n A list of `Tensor` objects.\n\n Raises:\n ValueError: If `vals` is invalid.\n \"\"\"\n if isinstance(vals, dict):\n if not self._names:\n raise ValueError(\n \"Staging areas must have names to enqueue a dictionary\")\n if sorted(self._names) != sorted(vals.keys()):\n raise ValueError(\"Keys in dictionary to put do not match names \"\n \"of staging area. Dictionary: (%s), Queue: (%s)\" %\n (sorted(vals.keys()), sorted(self._names)))\n # The order of values in `self._names` indicates the order in which the\n # tensors in the dictionary `vals` must be listed.\n vals = [vals[k] for k in self._names]\n else:\n if self._names:\n raise ValueError(\"You must enqueue a dictionary in a staging area \"\n \"with names\")\n if not isinstance(vals, (list, tuple)):\n vals = [vals]\n\n tensors = []\n for i, (val, dtype) in enumerate(zip(vals, self._dtypes)):\n tensors.append(\n ops.convert_to_tensor(\n val, dtype=dtype, name=\"component_%d\" % i))\n\n return tensors\n\n def _scope_vals(self, vals):\n \"\"\"Return a list of values to pass to `name_scope()`.\n\n Args:\n vals: A tensor, a list or tuple of tensors, or a dictionary.\n\n Returns:\n The values in vals as a list.\n \"\"\"\n if isinstance(vals, (list, tuple)):\n return vals\n elif isinstance(vals, dict):\n return vals.values()\n else:\n return [vals]\n\n def put(self, values, name=None):\n with ops.name_scope(name, \"%s_put\" % self._name,\n self._scope_vals(values)) as scope:\n vals = self._check_put_dtypes(values)\n if len(values) != len(self._dtypes):\n raise ValueError(\"Unexpected number of inputs \" + str(len(values)) +\n \"vs \" + str(len(self._dtypes)))\n for val, dtype in zip(vals, self._dtypes):\n if val.dtype != dtype:\n raise ValueError(\"Datatypes do not match. \" + str(val.dtype) + \" != \"\n + str(dtype))\n\n for val, shape in zip(vals, self._shapes):\n val.get_shape().assert_is_compatible_with(shape)\n\n return gen_data_flow_ops.stage(vals, shared_name=self._name, name=scope)\n\n def _get_return_value(self, tensors):\n \"\"\"Return the value to return from a get op.\n\n If the staging area has names, return a dictionary with the\n names as keys. Otherwise return either a single tensor\n or a list of tensors depending on the length of `tensors`.\n\n Args:\n tensors: List of tensors from the get op.\n\n Returns:\n A single tensor, a list of tensors, or a dictionary\n of tensors.\n \"\"\"\n if self._names:\n # The returned values in `tensors` are in the same order as\n # the names in `self._names`.\n return {n: tensors[i] for i, n in enumerate(self._names)}\n elif len(tensors) == 1:\n return tensors[0]\n else:\n return tensors\n\n def get(self, name=None):\n \"\"\"Gets one element from this staging area.\n\n If the staging area is empty when this operation executes, it will block\n until there is an element to dequeue.\n\n Args:\n name: A name for the operation (optional).\n\n Returns:\n The tuple of tensors that was gotten.\n \"\"\"\n if name is None:\n name = \"%s_get\" % self._name\n\n ret = gen_data_flow_ops.unstage(self._dtypes, shared_name=self._name,\n name=name)\n\n for output, shape in zip(ret, self._shapes):\n output.set_shape(shape)\n\n return self._get_return_value(ret)\n\n\nclass RecordInput(object):\n \"\"\"RecordInput asynchronously reads and randomly yields TFRecords.\n\n A RecordInput Op will continuously read a batch of records asynchronously\n into a buffer of some fixed capacity. It can also asynchronously yield\n random records from this buffer.\n\n It will not start yielding until at least `buffer_size / 2` elements have been\n placed into the buffer so that sufficient randomization can take place.\n\n The order the files are read will be shifted each epoch by `shift_amount` so\n that the data is presented in a different order every epoch.\n \"\"\"\n\n def __init__(self,\n file_pattern,\n batch_size=1,\n buffer_size=1,\n parallelism=1,\n shift_ratio=0,\n seed=0,\n name=None):\n \"\"\"Constructs a RecordInput Op.\n\n Args:\n file_pattern: File path to the dataset, possibly containing wildcards.\n All matching files will be iterated over each epoch.\n batch_size: How many records to return at a time.\n buffer_size: The maximum number of records the buffer will contain. This\n _must_ be smaller than the total number of records in an epoch or\n deadlock can occur.\n parallelism: How many reader threads to use for reading from files.\n shift_ratio: What percentage of the total number files to move the start\n file forward by each epoch.\n seed: Specify the random number seed used by generator that randomizes\n records.\n name: Optional name for the operation.\n\n Raises:\n ValueError: If one of the arguments is invalid.\n \"\"\"\n\n self._batch_size = batch_size\n self._file_pattern = file_pattern\n self._buffer_size = buffer_size\n self._parallelism = parallelism\n self._shift_ratio = shift_ratio\n self._seed = seed\n self._name = name\n\n def get_yield_op(self):\n \"\"\"Add a node that yields a minibatch every time it is executed.\"\"\"\n return gen_data_flow_ops.record_input(\n file_pattern=self._file_pattern,\n file_buffer_size=self._buffer_size,\n file_parallelism=self._parallelism,\n file_shuffle_shift_ratio=self._shift_ratio,\n batch_size=self._batch_size,\n file_random_seed=self._seed,\n name=self._name)\n"
]
| [
[
"tensorflow.python.ops.gen_data_flow_ops.sparse_accumulator_take_gradient",
"tensorflow.python.ops.gen_data_flow_ops._padding_fifo_queue_v2",
"tensorflow.python.ops.gen_data_flow_ops._barrier_close",
"tensorflow.python.ops.gen_data_flow_ops._priority_queue_v2",
"tensorflow.python.ops.gen_data_flow_ops.accumulator_take_gradient",
"tensorflow.python.ops.array_ops.stack",
"tensorflow.python.ops.gen_data_flow_ops.accumulator_apply_gradient",
"tensorflow.python.framework.tensor_shape.vector",
"tensorflow.python.framework.ops.get_collection",
"tensorflow.python.ops.gen_data_flow_ops._barrier_take_many",
"tensorflow.python.ops.gen_data_flow_ops.stage",
"tensorflow.python.ops.gen_data_flow_ops._barrier",
"tensorflow.python.framework.ops.IndexedSlices",
"tensorflow.python.ops.gen_data_flow_ops._queue_dequeue_up_to_v2",
"tensorflow.python.framework.tensor_util.constant_value",
"tensorflow.python.ops.gen_data_flow_ops._queue_dequeue",
"tensorflow.python.ops.gen_data_flow_ops.unstage",
"tensorflow.python.ops.gen_data_flow_ops.record_input",
"tensorflow.python.util.deprecation.deprecated",
"tensorflow.python.ops.gen_data_flow_ops._random_shuffle_queue_v2",
"tensorflow.python.ops.gen_data_flow_ops._fifo_queue_v2",
"tensorflow.python.ops.math_ops.to_int64",
"tensorflow.python.ops.gen_data_flow_ops._queue_size_v2",
"tensorflow.python.ops.gen_data_flow_ops._queue_close",
"tensorflow.python.framework.ops.NotDifferentiable",
"tensorflow.python.ops.array_ops.gather",
"tensorflow.python.ops.control_flow_ops.no_op",
"tensorflow.python.ops.gen_data_flow_ops.accumulator_num_accumulated",
"tensorflow.python.ops.gen_data_flow_ops._queue_enqueue_many_v2",
"tensorflow.python.ops.gen_data_flow_ops._queue_dequeue_v2",
"tensorflow.python.ops.gen_data_flow_ops._queue_enqueue",
"tensorflow.python.ops.gen_data_flow_ops._barrier_incomplete_size",
"tensorflow.python.ops.gen_data_flow_ops._queue_dequeue_many_v2",
"tensorflow.python.ops.gen_data_flow_ops.sparse_conditional_accumulator",
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.python.ops.gen_data_flow_ops._barrier_insert_many",
"tensorflow.python.framework.tensor_shape.unknown_shape",
"tensorflow.python.ops.control_flow_ops.group",
"tensorflow.python.framework.random_seed.get_seed",
"tensorflow.python.framework.tensor_shape.as_shape",
"tensorflow.python.ops.gen_data_flow_ops._barrier_ready_size",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.gen_data_flow_ops._queue_size",
"tensorflow.python.ops.gen_data_flow_ops._queue_enqueue_v2",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.ops.gen_data_flow_ops.conditional_accumulator",
"tensorflow.python.ops.gen_data_flow_ops._queue_close_v2"
]
]
|
ZhenLiuBuaa/wDAE_GNN_FewShot | [
"6db1e4b1fe99821ffa116be009b5765f47932400"
]
| [
"low_shot_learning/datasets/mini_imagenet_dataset.py"
]
| [
"from __future__ import print_function\n\nimport os\nimport os.path\nimport random\n\nimport h5py\nimport numpy as np\nimport torch\nimport torch.utils.data as data\nimport torchvision.transforms as transforms\nfrom PIL import Image\n\nimport low_shot_learning.utils as utils\n\n# Set the appropriate paths of the datasets here.\n_MINI_IMAGENET_DATASET = '/datasets_local/MiniImagenet/'\n\n_MEAN_PIXEL = [x / 255.0 for x in [120.39586422, 115.59361427, 104.54012653]]\n_STD_PIXEL = [x / 255.0 for x in [70.68188272, 68.27635443, 72.54505529]]\n\n\nclass MiniImageNetBase(data.Dataset):\n def __init__(\n self,\n transform_test,\n transform_train,\n phase='train',\n load_single_file_split=False,\n file_split=None,\n do_not_use_random_transf=False):\n\n data_dir = _MINI_IMAGENET_DATASET\n print('==> Download MiniImageNet dataset at {0}'.format(data_dir))\n file_train_categories_train_phase = os.path.join(\n data_dir, 'miniImageNet_category_split_train_phase_train.pickle')\n file_train_categories_val_phase = os.path.join(\n data_dir, 'miniImageNet_category_split_train_phase_val.pickle')\n file_train_categories_test_phase = os.path.join(\n data_dir, 'miniImageNet_category_split_train_phase_test.pickle')\n file_val_categories_val_phase = os.path.join(\n data_dir, 'miniImageNet_category_split_val.pickle')\n file_test_categories_test_phase = os.path.join(\n data_dir, 'miniImageNet_category_split_test.pickle')\n\n self.phase = phase\n if load_single_file_split:\n assert file_split in ('category_split_train_phase_train',\n 'category_split_train_phase_val',\n 'category_split_train_phase_test',\n 'category_split_val',\n 'category_split_test')\n self.file_split = file_split\n self.name = 'MiniImageNet_' + file_split\n\n print(\n '==> Loading mini ImageNet dataset - phase {0}'\n .format(file_split))\n\n file_to_load = os.path.join(\n data_dir,\n 'miniImageNet_{0}.pickle'.format(file_split))\n\n data = utils.load_pickle_data(file_to_load)\n self.data = data['data']\n self.labels = data['labels']\n self.label2ind = utils.buildLabelIndex(self.labels)\n self.labelIds = sorted(self.label2ind.keys())\n self.num_cats = len(self.labelIds)\n else:\n assert(phase in ('train', 'val', 'test', 'trainval'))\n self.name = 'MiniImageNet_' + phase\n\n print('Loading mini ImageNet dataset - phase {0}'.format(phase))\n if self.phase=='train':\n # Loads the training classes (and their data) as base classes\n data_train = utils.load_pickle_data(\n file_train_categories_train_phase)\n self.data = data_train['data']\n self.labels = data_train['labels']\n\n self.label2ind = utils.buildLabelIndex(self.labels)\n self.labelIds = sorted(self.label2ind.keys())\n self.num_cats = len(self.labelIds)\n self.labelIds_base = self.labelIds\n self.num_cats_base = len(self.labelIds_base)\n\n elif self.phase=='trainval':\n # Loads the training + validation classes (and their data) as\n # base classes\n data_train = utils.load_pickle_data(\n file_train_categories_train_phase)\n data_val = utils.load_pickle_data(\n file_val_categories_val_phase)\n self.data = np.concatenate(\n [data_train['data'], data_val['data']], axis=0)\n self.labels = data_train['labels'] + data_val['labels']\n\n self.label2ind = utils.buildLabelIndex(\n self.labels)\n self.labelIds = sorted(self.label2ind.keys())\n self.num_cats = len(self.labelIds)\n self.labelIds_base = self.labelIds\n self.num_cats_base = len(self.labelIds_base)\n\n elif self.phase=='val' or self.phase=='test':\n # Uses the validation / test classes (and their data) as novel\n # as novel class data and the vaditation / test image split of\n # the training classes for the base classes.\n\n if self.phase=='test':\n # load data that will be used for evaluating the recognition\n # accuracy of the base classes.\n data_base = utils.load_pickle_data(\n file_train_categories_test_phase)\n # load data that will be use for evaluating the few-shot\n # recogniton accuracy on the novel classes.\n data_novel = utils.load_pickle_data(\n file_test_categories_test_phase)\n else: # phase=='val'\n # load data that will be used for evaluating the recognition\n # accuracy of the base classes.\n data_base = utils.load_pickle_data(\n file_train_categories_val_phase)\n # load data that will be use for evaluating the few-shot\n # recogniton accuracy on the novel classes.\n data_novel = utils.load_pickle_data(\n file_val_categories_val_phase)\n\n self.data = np.concatenate(\n [data_base['data'], data_novel['data']], axis=0)\n self.labels = data_base['labels'] + data_novel['labels']\n\n self.label2ind = utils.buildLabelIndex(self.labels)\n self.labelIds = sorted(self.label2ind.keys())\n self.num_cats = len(self.labelIds)\n\n self.labelIds_base = utils.buildLabelIndex(data_base['labels']).keys()\n self.labelIds_novel = utils.buildLabelIndex(data_novel['labels']).keys()\n self.num_cats_base = len(self.labelIds_base)\n self.num_cats_novel = len(self.labelIds_novel)\n intersection = set(self.labelIds_base) & set(self.labelIds_novel)\n assert len(intersection) == 0\n else:\n raise ValueError('Not valid phase {0}'.format(self.phase))\n\n self.transform_test = transform_test\n self.transform_train = transform_train\n if ((self.phase=='test' or self.phase=='val') or\n (do_not_use_random_transf==True)):\n self.transform = self.transform_test\n else:\n self.transform = self.transform_train\n\n def __getitem__(self, index):\n img, label = self.data[index], self.labels[index]\n # doing this so that it is consistent with all other datasets\n # to return a PIL Image\n img = Image.fromarray(img)\n img = self.transform(img)\n\n return img, label\n\n def __len__(self):\n return len(self.data)\n\n\nclass MiniImageNet(MiniImageNetBase):\n def __init__(\n self,\n phase='train',\n image_size=84,\n load_single_file_split=False,\n file_split=None,\n do_not_use_random_transf=False):\n\n normalize = transforms.Normalize(mean=_MEAN_PIXEL, std=_STD_PIXEL)\n\n if image_size==84:\n\n transform_test = transforms.Compose([\n lambda x: np.asarray(x),\n transforms.ToTensor(),\n normalize])\n\n transform_train = transforms.Compose([\n transforms.RandomCrop(84, padding=8),\n transforms.RandomHorizontalFlip(),\n lambda x: np.asarray(x),\n transforms.ToTensor(),\n normalize])\n else:\n assert image_size > 0\n\n transform_test = transforms.Compose([\n transforms.Resize(image_size),\n lambda x: np.asarray(x),\n transforms.ToTensor(),\n normalize,])\n\n transform_train = transforms.Compose([\n transforms.RandomCrop(84, padding=8),\n transforms.Resize(image_size),\n transforms.RandomHorizontalFlip(),\n lambda x: np.asarray(x),\n transforms.ToTensor(),\n normalize,])\n\n\n MiniImageNetBase.__init__(\n self,\n transform_test=transform_test,\n transform_train=transform_train,\n phase=phase,\n load_single_file_split=load_single_file_split,\n file_split=file_split,\n do_not_use_random_transf=do_not_use_random_transf)\n\n\nclass MiniImageNet80x80(MiniImageNet):\n def __init__(\n self,\n phase='train',\n load_single_file_split=False,\n file_split=None,\n do_not_use_random_transf=False):\n\n MiniImageNet.__init__(\n self,\n phase=phase,\n image_size=80,\n load_single_file_split=load_single_file_split,\n file_split=file_split,\n do_not_use_random_transf=do_not_use_random_transf)\n\n\ndef load_features_labels(dataset_file):\n data_file = h5py.File(dataset_file, 'r')\n count = data_file['count'][0]\n features = data_file['all_features'][...]\n labels = data_file['all_labels'][:count].tolist()\n features = features[:count,:]\n\n return data_file, count, features, labels\n\n\nclass MiniImageNetFeatures(data.Dataset):\n def __init__(self, data_directory, phase='train'):\n file_train_categories_train_phase = os.path.join(\n data_directory,\n 'MiniImageNet_category_split_train_phase_train.json')\n file_train_categories_val_phase = os.path.join(\n data_directory,\n 'MiniImageNet_category_split_train_phase_val.json')\n file_train_categories_test_phase = os.path.join(\n data_directory,\n 'MiniImageNet_category_split_train_phase_test.json')\n file_val_categories_val_phase = os.path.join(\n data_directory,\n 'MiniImageNet_category_split_val.json')\n file_test_categories_test_phase = os.path.join(\n data_directory,\n 'MiniImageNet_category_split_test.json')\n\n self.phase = phase\n assert phase in ('train', 'val', 'test', 'trainval')\n self.name = 'MiniImageNetFeatures_Phase_' + phase\n\n print('Loading mini ImageNet dataset - phase {0}'.format(phase))\n if self.phase=='train':\n # During training phase we only load the training phase images\n # of the training categories (aka base categories).\n _, _, features, labels = load_features_labels(\n file_train_categories_train_phase)\n\n self.features = features\n self.labels = labels\n\n self.label2ind = utils.buildLabelIndex(self.labels)\n self.labelIds = sorted(self.label2ind.keys())\n self.num_cats = len(self.labelIds)\n self.labelIds_base = self.labelIds\n self.num_cats_base = len(self.labelIds_base)\n\n elif self.phase=='trainval':\n _, _, features_train, labels_train = load_features_labels(\n file_train_categories_train_phase)\n _, _, features_val, labels_val = load_features_labels(\n file_val_categories_val_phase)\n\n self.features = np.concatenate(\n [features_train, features_val], axis=0)\n self.labels = labels_train + labels_val\n\n self.label2ind = utils.buildLabelIndex(self.labels)\n self.labelIds = sorted(self.label2ind.keys())\n self.num_cats = len(self.labelIds)\n self.labelIds_base = self.labelIds\n self.num_cats_base = len(self.labelIds_base)\n elif self.phase=='val' or self.phase=='test':\n if self.phase=='test':\n # load data that will be used for evaluating the recognition\n # accuracy of the base categories.\n _, _, base_features, base_labels = load_features_labels(\n file_train_categories_test_phase)\n\n # load data that will be use for evaluating the few-shot\n # recogniton accuracy on the novel categories.\n _, _, novel_features, novel_labels = load_features_labels(\n file_test_categories_test_phase)\n else: # phase=='val'\n # load data that will be used for evaluating the\n # recognition accuracy of the base categories.\n _, _, base_features, base_labels = load_features_labels(\n file_train_categories_val_phase)\n\n # load data that will be use for evaluating the few-shot\n # recogniton accuracy on the novel categories.\n _, _, novel_features, novel_labels = load_features_labels(\n file_val_categories_val_phase)\n\n self.features = np.concatenate(\n [base_features, novel_features], axis=0)\n self.labels = base_labels + novel_labels\n\n self.label2ind = utils.buildLabelIndex(self.labels)\n self.labelIds = sorted(self.label2ind.keys())\n self.num_cats = len(self.labelIds)\n\n self.labelIds_base = utils.buildLabelIndex(base_labels).keys()\n self.labelIds_novel = utils.buildLabelIndex(novel_labels).keys()\n self.num_cats_base = len(self.labelIds_base)\n self.num_cats_novel = len(self.labelIds_novel)\n intersection = set(self.labelIds_base) & set(self.labelIds_novel)\n assert len(intersection) == 0\n else:\n raise ValueError('Not valid phase {0}'.format(self.phase))\n\n def __getitem__(self, index):\n features_this = torch.Tensor(self.features[index]).view(-1,1,1)\n label_this = self.labels[index]\n return features_this, label_this\n\n def __len__(self):\n return len(self.data)\n"
]
| [
[
"numpy.concatenate",
"torch.Tensor",
"numpy.asarray"
]
]
|
javabean68/alaricus | [
"116f57aacff2cd32e6d1406700a609e3cbc6030e"
]
| [
"code/Euromillions/neural_network_2.py"
]
| [
"# Create your first MLP in Keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation\n\n\n\nimport dataset as ds\nimport numpy as np\nfrom display import *\nfrom keras import backend as K\nimport download\n\ndef my_loss(y_true, y_pred):\n return (1 - K.sum(y_true * y_pred, axis =-1))\n\nfrom sklearn.model_selection import train_test_split\n\nclass NeuralNetwork(object):\n def create(self, input_dim):\n # fix random seed for reproducibility\n seed = 42\n np.random.seed(seed) \n \n model = Sequential()\n model.add(Dense(51*7, kernel_initializer='random_uniform',\n bias_initializer='zeros', activation='sigmoid', input_dim=input_dim))\n \n \n\n \n \n \n model.add(Activation('softmax')) \n model.compile(optimizer='adam',\n loss='hinge',\n metrics=['accuracy'])\n \n return model\n\n def run(self):\n\n X, Y = ds.create_dataset(n_last_rows=5); \n \n X = ds.normalize_data(X, num=51)\n Y = ds.normalize_data(Y, num=51) \n \n X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0, random_state=42) \n \n \n nw = NeuralNetwork()\n \n model = nw.create(X_train.shape[1])\n print(model.summary())\n \n \n # Train the model, iterating on the data in batches of 16 samples\n model.fit(X_train, y_train, epochs=1000, batch_size=32)\n \n \n score = model.evaluate(X_test, y_test, batch_size=32)\n print(score)\n \n last_row = ds.get_last_row(n_last_rows=5)\n #print(last_row)\n last_row = ds.normalize_data(last_row, num=51)\n last_row = np.reshape(np.ravel(last_row), (1, 51 * 7 * 5)) \n \n \n \n y_proba = model.predict(last_row)\n \n \n predictions = list()\n for i in range(0,7):\n v = y_proba[0, i * 51 : (i+1) * 51] \n #print(1000 * v)\n display(10000 * np.reshape(v, (1, 51))) \n predictions.append(v.argmax(axis=-1))\n print(v.argmax(axis=-1))\n return predictions;\n \n"
]
| [
[
"numpy.random.seed",
"numpy.ravel",
"numpy.reshape",
"sklearn.model_selection.train_test_split"
]
]
|
NzLeuphana/QuantEcon.py | [
"1db07f1c49c5ff4810c6e3e84b00eb3ab28c8da5"
]
| [
"quantecon/markov/tests/test_approximation.py"
]
| [
"\"\"\"\nTests for approximation.py file (i.e. tauchen)\n\n\"\"\"\nimport sys\nimport unittest\nimport numpy as np\nfrom quantecon.markov import tauchen, rouwenhorst\n#from quantecon.markov.approximation import rouwenhorst\n\n\nclass TestTauchen(unittest.TestCase):\n\n def setUp(self):\n self.rho, self.sigma_u = np.random.rand(2)\n self.n = np.random.random_integers(3, 25)\n self.m = np.random.random_integers(4)\n self.tol = 1e-12\n\n mc = tauchen(self.rho, self.sigma_u, self.m, self.n)\n self.x, self.P = mc.state_values, mc.P\n\n def tearDown(self):\n del self.x\n del self.P\n\n def testShape(self):\n i, j = self.P.shape\n\n self.assertTrue(i == j)\n\n def testDim(self):\n dim_x = self.x.ndim\n dim_P = self.P.ndim\n\n self.assertTrue(dim_x == 1 and dim_P == 2)\n\n def test_transition_mat_row_sum_1(self):\n self.assertTrue(np.allclose(np.sum(self.P, axis=1), 1, atol=self.tol))\n\n def test_positive_probs(self):\n self.assertTrue(np.all(self.P) > -self.tol)\n\n def test_states_sum_0(self):\n self.assertTrue(abs(np.sum(self.x)) < self.tol)\n\n\nclass TestRouwenhorst(unittest.TestCase):\n\n def setUp(self):\n self.rho, self.sigma = np.random.uniform(0, 1, size=2)\n self.n = np.random.random_integers(3, 25)\n self.ybar = np.random.random_integers(0, 10)\n self.tol = 1e-12\n\n mc = rouwenhorst(self.n, self.ybar, self.sigma, self.rho)\n self.x, self.P = mc.state_values, mc.P\n\n def tearDown(self):\n del self.x\n del self.P\n\n def testShape(self):\n i, j = self.P.shape\n\n self.assertTrue(i == j)\n\n def testDim(self):\n dim_x = self.x.ndim\n dim_P = self.P.ndim\n self.assertTrue(dim_x == 1 and dim_P == 2)\n\n def test_transition_mat_row_sum_1(self):\n self.assertTrue(np.allclose(np.sum(self.P, axis=1), 1, atol=self.tol))\n\n def test_positive_probs(self):\n self.assertTrue(np.all(self.P) > -self.tol)\n\n def test_states_sum_0(self):\n tol = self.tol + self.n*(self.ybar/(1 - self.rho))\n self.assertTrue(abs(np.sum(self.x)) < tol)\n\n def test_control_case(self):\n n = 3; ybar = 1; sigma = 0.5; rho = 0.8;\n mc_rouwenhorst = rouwenhorst(n, ybar, sigma, rho)\n mc_rouwenhorst.x, mc_rouwenhorst.P = mc_rouwenhorst.state_values, mc_rouwenhorst.P\n sigma_y = np.sqrt(sigma**2 / (1-rho**2))\n psi = sigma_y * np.sqrt(n-1)\n known_x = np.array([-psi+5.0, 5., psi+5.0])\n known_P = np.array(\n [[0.81, 0.18, 0.01], [0.09, 0.82, 0.09], [0.01, 0.18, 0.81]])\n self.assertTrue(sum(mc_rouwenhorst.x - known_x) <\n self.tol and sum(sum(mc_rouwenhorst.P - known_P)) < self.tol)\n\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(\n [TestTauchen, TestRouwenhorst])\n unittest.TextTestRunner(verbosity=2, stream=sys.stderr).run(suite)\n"
]
| [
[
"numpy.array",
"numpy.random.rand",
"numpy.random.random_integers",
"numpy.sum",
"numpy.random.uniform",
"numpy.sqrt",
"numpy.all"
]
]
|
KyivAIGroup/iterative-winners-take-all | [
"8d5dec074d440c99206d89aac22c736d1a5bc413"
]
| [
"fig2.py"
]
| [
"\"\"\"\r\nHow weight sparsity changes the encoding sparsity.\r\n\"\"\"\r\n\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom pathlib import Path\r\n\r\nfrom kwta import iWTA\r\n\r\n# mpl.rcParams['grid.color'] = 'k'\r\n# mpl.rcParams['grid.linestyle'] = ':'\r\n# mpl.rcParams['grid.linewidth'] = 0.5\r\n\r\n# mpl.rcParams['figure.figsize'] = [10.0, 8.0]\r\n# mpl.rcParams['figure.dpi'] = 80\r\nmpl.rcParams['savefig.dpi'] = 800\r\nmpl.rcParams['savefig.format'] = 'pdf'\r\n\r\nmpl.rcParams['font.size'] = 14\r\nmpl.rcParams['legend.fontsize'] = 14\r\nmpl.rcParams['figure.titlesize'] = 14\r\n\r\n\r\ndef generate_random_vector(N, a_x):\r\n \"\"\"\r\n Generate a binary vector of size `N` with exactly `a_x` active neurons.\r\n \"\"\"\r\n vector = np.zeros(N, dtype=int)\r\n ones = np.random.choice(N, size=a_x, replace=False)\r\n vector[ones] = 1\r\n return vector\r\n\r\n\r\ndef generate_random_matrix(R, N, a_x):\r\n \"\"\"\r\n Generate a binary matrix of size (R, N) with exactly `a_x` active neurons\r\n per row.\r\n \"\"\"\r\n matrix = np.zeros((R, N), dtype=int)\r\n for i in range(R):\r\n matrix[i] = generate_random_vector(N, a_x)\r\n return matrix\r\n\r\nN_x = 200\r\nN_y = 200\r\nN_h = 200\r\n\r\na_x = 20\r\n\r\n# The no. of active synapses in a weight matrix per output neuron\r\na = {\r\n 'xy': 20,\r\n 'xh': 20,\r\n 'hy': 20,\r\n 'hh': 20,\r\n 'yh': 20,\r\n 'yy': 5,\r\n}\r\n\r\nw = {\r\n 'w_xy': generate_random_matrix(N_y, N_x, a['xy']),\r\n 'w_xh': generate_random_matrix(N_h, N_x, a['xh']),\r\n 'w_hy': generate_random_matrix(N_y, N_h, a['hy']),\r\n 'w_hh': generate_random_matrix(N_h, N_h, a['hh']),\r\n 'w_yh': generate_random_matrix(N_h, N_y, a['yh']),\r\n 'w_yy': generate_random_matrix(N_y, N_y, a['yy']),\r\n}\r\n\r\n# Set iters to 200 to reproduce the figure\r\niters = 10\r\n\r\n\r\ndef plot_w(weight, s='y'):\r\n weight = f\"w_{weight}\"\r\n print(f'plotting {weight}')\r\n N = w[weight].shape[1]\r\n w_range = np.arange(1, N, 5)\r\n Y = np.zeros((w_range.size, iters, N_y))\r\n H = np.zeros((w_range.size, iters, N_h))\r\n s_y = np.zeros((w_range.size, iters))\r\n s_h = np.zeros((w_range.size, iters))\r\n for k, a_i in enumerate(w_range):\r\n w[weight] = generate_random_matrix(w[weight].shape[0],\r\n w[weight].shape[1], a_i)\r\n for i in range(iters):\r\n x = generate_random_vector(N_x, a_x)\r\n H[k, i], Y[k, i] = iWTA(x, **w)\r\n s_y[k, i] = np.mean(Y[k, i])\r\n s_h[k, i] = np.mean(H[k, i])\r\n\r\n if s == 'y':\r\n # excitatory 'y' output population\r\n s_mean = np.mean(s_y, axis=1)\r\n s_std = np.std(s_y, axis=1)\r\n else:\r\n # inhibitory 'h' output population\r\n s_mean = np.mean(s_h, axis=1)\r\n s_std = np.std(s_h, axis=1)\r\n\r\n ax.plot(w_range / N, s_mean, label='w$^{%s}$' % weight[2:])\r\n ax.fill_between(w_range / N, s_mean + s_std, s_mean - s_std, alpha=0.5)\r\n\r\n # return to default\r\n w[weight] = generate_random_matrix(w[weight].shape[0], w[weight].shape[1],\r\n a[weight[2:]])\r\n\r\n\r\nfig, ax = plt.subplots(1)\r\nresults_dir = Path(\"results\")\r\nresults_dir.mkdir(exist_ok=True)\r\n\r\nplot_w('xy')\r\nplot_w('xh')\r\nplot_w('hy')\r\nplot_w('hh')\r\nplot_w('yh')\r\nplot_w('yy')\r\n\r\nax.legend()\r\nax.set_xlabel(r'$s_w$, weights sparsity')\r\nax.set_ylabel(r'$s_y$, y layer sparsity')\r\nplt.ylim([0, 1.05])\r\nplt.xlim([0, 1])\r\nfig.savefig(results_dir / 'fig2a.pdf', bbox_inches='tight')\r\n\r\nfig, ax = plt.subplots(1)\r\nplot_w('xy', 'h')\r\nplot_w('xh', 'h')\r\nplot_w('hy', 'h')\r\nplot_w('hh', 'h')\r\nplot_w('yh', 'h')\r\nplot_w('yy', 'h')\r\n\r\nax.legend()\r\nax.set_xlabel(r'$s_w$, weights sparsity')\r\nax.set_ylabel(r'$s_h$, h layer sparsity')\r\nplt.ylim([0, 1.05])\r\nplt.xlim([0, 1])\r\nfig.savefig(results_dir / 'fig2b.pdf', bbox_inches='tight')\r\nplt.show()\r\n"
]
| [
[
"matplotlib.pyplot.xlim",
"numpy.random.choice",
"numpy.zeros",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.subplots",
"numpy.mean",
"numpy.std",
"numpy.arange",
"matplotlib.pyplot.show"
]
]
|
1715labs/baal | [
"ee61f89c78353f7d50d4a3b3285ee52aab09dd12"
]
| [
"src/baal/utils/pytorch_lightning.py"
]
| [
"import sys\nimport types\nfrom abc import ABC\nfrom collections.abc import Sequence\nfrom typing import Dict, Any, Optional\n\nimport numpy as np\nimport structlog\nimport torch\nfrom baal.active import ActiveLearningDataset\nfrom baal.active.heuristics import heuristics\nfrom baal.modelwrapper import mc_inference\nfrom baal.utils.cuda_utils import to_cuda\nfrom baal.utils.iterutils import map_on_tensor\nfrom pytorch_lightning import Trainer, Callback, LightningDataModule, LightningModule\nfrom pytorch_lightning.accelerators import GPUAccelerator\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\n\nlog = structlog.get_logger('PL testing')\n\n\nclass BaaLDataModule(LightningDataModule):\n def __init__(self, active_dataset: ActiveLearningDataset, batch_size=1,\n **kwargs):\n super().__init__(**kwargs)\n self.active_dataset = active_dataset\n self.batch_size = batch_size\n\n def pool_dataloader(self):\n \"\"\"Create Dataloader for the pool of unlabelled examples.\"\"\"\n return DataLoader(self.active_dataset.pool,\n batch_size=self.batch_size, num_workers=4, shuffle=False)\n\n def on_load_checkpoint(self, checkpoint: Dict[str, Any]) -> None:\n if 'active_dataset' in checkpoint:\n self.active_dataset.load_state_dict(checkpoint['active_dataset'])\n else:\n log.warning(\"'active_dataset' not in checkpoint!\")\n\n def on_save_checkpoint(self, checkpoint: Dict[str, Any]) -> Dict:\n checkpoint['active_dataset'] = self.active_dataset.state_dict()\n return checkpoint\n\n\nclass ActiveLightningModule(LightningModule):\n \"\"\"Pytorch Lightning class which adds methods to perform\n active learning.\n \"\"\"\n\n def pool_dataloader(self):\n \"\"\"DataLoader for the pool. Must be defined if you do not use a DataModule\"\"\"\n raise NotImplementedError\n\n def predict_step(self, batch, batch_idx, dataloader_idx: Optional[int] = None):\n \"\"\"Predict on batch using MC inference `I` times.\n `I` is defined in the hparams property.\n Args:\n data (Tensor): Data to feed to the model.\n batch_idx (int): Batch index.\n dataloader_idx: Index of the current dataloader (not used)\n\n Returns:\n Models predictions stacked `I` times on the last axis.\n\n Notes:\n If `hparams.replicate_in_memeory` is True, we will stack inputs I times.\n This might create OoM errors. In that case, set it to False.\n \"\"\"\n # Get the input only.\n x, _ = batch\n # Perform Monte-Carlo Inference fro I iterations.\n out = mc_inference(self, x, self.hparams.iterations, self.hparams.replicate_in_memory)\n return out\n\n\nclass ResetCallback(Callback):\n \"\"\"Callback to reset the weights between active learning steps.\n\n Args:\n weights (dict): State dict of the model.\n\n Notes:\n The weight should be deep copied beforehand.\n\n \"\"\"\n\n def __init__(self, weights):\n self.weights = weights\n\n def on_train_start(self, trainer, module):\n \"\"\"Will reset the module to its initial weights.\"\"\"\n module.load_state_dict(self.weights)\n trainer.fit_loop.current_epoch = 0\n\n\nclass BaalTrainer(Trainer):\n \"\"\"Object that perform the training and active learning iteration.\n\n Args:\n dataset (ActiveLearningDataset): Dataset with some sample already labelled.\n heuristic (Heuristic): Heuristic from baal.active.heuristics.\n ndata_to_label (int): Number of sample to label per step.\n max_sample (int): Limit the number of sample used (-1 is no limit).\n **kwargs: Parameters forwarded to `get_probabilities`\n and to pytorch_ligthning Trainer.__init__\n \"\"\"\n\n def __init__(self, dataset: ActiveLearningDataset,\n heuristic: heuristics.AbstractHeuristic = heuristics.Random(),\n ndata_to_label: int = 1,\n **kwargs) -> None:\n\n super().__init__(**kwargs)\n self.ndata_to_label = ndata_to_label\n self.heuristic = heuristic\n self.dataset = dataset\n self.kwargs = kwargs\n\n def predict_on_dataset(self, model=None, dataloader=None, *args, **kwargs):\n \"For documentation, see `predict_on_dataset_generator`\"\n preds = list(self.predict_on_dataset_generator(model, dataloader))\n\n if len(preds) > 0 and not isinstance(preds[0], Sequence):\n # Is an Array or a Tensor\n return np.vstack(preds)\n return [np.vstack(pr) for pr in zip(*preds)]\n\n def predict_on_dataset_generator(self, model=None, dataloader=None, *args, **kwargs):\n \"\"\"Predict on the pool loader.\n\n Args:\n model: Model to be used in prediction. If None, will get the Trainer's model.\n dataloader (Optional[DataLoader]): If provided, will predict on this dataloader.\n Otherwise, uses model.pool_dataloader().\n\n Returns:\n Numpy arrays with all the predictions.\n \"\"\"\n model = model or self.lightning_module\n model.eval()\n if isinstance(self.accelerator, GPUAccelerator):\n model.cuda(self.accelerator.root_device)\n dataloader = dataloader or model.pool_dataloader()\n if len(dataloader) == 0:\n return None\n\n log.info(\"Start Predict\", dataset=len(dataloader))\n for idx, batch in enumerate(tqdm(dataloader, total=len(dataloader), file=sys.stdout)):\n if isinstance(self.accelerator, GPUAccelerator):\n batch = to_cuda(batch)\n pred = model.predict_step(batch, idx)\n yield map_on_tensor(lambda x: x.detach().cpu().numpy(), pred)\n # teardown, TODO customize this later?\n model.cpu()\n\n def step(self, model=None, datamodule: Optional[BaaLDataModule] = None) -> bool:\n \"\"\"\n Perform an active learning step.\n\n model: Model to be used in prediction. If None, will get the Trainer's model.\n dataloader (Optional[DataLoader]): If provided, will predict on this dataloader.\n Otherwise, uses model.pool_dataloader().\n\n Notes:\n This will get the pool from the model pool_dataloader and if max_sample is set, it will\n **require** the data_loader sampler to select `max_pool` samples.\n\n Returns:\n boolean, Flag indicating if we continue training.\n\n \"\"\"\n # High to low\n if datamodule is None:\n pool_dataloader = self.lightning_module.pool_dataloader()\n else:\n pool_dataloader = datamodule.pool_dataloader()\n model = model if model is not None else self.lightning_module\n\n if isinstance(pool_dataloader.sampler, torch.utils.data.sampler.RandomSampler):\n log.warning(\"Your pool_dataloader has `shuffle=True`,\"\n \" it is best practice to turn this off.\")\n\n if len(pool_dataloader) > 0:\n # TODO Add support for max_samples in pool_dataloader\n probs = self.predict_on_dataset_generator(model=model,\n dataloader=pool_dataloader, **self.kwargs)\n if probs is not None and (isinstance(probs, types.GeneratorType) or len(probs) > 0):\n to_label = self.heuristic(probs)\n if len(to_label) > 0:\n self.dataset.label(to_label[: self.ndata_to_label])\n return True\n return False\n"
]
| [
[
"torch.utils.data.DataLoader",
"numpy.vstack"
]
]
|
TobiasM95/TicTacToeZero | [
"ab85e67b6e1d47268b3e2796d2991e4d10ee5d76"
]
| [
"src/MCTS.py"
]
| [
"#!/usr/bin/env python3\nimport numpy as np\nfrom scipy.special import softmax\n\nNUMBER_SIMULATIONS = 100 #agz is 800\nMCTS_TEMPERATURE = 1.0\n\n#states are convnet states\n#actions are cnn output action vectors hot state\nclass Node():\n\n def __init__(self, state=None, action=None, prior=1.0):\n #root node has no parent and no action\n self.action = action\n self.state = state\n self.visit_count = 0\n self.total_val = 0\n self.mean_val = 0\n self.prior = prior\n self.children = []\n self.to_play = -1\n\n def update(self, value):\n self.visit_count += 1\n self.total_val += value\n self.mean_val = self.total_val / self.visit_count\n\n def is_expanded(self):\n return len(self.children) > 0\n\n def get_depth(self):\n depth = 0\n clist = [c for c in self.children]\n while(len(clist) > 0):\n clist = [c for p in clist for c in p.children ]\n depth += 1\n return depth\n\n def print_node(self, note = \"\"):\n print(\"Node details of\", note, \":\")\n if self.action is not None:\n ai = np.where(self.action == 1)[0]\n else:\n ai = None\n print(\"Action index:\", ai)\n print(\"State (convnet state, show current position):\")\n print(self.state[:,:,-3] + self.state[:,:,-2]*2)\n print(\"(N, W, Q, P) = (\",\n self.visit_count, \",\",\n self.total_val, \",\",\n self.mean_val, \",\",\n self.prior, \")\")\n print(\"To play\", self.to_play)\n print(\"Number of children\", len(self.children))\n print(\"Turns of children\", [np.where(c.action == 1)[0] for c in self.children])\n print(\"Max depth of node\", self.get_depth())\n\ndef run_mcts(game, network, print_root = False):\n root = Node(state = np.copy(game.get_convnet_input()))\n\n for _ in range(NUMBER_SIMULATIONS):\n sim_game = game.copy_game()\n node = root\n search_path = [node]\n\n terminal = False\n while(node.is_expanded()):\n action, node = select_mcts_action(node)\n sim_game.move(sim_game.cnn_action_to_coords(action))\n node.state = sim_game.get_convnet_input()\n search_path.append(node)\n if sim_game.state != -1:\n terminal = True\n\n value = evaluate_node_and_expand(node, network, sim_game, terminal)\n\n for node in reversed(search_path):\n v = value if node.to_play == sim_game.turn - 1 else (1 - value)\n node.update(v)\n if print_root:\n root.print_node(\"Root\")\n return choose_action(root), generate_mcts_policy(root)\n\ndef select_mcts_action(node):\n #UCTS? algorithm choice\n best_choice = (0, -1.0*np.inf)\n for i, child in enumerate(node.children):\n #in alpha zero paper this is described as slowly(log) growing exploration rate\n #set this here as constant for now\n PUCT_C = 1.0\n PUCT_U = PUCT_C*child.prior*np.sqrt(node.visit_count)/(1+child.visit_count)\n action_value = child.mean_val + PUCT_U\n if action_value >= best_choice[1]:\n best_choice = (i, action_value)\n\n return node.children[best_choice[0]].action, node.children[best_choice[0]]\n\ndef evaluate_node_and_expand(node, network, sim_game, terminal):\n if not terminal:\n #check where nodes stay in existence??\n policy_logits, value = network.evaluate(\n node.state.reshape(1,9,9,2*sim_game.NUMBER_OF_SAVED_GAME_STATES + 1))\n #value.shape = (1,1) policy_logits.shape = (1,81)\n else:\n if sim_game.state == 0:\n return 0.5\n else:\n return 0\n \n # Expand the node.\n node.to_play = sim_game.turn - 1\n legal_move_indices = sim_game.get_legal_move_indices()\n #policy = np.array([np.exp(policy_logits[0,i]\n # - np.amax(policy_logits[0,legal_move_indices])) for i in legal_move_indices])\n #policy = policy / np.sum(policy)\n #print(policy.shape, \"man\")\n policy = softmax(policy_logits[0,legal_move_indices])\n #print(policy.shape, \"sm\", policy)\n for index, p in zip(legal_move_indices, policy):\n action = np.zeros(81)\n action[index] = 1\n node.children.append(Node(state=None, action=action, prior=p))\n return value\n\ndef choose_action(root):\n action = np.zeros(81)\n visit_counts = np.array([child.visit_count for child in root.children])\n scaled_counts = np.power(visit_counts, 1.0/MCTS_TEMPERATURE)\n scaled_counts[scaled_counts == 0] = -np.inf\n scaled_counts = softmax(scaled_counts)\n #create softmax distribution\n #choose random move from distribution\n #but for now just pick max move\n index = np.random.choice(scaled_counts.shape[0], 1, p=scaled_counts)[0]\n #print(\"MCTS\", scaled_counts.shape, scaled_counts, len(root.children), index)\n #index = np.argmax(scaled_counts)\n return root.children[index].action\n \ndef generate_mcts_policy(root):\n pol = np.zeros(81)\n for child in root.children:\n pol[np.where(child.action == 1)[0]] = child.prior\n return pol\n"
]
| [
[
"numpy.array",
"scipy.special.softmax",
"numpy.random.choice",
"numpy.zeros",
"numpy.where",
"numpy.power",
"numpy.sqrt"
]
]
|
JeremyXSC/MCN-MT | [
"df62689e5ab3ac3c40a9e793425036594c903cbc"
]
| [
"selftrainingMCN_5model_meannet.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function, absolute_import\nimport argparse\nimport time\nimport os.path as osp\nimport os\nimport sys\nimport numpy as np\nimport torch\nimport csv\nimport codecs\nfrom torch import nn\nfrom torch.nn import init\nfrom torch.backends import cudnn\nfrom torch.utils.data import DataLoader\nfrom reid import datasets\nfrom reid import models\nfrom reid.loss import TripletLoss\nfrom reid.trainers import CoTrainerAsy, CoTrainerAsy4, CoTrainerAsy5\nfrom reid.trainers_meannet import CoTrainerAsyMean_5model \nfrom reid.evaluators import Evaluator, extract_features\nfrom reid.utils.data import transforms as T\nimport torch.nn.functional as F\nfrom reid.utils.data.preprocessor import Preprocessor\nfrom reid.utils.data.sampler import RandomIdentitySampler\nfrom reid.utils.serialization import load_checkpoint, save_checkpoint\n\nfrom sklearn.cluster import DBSCAN\nfrom reid.rerank import re_ranking\n\n\nclass Logger(object):\n def __init__(self, fileN=\"Default.log\"):\n self.terminal = sys.stdout\n self.log = open(fileN, \"a\")\n\n def write(self, message):\n self.terminal.write(message)\n self.log.write(message)\n\n def flush(self):\n pass\n\n\nsys.stdout = Logger(\"./LOG/MCN_5_mean/D2M/print.txt\") \n\ndef data_write_csv(file_name, datas):#file_name为写入CSV文件的路径,datas为要写入数据列表\n file_csv = codecs.open(file_name,'w+','utf-8')#追加\n writer = csv.writer(file_csv, delimiter=' ', quotechar=' ', quoting=csv.QUOTE_MINIMAL)\n for data in datas:\n writer.writerow(data)\n print(\"保存文件成功,处理结束\")\n\ndef calScores(clusters, labels):\n \"\"\"\n compute pair-wise precision pair-wise recall\n \"\"\"\n from scipy.special import comb\n if len(clusters) == 0:\n return 0, 0\n else:\n curCluster = []\n for curClus in clusters.values():\n curCluster.append(labels[curClus])\n TPandFP = sum([comb(len(val), 2) for val in curCluster])\n TP = 0\n for clusterVal in curCluster:\n for setMember in set(clusterVal):\n if sum(clusterVal == setMember) < 2: continue\n TP += comb(sum(clusterVal == setMember), 2)\n FP = TPandFP - TP\n # FN and TN\n TPandFN = sum([comb(labels.tolist().count(val), 2) for val in set(labels)])\n FN = TPandFN - TP\n # cal precision and recall\n precision, recall = TP / (TP + FP), TP / (TP + FN)\n fScore = 2 * precision * recall / (precision + recall)\n return precision, recall, fScore\n\n\ndef get_data(name, data_dir, height, width, batch_size,\n workers):\n root = osp.join(data_dir, name)\n\n dataset = datasets.create(name, root, num_val=0.1)\n\n normalizer = T.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n # use all training and validation images in target dataset\n train_set = dataset.trainval\n num_classes = dataset.num_trainval_ids\n\n transformer = T.Compose([\n T.Resize((height, width)),\n T.ToTensor(),\n normalizer,\n ])\n\n extfeat_loader = DataLoader(\n Preprocessor(train_set, root=dataset.images_dir,\n transform=transformer),\n batch_size=batch_size, num_workers=workers,\n shuffle=False, pin_memory=True)\n\n test_loader = DataLoader(\n Preprocessor(list(set(dataset.query) | set(dataset.gallery)),\n root=dataset.images_dir, transform=transformer),\n batch_size=batch_size // 2, num_workers=workers,\n shuffle=False, pin_memory=True)\n\n return dataset, num_classes, extfeat_loader, test_loader\n\n\ndef saveAll(nameList, rootDir, tarDir):\n import os\n import shutil\n if os.path.exists(tarDir):\n shutil.rmtree(tarDir)\n os.makedirs(tarDir)\n for name in nameList:\n shutil.copyfile(os.path.join(rootDir, name), os.path.join(tarDir, name))\n\n\ndef get_source_data(name, data_dir, height, width, batch_size, workers):\n root = osp.join(data_dir, name)\n\n dataset = datasets.create(name, root, num_val=0.1)\n\n normalizer = T.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n # use all training images on source dataset\n train_set = dataset.train\n num_classes = dataset.num_train_ids\n\n transformer = T.Compose([\n T.Resize((height, width)),\n T.ToTensor(),\n normalizer,\n ])\n\n extfeat_loader = DataLoader(\n Preprocessor(train_set, root=dataset.images_dir,\n transform=transformer),\n batch_size=batch_size, num_workers=workers,\n shuffle=False, pin_memory=True)\n\n return dataset, extfeat_loader\n\n\ndef calDis(qFeature, gFeature): # 246s\n x, y = F.normalize(qFeature), F.normalize(gFeature)\n # x, y = qFeature, gFeature\n m, n = x.shape[0], y.shape[0]\n disMat = torch.pow(x, 2).sum(dim=1, keepdim=True).expand(m, n) + \\\n torch.pow(y, 2).sum(dim=1, keepdim=True).expand(n, m).t()\n disMat.addmm_(1, -2, x, y.t())\n return disMat.clamp_(min=1e-5)\n\n\ndef labelUnknown(knownFeat, allLab, unknownFeat):\n disMat = calDis(knownFeat, unknownFeat)\n labLoc = disMat.argmin(dim=0)\n return allLab[labLoc]\n\n\ndef labelNoise(feature, labels):\n # features and labels with -1\n noiseFeat, pureFeat = feature[labels == -1, :], feature[labels != -1, :]\n labels = labels[labels != -1]\n unLab = labelUnknown(pureFeat, labels, noiseFeat)\n return unLab.numpy()\n\n\ndef main(args):\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n cudnn.benchmark = True\n\n # Create data loaders\n assert args.num_instances > 1, \"num_instances should be greater than 1\"\n assert args.batch_size % args.num_instances == 0, \\\n 'num_instances should divide batch_size'\n if args.height is None or args.width is None:\n args.height, args.width = (144, 56) if args.arch == 'inception' else \\\n (256, 128)\n\n # get source data\n src_dataset, src_extfeat_loader = \\\n get_source_data(args.src_dataset, args.data_dir, args.height,\n args.width, args.batch_size, args.workers)\n # get target data\n tgt_dataset, num_classes, tgt_extfeat_loader, test_loader = \\\n get_data(args.tgt_dataset, args.data_dir, args.height,\n args.width, args.batch_size, args.workers)\n\n # Create model\n # Hacking here to let the classifier be the number of source ids\n if args.src_dataset == 'dukemtmc':\n model = models.create(args.arch, num_classes=632, pretrained=False)\n coModel = models.create(args.arch, num_classes=632, pretrained=False)\n co2Model = models.create(args.arch, num_classes=632, pretrained=False)\n co3Model = models.create(args.arch, num_classes=632, pretrained=False)\n co4Model = models.create(args.arch, num_classes=632, pretrained=False)\n model_ema = models.create(args.arch, num_classes=632, pretrained=False)\n coModel_ema = models.create(args.arch, num_classes=632, pretrained=False)\n co2Model_ema = models.create(args.arch, num_classes=632, pretrained=False)\n co3Model_ema = models.create(args.arch, num_classes=632, pretrained=False)\n co4Model_ema = models.create(args.arch, num_classes=632, pretrained=False)\n elif args.src_dataset == 'market1501':\n model = models.create(args.arch, num_classes=676, pretrained=False)\n coModel = models.create(args.arch, num_classes=676, pretrained=False)\n co2Model = models.create(args.arch, num_classes=676, pretrained=False)\n co3Model = models.create(args.arch, num_classes=676, pretrained=False)\n co4Model = models.create(args.arch, num_classes=676, pretrained=False)\n model_ema = models.create(args.arch, num_classes=676, pretrained=False)\n coModel_ema = models.create(args.arch, num_classes=676, pretrained=False)\n co2Model_ema = models.create(args.arch, num_classes=676, pretrained=False)\n co3Model_ema = models.create(args.arch, num_classes=676, pretrained=False)\n co4Model_ema = models.create(args.arch, num_classes=676, pretrained=False)\n elif args.src_dataset == 'msmt17':\n model = models.create(args.arch, num_classes=1041, pretrained=False)\n coModel = models.create(args.arch, num_classes=1041, pretrained=False)\n co2Model = models.create(args.arch, num_classes=1041, pretrained=False)\n co3Model = models.create(args.arch, num_classes=1041, pretrained=False)\n co4Model = models.create(args.arch, num_classes=1041, pretrained=False)\n model_ema = models.create(args.arch, num_classes=1041, pretrained=False)\n coModel_ema = models.create(args.arch, num_classes=1041, pretrained=False)\n co2Model_ema = models.create(args.arch, num_classes=1041, pretrained=False)\n co3Model_ema = models.create(args.arch, num_classes=1041, pretrained=False)\n co4Model_ema = models.create(args.arch, num_classes=1041, pretrained=False)\n elif args.src_dataset == 'cuhk03':\n model = models.create(args.arch, num_classes=1230, pretrained=False)\n coModel = models.create(args.arch, num_classes=1230, pretrained=False)\n co2Model = models.create(args.arch, num_classes=1230, pretrained=False)\n co3Model = models.create(args.arch, num_classes=1230, pretrained=False)\n co4Model = models.create(args.arch, num_classes=1230, pretrained=False)\n model_ema = models.create(args.arch, num_classes=1230, pretrained=False)\n coModel_ema = models.create(args.arch, num_classes=1230, pretrained=False)\n co2Model_ema = models.create(args.arch, num_classes=1230, pretrained=False)\n co3Model_ema = models.create(args.arch, num_classes=1230, pretrained=False)\n co4Model_ema = models.create(args.arch, num_classes=1230, pretrained=False)\n else:\n raise RuntimeError('Please specify the number of classes (ids) of the network.')\n\n # Load from checkpoint\n if args.resume:\n print('Resuming checkpoints from finetuned model on another dataset...\\n')\n checkpoint = load_checkpoint(args.resume)\n model.load_state_dict(checkpoint['state_dict'], strict=False)\n coModel.load_state_dict(checkpoint['state_dict'], strict=False)\n co2Model.load_state_dict(checkpoint['state_dict'], strict=False)\n co3Model.load_state_dict(checkpoint['state_dict'], strict=False)\n co4Model.load_state_dict(checkpoint['state_dict'], strict=False)\n model_ema.load_state_dict(checkpoint['state_dict'], strict=False)\n coModel_ema.load_state_dict(checkpoint['state_dict'], strict=False)\n co2Model_ema.load_state_dict(checkpoint['state_dict'], strict=False)\n co3Model_ema.load_state_dict(checkpoint['state_dict'], strict=False)\n co4Model_ema.load_state_dict(checkpoint['state_dict'], strict=False)\n else:\n raise RuntimeWarning('Not using a pre-trained model.')\n model = nn.DataParallel(model).cuda()\n coModel = nn.DataParallel(coModel).cuda()\n co2Model = nn.DataParallel(co2Model).cuda()\n co3Model = nn.DataParallel(co3Model).cuda()\n co4Model = nn.DataParallel(co4Model).cuda()\n model_ema = nn.DataParallel(model_ema).cuda()\n coModel_ema = nn.DataParallel(coModel_ema).cuda()\n co2Model_ema = nn.DataParallel(co2Model_ema).cuda()\n co3Model_ema = nn.DataParallel(co3Model_ema).cuda()\n co4Model_ema = nn.DataParallel(co4Model_ema).cuda()\n for param in model_ema.parameters():\n param.detach_() #截断反向传播的梯度流\n for param in coModel_ema.parameters():\n param.detach_()\n for param in co2Model_ema.parameters():\n param.detach_()\n for param in co3Model_ema.parameters():\n param.detach_()\n for param in co4Model_ema.parameters():\n param.detach_()\n\n\n evaluator = Evaluator(model_ema, print_freq=args.print_freq)\n evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery)\n # if args.evaluate: return\n\n # Criterion\n criterion = [\n TripletLoss(args.margin, args.num_instances, isAvg=False, use_semi=False).cuda(),\n TripletLoss(args.margin, args.num_instances, isAvg=False, use_semi=False).cuda(),\n ]\n\n # Optimizer\n optimizer = torch.optim.Adam(\n model.parameters(), lr=args.lr\n )\n coOptimizer = torch.optim.Adam(\n coModel.parameters(), lr=args.lr\n )\n \n co2Optimizer = torch.optim.Adam(\n co2Model.parameters(), lr = args.lr\n )\n \n co3Optimizer = torch.optim.Adam(\n co3Model.parameters(), lr = args.lr\n )\n \n co4Optimizer = torch.optim.Adam(\n co4Model.parameters(), lr = args.lr\n )\n\n optims = [optimizer, coOptimizer, co2Optimizer, co3Optimizer,co4Optimizer]\n\n # training stage transformer on input images\n normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n train_transformer = T.Compose([\n T.Resize((args.height, args.width)),\n T.RandomHorizontalFlip(),\n T.ToTensor(), normalizer,\n T.RandomErasing(probability=0.5, sh=0.2, r1=0.3)\n ])\n \n data_transformer = T.Compose([\n T.Resize((args.height,args.width)),\n T.ToTensor(),\n normalizer,\n ])\n\n # # Start training\n for iter_n in range(args.iteration):\n if args.lambda_value == 0:\n source_features = 0\n else:\n # get source datas' feature\n source_features, _ = extract_features(model_ema, src_extfeat_loader, print_freq=args.print_freq)\n # synchronization feature order with src_dataset.train\n source_features = torch.cat([source_features[f].unsqueeze(0) for f, _, _ in src_dataset.train], 0)\n\n # extract training images' features\n print('Iteration {}: Extracting Target Dataset Features...'.format(iter_n + 1))\n target_features, _ = extract_features(model_ema, tgt_extfeat_loader, print_freq=args.print_freq)\n # synchronization feature order with dataset.train\n target_features = torch.cat([target_features[f].unsqueeze(0) for f, _, _ in tgt_dataset.trainval], 0)\n # calculate distance and rerank result\n print('Calculating feature distances...')\n target_features = target_features.numpy()\n rerank_dist = re_ranking(source_features, target_features, lambda_value=args.lambda_value)\n if iter_n == 0:\n # DBSCAN cluster\n tri_mat = np.triu(rerank_dist, 1) # tri_mat.dim=2\n tri_mat = tri_mat[np.nonzero(tri_mat)] # tri_mat.dim=1\n tri_mat = np.sort(tri_mat, axis=None)\n top_num = np.round(args.rho * tri_mat.size).astype(int)\n eps = tri_mat[:top_num].mean()\n print('eps in cluster: {:.3f}'.format(eps))\n cluster = DBSCAN(eps=eps, min_samples=4, metric='precomputed', n_jobs=8)\n\n # select & cluster images as training set of this epochs\n print('Clustering and labeling...')\n labels = cluster.fit_predict(rerank_dist)\n num_ids = len(set(labels)) - 1\n print('Iteration {} have {} training ids'.format(iter_n + 1, num_ids))\n # generate new dataset\n new_dataset, unknown_dataset = [], []\n # assign label for target ones\n unknownLab = labelNoise(torch.from_numpy(target_features), torch.from_numpy(labels))\n # unknownFeats = target_features[labels==-1,:]\n unCounter, index = 0, 0\n from collections import defaultdict\n realIDs, fakeIDs = defaultdict(list), []\n for (fname, realPID, cam), label in zip(tgt_dataset.trainval, labels):\n if label == -1:\n unknown_dataset.append((fname, int(unknownLab[unCounter]), cam)) # unknown data\n fakeIDs.append(int(unknownLab[unCounter]))\n realIDs[realPID].append(index)\n unCounter += 1\n index += 1\n continue\n # dont need to change codes in trainer.py _parsing_input function and sampler function after add 0\n new_dataset.append((fname, label, cam))\n fakeIDs.append(label)\n realIDs[realPID].append(index)\n index += 1\n print('Iteration {} have {} training images'.format(iter_n + 1, len(new_dataset)))\n print('Iteration {} have {} outliers training images'.format(iter_n+1, len(unknown_dataset)))\n precision, recall, fscore = calScores(realIDs, np.asarray(fakeIDs)) # fakeIDs does not contain -1\n print('precision:{}, recall:{}, fscore: {}'.format(100 * precision, 100 * recall, fscore))\n\n train_loader = DataLoader(\n Preprocessor(new_dataset, root=tgt_dataset.images_dir, transform=train_transformer),\n batch_size=args.batch_size, num_workers=4,\n sampler=RandomIdentitySampler(new_dataset, args.num_instances),\n pin_memory=True, drop_last=True\n )\n # hard samples\n # noiseImgs = [name[1] for name in unknown_dataset]\n # saveAll(noiseImgs, tgt_dataset.images_dir, 'noiseImg')\n # import ipdb; ipdb.set_trace()\n unLoader = DataLoader(\n Preprocessor(unknown_dataset, root=tgt_dataset.images_dir, transform=train_transformer),\n batch_size=args.batch_size, num_workers=4,\n sampler=RandomIdentitySampler(unknown_dataset, args.num_instances),\n pin_memory=True, drop_last=True\n )\n \n #*********************************二次聚类**************************************\n print('***************second cluster*************')\n print('tgt_dataset.trainval type:{}'.format(type(tgt_dataset.trainval)))\n print('new_dataset type:{}'.format(type(new_dataset)))\n #tgt_dataset.trainval type:<class 'list'>\n #new_dataset type:<class 'list'>\n \n #data_write_csv('tgt_dataset.trainval.csv',tgt_dataset.trainval)\n #data_write_csv('new_dataset.csv',new_dataset)\n\n train_all_loader = DataLoader(\n Preprocessor(new_dataset, root=tgt_dataset.images_dir,\n transform=data_transformer),\n batch_size=args.batch_size, num_workers=4,\n shuffle=False, pin_memory=True)\n \n \n target_features2, _ = extract_features(model_ema, train_all_loader, print_freq=args.print_freq)\n # synchronization feature order with dataset.train\n target_features2 = torch.cat([target_features2[f].unsqueeze(0) for f, _, _ in new_dataset], 0)\n # calculate distance and rerank result\n print('Calculating feature distances...')\n target_features2 = target_features2.numpy()\n rerank_dist2 = re_ranking(source_features, target_features2, lambda_value=args.lambda_value)\n if iter_n == 0:\n # DBSCAN cluster\n tri_mat2 = np.triu(rerank_dist2, 1) # tri_mat2.dim=2\n tri_mat2 = tri_mat2[np.nonzero(tri_mat2)] # tri_mat2.dim=1\n tri_mat2 = np.sort(tri_mat2, axis=None)\n top_num2 = np.round(args.rho * tri_mat2.size).astype(int)\n eps2 = tri_mat2[:top_num2].mean()\n print('eps2 in cluster: {:.3f}'.format(eps2))\n cluster2 = DBSCAN(eps=eps2, min_samples=4, metric='precomputed', n_jobs=8)\n\n # select & cluster images as training set of this epochs\n print('Clustering and labeling...')\n labels2 = cluster2.fit_predict(rerank_dist2)\n num_ids2 = len(set(labels2)) - 1\n print('Iteration {} have {} training ids'.format(iter_n + 1, num_ids2))\n # generate new dataset\n new_dataset2, unknown_dataset2 = [], []\n # assign label for target ones\n unknownLab2 = labelNoise(torch.from_numpy(target_features2), torch.from_numpy(labels2))\n # unknownFeats = target_features[labels==-1,:]\n unCounter, index = 0, 0\n from collections import defaultdict\n realIDs2, fakeIDs2 = defaultdict(list), []\n for (fname, realPID, cam), label in zip(new_dataset, labels2):\n if label == -1:\n unknown_dataset2.append((fname, int(unknownLab2[unCounter]), cam)) # unknown data\n fakeIDs2.append(int(unknownLab2[unCounter]))\n realIDs2[realPID].append(index)\n unCounter += 1\n index += 1\n continue\n # dont need to change codes in trainer.py _parsing_input function and sampler function after add 0\n new_dataset2.append((fname, label, cam))\n fakeIDs2.append(label)\n realIDs2[realPID].append(index)\n index += 1\n print('Iteration {} have {} inliers2 training images'.format(iter_n + 1, len(new_dataset2)))\n print('Iteration {} have {} outliers2 training images'.format(iter_n+1, len(unknown_dataset2)))\n precision2, recall2, fscore2 = calScores(realIDs2, np.asarray(fakeIDs2)) # fakeIDs2 does not contain -1\n print('precision2:{}, recall2:{}, fscore2: {}'.format(100 * precision2, 100 * recall2, fscore2))\n\n # train_inliers_loader = DataLoader(\n # Preprocessor(new_dataset2, root=tgt_dataset.images_dir, transform=train_transformer),\n # batch_size=args.batch_size, num_workers=4,\n # sampler=RandomIdentitySampler(new_dataset2, args.num_instances),\n # pin_memory=True, drop_last=True\n # )\n # hard samples\n # noiseImgs = [name[1] for name in unknown_dataset]\n # saveAll(noiseImgs, tgt_dataset.images_dir, 'noiseImg')\n # import ipdb; ipdb.set_trace()\n train_out2_loader = DataLoader(\n Preprocessor(unknown_dataset2, root=tgt_dataset.images_dir, transform=train_transformer),\n batch_size=args.batch_size, num_workers=4,\n sampler=RandomIdentitySampler(unknown_dataset2, args.num_instances),\n pin_memory=True, drop_last=True\n )\n \n #*********************************三次聚类**************************************\n print('***************second cluster*************')\n print('tgt_dataset.trainval type:{}'.format(type(tgt_dataset.trainval)))\n print('new_dataset2 type:{}'.format(type(new_dataset2)))\n #tgt_dataset.trainval type:<class 'list'>\n #new_dataset type:<class 'list'>\n \n #data_write_csv('tgt_dataset.trainval.csv',tgt_dataset.trainval)\n #data_write_csv('new_dataset.csv',new_dataset)\n\n train_in2_loader = DataLoader(\n Preprocessor(new_dataset2, root=tgt_dataset.images_dir,\n transform=data_transformer),\n batch_size=args.batch_size, num_workers=4,\n shuffle=False, pin_memory=True)\n \n \n target_features3, _ = extract_features(model_ema, train_in2_loader, print_freq=args.print_freq)\n # synchronization feature order with dataset.train\n target_features3 = torch.cat([target_features3[f].unsqueeze(0) for f, _, _ in new_dataset2], 0)\n # calculate distance and rerank result\n print('Calculating feature distances...')\n target_features3 = target_features3.numpy()\n rerank_dist3 = re_ranking(source_features, target_features3, lambda_value=args.lambda_value)\n if iter_n == 0:\n # DBSCAN cluster\n tri_mat3 = np.triu(rerank_dist3, 1) # tri_mat2.dim=2\n tri_mat3 = tri_mat3[np.nonzero(tri_mat3)] # tri_mat2.dim=1\n tri_mat3 = np.sort(tri_mat3, axis=None)\n top_num3 = np.round(args.rho * tri_mat3.size).astype(int)\n eps3 = tri_mat3[:top_num3].mean()\n print('eps3 in cluster: {:.3f}'.format(eps3))\n cluster3 = DBSCAN(eps=eps3, min_samples=4, metric='precomputed', n_jobs=8)\n\n # select & cluster images as training set of this epochs\n print('Clustering and labeling...')\n labels3 = cluster3.fit_predict(rerank_dist3)\n num_ids3 = len(set(labels3)) - 1\n print('Iteration {} have {} training ids'.format(iter_n + 1, num_ids3))\n # generate new dataset\n new_dataset3, unknown_dataset3 = [], []\n # assign label for target ones\n unknownLab3 = labelNoise(torch.from_numpy(target_features3), torch.from_numpy(labels3))\n # unknownFeats = target_features[labels==-1,:]\n unCounter, index = 0, 0\n from collections import defaultdict\n realIDs3, fakeIDs3 = defaultdict(list), []\n for (fname, realPID, cam), label in zip(new_dataset, labels3):\n if label == -1:\n unknown_dataset3.append((fname, int(unknownLab3[unCounter]), cam)) # unknown data\n fakeIDs3.append(int(unknownLab3[unCounter]))\n realIDs3[realPID].append(index)\n unCounter += 1\n index += 1\n continue\n # dont need to change codes in trainer.py _parsing_input function and sampler function after add 0\n new_dataset3.append((fname, label, cam))\n fakeIDs3.append(label)\n realIDs3[realPID].append(index)\n index += 1\n print('Iteration {} have {} inliers3 training images'.format(iter_n + 1, len(new_dataset3)))\n print('Iteration {} have {} outliers3 training images'.format(iter_n+1, len(unknown_dataset3)))\n precision3, recall3, fscore3 = calScores(realIDs3, np.asarray(fakeIDs3)) # fakeIDs3 does not contain -1\n print('precision3:{}, recall3:{}, fscore3: {}'.format(100 * precision3, 100 * recall3, fscore3))\n\n # train_in3_loader = DataLoader(\n # Preprocessor(new_dataset3, root=tgt_dataset.images_dir, transform=train_transformer),\n # batch_size=args.batch_size, num_workers=4,\n # sampler=RandomIdentitySampler(new_dataset3, args.num_instances),\n # pin_memory=True, drop_last=True\n # )\n # hard samples\n # noiseImgs = [name[1] for name in unknown_dataset]\n # saveAll(noiseImgs, tgt_dataset.images_dir, 'noiseImg')\n # import ipdb; ipdb.set_trace()\n train_out3_loader = DataLoader(\n Preprocessor(unknown_dataset3, root=tgt_dataset.images_dir, transform=train_transformer),\n batch_size=args.batch_size, num_workers=4,\n sampler=RandomIdentitySampler(unknown_dataset3, args.num_instances),\n pin_memory=True, drop_last=True\n )\n \n \n #*********************************四次聚类**************************************\n print('***************second cluster*************')\n print('tgt_dataset.trainval type:{}'.format(type(tgt_dataset.trainval)))\n print('new_dataset3 type:{}'.format(type(new_dataset3)))\n #tgt_dataset.trainval type:<class 'list'>\n #new_dataset type:<class 'list'>\n \n #data_write_csv('tgt_dataset.trainval.csv',tgt_dataset.trainval)\n #data_write_csv('new_dataset.csv',new_dataset)\n\n train_in3_loader = DataLoader(\n Preprocessor(new_dataset3, root=tgt_dataset.images_dir,\n transform=data_transformer),\n batch_size=args.batch_size, num_workers=4,\n shuffle=False, pin_memory=True)\n \n \n target_features4, _ = extract_features(model_ema, train_in3_loader, print_freq=args.print_freq)\n # synchronization feature order with dataset.train\n target_features4 = torch.cat([target_features4[f].unsqueeze(0) for f, _, _ in new_dataset3], 0)\n # calculate distance and rerank result\n print('Calculating feature distances...')\n target_features4 = target_features4.numpy()\n rerank_dist4 = re_ranking(source_features, target_features4, lambda_value=args.lambda_value)\n if iter_n == 0:\n # DBSCAN4cluster\n tri_mat4 = np.triu(rerank_dist4, 1) # tri_mat4.dim=2\n tri_mat4 = tri_mat4[np.nonzero(tri_mat4)] # tri_mat4.dim=1\n tri_mat4 = np.sort(tri_mat4, axis=None)\n top_num4 = np.round(args.rho * tri_mat4.size).astype(int)\n eps4 = tri_mat4[:top_num4].mean()\n print('eps4 in cluster: {:.3f}'.format(eps4))\n cluster4 = DBSCAN(eps=eps4, min_samples=4, metric='precomputed', n_jobs=8)\n\n # select & cluster images as training set of this epochs\n print('Clustering and labeling...')\n labels4 = cluster4.fit_predict(rerank_dist4)\n num_ids4 = len(set(labels4)) - 1\n print('Iteration {} have {} training ids'.format(iter_n + 1, num_ids4))\n # generate new dataset\n new_dataset4, unknown_dataset4 = [], []\n # assign label for target ones\n unknownLab4 = labelNoise(torch.from_numpy(target_features4), torch.from_numpy(labels4))\n # unknownFeats = target_features[labels==-1,:]\n unCounter, index = 0, 0\n from collections import defaultdict\n realIDs4, fakeIDs4 = defaultdict(list), []\n for (fname, realPID, cam), label in zip(new_dataset, labels4):\n if label == -1:\n unknown_dataset4.append((fname, int(unknownLab4[unCounter]), cam)) # unknown data\n fakeIDs4.append(int(unknownLab4[unCounter]))\n realIDs4[realPID].append(index)\n unCounter += 1\n index += 1\n continue\n # dont need to change codes in trainer.py _parsing_input function and sampler function after add 0\n new_dataset4.append((fname, label, cam))\n fakeIDs4.append(label)\n realIDs4[realPID].append(index)\n index += 1\n print('Iteration {} have {} inliers4 training images'.format(iter_n + 1, len(new_dataset4)))\n print('Iteration {} have {} outliers4 training images'.format(iter_n+1, len(unknown_dataset4)))\n precision4, recall4, fscore4 = calScores(realIDs4, np.asarray(fakeIDs4)) # fakeIDs4 does not contain -1\n print('precision4:{}, recall4:{}, fscore4: {}'.format(100 * precision4, 100 * recall4, fscore4))\n\n train_in4_loader = DataLoader(\n Preprocessor(new_dataset4, root=tgt_dataset.images_dir, transform=train_transformer),\n batch_size=args.batch_size, num_workers=4,\n sampler=RandomIdentitySampler(new_dataset4, args.num_instances),\n pin_memory=True, drop_last=True\n )\n # hard samples\n # noiseImgs = [name[1] for name in unknown_dataset]\n # saveAll(noiseImgs, tgt_dataset.images_dir, 'noiseImg')\n # import ipdb; ipdb.set_trace()\n train_out4_loader = DataLoader(\n Preprocessor(unknown_dataset4, root=tgt_dataset.images_dir, transform=train_transformer),\n batch_size=args.batch_size, num_workers=4,\n sampler=RandomIdentitySampler(unknown_dataset4, args.num_instances),\n pin_memory=True, drop_last=True\n )\n \n \n \n \n \n \n \n # train model with new generated dataset\n trainer = CoTrainerAsyMean_5model(\n model, coModel, co2Model, co3Model, co4Model, model_ema, coModel_ema, co2Model_ema, co3Model_ema, co4Model_ema, train_in4_loader, train_out4_loader, train_out3_loader, train_out2_loader, unLoader, criterion, optims\n )\n \n # trainer = CoTrainerAsy(\n # model, coModel, train_loader, unLoader, criterion, optims\n # )\n\n # Start training\n for epoch in range(args.epochs):\n trainer.train(epoch, remRate=0.2 + (0.8 / args.iteration) * (1 + iter_n))\n\n # test only\n rank_score = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery)\n # print('co-model:\\n')\n # rank_score = evaluatorB.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery)\n\n # Evaluate\n rank_score = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery)\n save_checkpoint({\n 'state_dict': model.module.state_dict(),\n 'epoch': epoch + 1, 'best_top1': rank_score.market1501[0],\n }, True, fpath=osp.join(args.logs_dir, 'asyCo.pth'))\n return rank_score.map, rank_score.market1501[0]\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Triplet loss classification\")\n # data\n parser.add_argument('--src_dataset', type=str, default='dukemtmc',\n choices=datasets.names())\n parser.add_argument('--tgt_dataset', type=str, default='market1501',\n choices=datasets.names())\n parser.add_argument('--batch_size', type=int, default=64)\n parser.add_argument('--workers', type=int, default=4)\n parser.add_argument('--split', type=int, default=0)\n parser.add_argument('--noiseLam', type=float, default=0.5)\n parser.add_argument('--height', type=int,\n help=\"input height, default: 256 for resnet*, \"\n \"144 for inception\")\n parser.add_argument('--width', type=int,\n help=\"input width, default: 128 for resnet*, \"\n \"56 for inception\")\n parser.add_argument('--combine-trainval', action='store_true',\n help=\"train and val sets together for training, \"\n \"val set alone for validation\")\n parser.add_argument('--num_instances', type=int, default=4,\n help=\"each minibatch consist of \"\n \"(batch_size // num_instances) identities, and \"\n \"each identity has num_instances instances, \"\n \"default: 4\")\n # model\n parser.add_argument('--arch', type=str, default='resnet50',\n choices=models.names())\n # loss\n parser.add_argument('--margin', type=float, default=0.5,\n help=\"margin of the triplet loss, default: 0.5\")\n parser.add_argument('--lambda_value', type=float, default=0.1,\n help=\"balancing parameter, default: 0.1\")\n parser.add_argument('--rho', type=float, default=1.6e-3,\n help=\"rho percentage, default: 1.6e-3\")\n # optimizer\n parser.add_argument('--lr', type=float, default=6e-5,\n help=\"learning rate of all parameters\")\n # training configs\n parser.add_argument('--resume', type=str, metavar='PATH',\n default='')\n parser.add_argument('--evaluate', type=int, default=0,\n help=\"evaluation only\")\n parser.add_argument('--seed', type=int, default=1)\n parser.add_argument('--print_freq', type=int, default=1)\n parser.add_argument('--iteration', type=int, default=10)\n parser.add_argument('--epochs', type=int, default=30)\n # metric learning\n parser.add_argument('--dist_metric', type=str, default='euclidean',\n choices=['euclidean', 'kissme'])\n # misc\n parser.add_argument('--data_dir', type=str, metavar='PATH',\n default='')\n parser.add_argument('--logs_dir', type=str, metavar='PATH',\n default='')\n\n args = parser.parse_args()\n mean_ap, rank1 = main(args)\n"
]
| [
[
"torch.nn.functional.normalize",
"numpy.asarray",
"numpy.random.seed",
"numpy.round",
"numpy.triu",
"torch.from_numpy",
"torch.manual_seed",
"numpy.nonzero",
"sklearn.cluster.DBSCAN",
"numpy.sort",
"torch.nn.DataParallel",
"torch.pow"
]
]
|
cogsci2/android-demo-app | [
"16da120c1db5b2be3fdeb08034760607f6fbbba6"
]
| [
"ImageSegmentation/deeplabv3.py"
]
| [
"import torch\n\nmodel = torch.hub.load('pytorch/vision:v0.7.0', 'deeplabv3_resnet50', pretrained=True)\nmodel.eval()\n\nscriptedm = torch.jit.script(model)\ntorch.jit.save(scriptedm, \"deeplabv3_scripted.pt\")\n\n"
]
| [
[
"torch.jit.script",
"torch.jit.save",
"torch.hub.load"
]
]
|
hugobb/sgda | [
"69dcda47bb2c5b76d46ead32eb46ab5fb5e5e6d3"
]
| [
"gamesopt/games/base.py"
]
| [
"from abc import ABC, abstractmethod\nfrom pathlib import Path\nimport torch.autograd as autograd\nimport torch\nfrom typing import List, Optional\nimport copy\nimport torch.distributed as dist\n\n\nclass Game(ABC):\n def __init__(self, players: List[torch.Tensor], num_samples: int, rank: Optional[int] = None, importance_sampling: bool = False) -> None:\n self.num_players = len(players)\n self.players = players\n self.num_samples = num_samples\n self.master_node = None\n self.n_process = 1\n self.rank = rank\n self.dim = sum(p.numel() for p in players)\n\n self.p = torch.ones(self.num_samples) / self.num_samples\n self.importance_sampling = importance_sampling\n\n self.shape = []\n self.split_size = []\n for p in self.players:\n self.shape.append(p.size())\n self.split_size.append(p.numel())\n\n def broadcast(self, src: int) -> None:\n for i in range(self.num_players):\n dist.broadcast(self.players[i], src)\n\n def unflatten(self, index: int, x: torch.Tensor) -> torch.Tensor:\n return x.split(self.split_size)[index].view(self.shape[index])\n\n def flatten(self, tensor_list: List[torch.Tensor]) -> torch.Tensor:\n return torch.cat([ x.view(-1) for x in tensor_list])\n\n def set_master_node(self, rank: int, n_process: int):\n self.master_node = rank\n self.n_process = n_process\n\n @abstractmethod\n def reset(self) -> None:\n pass\n\n def copy(self):\n players = []\n for i in range(self.num_players):\n players.append(self.players[i].clone())\n game = copy.copy(self)\n game.players = players\n return game\n\n def set_players(self, players):\n for i in range(self.num_players):\n self.players[i] = players[i].clone()\n\n def loss(self, index: Optional[int] = None):\n raise NotImplementedError(\"You need to overwrite either `loss` or `operator`, when inheriting `Game`.\")\n\n def operator(self, index: Optional[int] = None, player_index: Optional[int] = None) -> torch.Tensor:\n grad = self._operator(index, player_index)\n if self.importance_sampling:\n grad = grad/float(self.p[index]*len(self.p))\n return grad\n\n def _operator(self, index: Optional[int] = None, player_index: Optional[int] = None) -> torch.Tensor:\n loss = self.loss(index)\n if player_index is None:\n return self.flatten(map(self.grad, loss, range(self.num_players)))\n else:\n return self.grad(loss[player_index], player_index)\n\n def grad(self, loss: torch.Tensor, index: int) -> torch.Tensor:\n return autograd.grad(loss, self.players[index], retain_graph=True)[0]\n\n def full_operator(self) -> torch.Tensor:\n index = self.sample_batch()\n return self._operator(index)\n\n def hamiltonian(self) -> float:\n grad = self.full_operator()\n\n if self.master_node is not None:\n dist.reduce(grad, self.master_node)\n grad /= self.n_process\n\n hamiltonian = (grad**2).sum()\n hamiltonian /= 2\n\n return float(hamiltonian)\n\n def sample_batch(self) -> Optional[torch.Tensor]:\n return None\n\n def sample(self, n: int = 1) -> Optional[torch.Tensor]:\n return None\n\n def update_players(self, players: List[torch.Tensor]) -> None:\n self.players = players\n\n def save(self, filename: Path) -> None:\n pass\n\n @staticmethod\n def load(filename: Path):\n pass\n\n def dist(self, game) -> float:\n dist = 0\n for i in range(self.num_players):\n dist += ((game.players[i] - self.players[i])**2).sum()\n return float(dist)\n \n\n"
]
| [
[
"torch.distributed.reduce",
"torch.distributed.broadcast",
"torch.autograd.grad",
"torch.ones"
]
]
|
alanpeixinho/NiftyNet | [
"9a17022a71985974f9e5ca992c765d55860fdd7d",
"9a17022a71985974f9e5ca992c765d55860fdd7d"
]
| [
"niftynet/contrib/csv_reader/sampler_resize_v2_csv.py",
"tests/gn_test.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nResize input image as output window.\n\"\"\"\nfrom __future__ import absolute_import, print_function, division\n\nimport numpy as np\nimport scipy.ndimage\nimport tensorflow as tf\n\nfrom niftynet.contrib.csv_reader.sampler_csv_rows import ImageWindowDatasetCSV\nfrom niftynet.engine.image_window import LOCATION_FORMAT\n\n\nclass ResizeSamplerCSV(ImageWindowDatasetCSV):\n \"\"\"\n This class generates samples by rescaling\n the whole image to the desired size\n Assuming the reader's output is 5d:\n ``Height x Width x Depth x time x Modality``\n \"\"\"\n\n def __init__(self,\n reader,\n csv_reader=None,\n window_sizes=None,\n batch_size=1,\n spatial_window_size=None,\n windows_per_image=1,\n shuffle=True,\n queue_length=10,\n num_threads=4,\n smaller_final_batch_mode='pad',\n name='resize_sampler_v2'):\n tf.compat.v1.logging.info('reading size of preprocessed images')\n self.csv_reader = csv_reader\n ImageWindowDatasetCSV.__init__(\n self,\n reader=reader,\n csv_reader=csv_reader,\n window_sizes=window_sizes,\n batch_size=batch_size,\n windows_per_image=windows_per_image,\n queue_length=queue_length,\n num_threads=num_threads,\n shuffle=shuffle,\n epoch=-1 if shuffle else 1,\n smaller_final_batch_mode=smaller_final_batch_mode,\n name=name)\n if spatial_window_size:\n # override all spatial window defined in input\n # modalities sections\n # this is useful when do inference with a spatial window\n # which is different from the training specifications\n self.window.set_spatial_shape(spatial_window_size)\n # tf.logging.info(\"initialised resize sampler %s \", self.window.shapes)\n # tf.logging.info('CSV reader is {}'.format(self.csv_reader))\n\n def layer_op(self, idx=None):\n \"\"\"\n This function generates sampling windows to the input buffer\n image data are from ``self.reader()``.\n\n It first completes window shapes based on image data,\n then resize each image as window and output\n a dictionary (required by input buffer)\n\n :return: output data dictionary ``{'image_modality': data_array}``\n \"\"\"\n image_id, data, interp_orders = self.reader(idx=idx)\n image_shapes = \\\n dict((name, data[name].shape) for name in self.window.names)\n # window shapes can be dynamic, here they\n # are converted to static ones\n # as now we know the image shapes\n static_window_shapes = self.window.match_image_shapes(image_shapes)\n # for resize sampler the coordinates are not used\n # simply use the spatial dims of the input image\n output_dict = {}\n for name in list(data):\n # prepare output dictionary keys\n coordinates_key = LOCATION_FORMAT.format(name)\n image_data_key = name\n\n output_dict[coordinates_key] = self.dummy_coordinates(\n image_id, static_window_shapes[name], self.window.n_samples)\n image_array = []\n for _ in range(self.window.n_samples):\n # prepare image data\n image_shape = image_shapes[name]\n window_shape = static_window_shapes[name]\n\n if image_shape == window_shape or interp_orders[name][0] < 0:\n # already in the same shape\n image_window = data[name]\n else:\n zoom_ratio = [float(p) / float(d) for p, d in\n zip(window_shape, image_shape)]\n image_window = zoom_3d(image=data[name],\n ratio=zoom_ratio, interp_order=\n interp_orders[name][0])\n image_array.append(image_window[np.newaxis, ...])\n if len(image_array) > 1:\n output_dict[image_data_key] = \\\n np.concatenate(image_array, axis=0)\n else:\n output_dict[image_data_key] = image_array[0]\n # the output image shape should be\n # [enqueue_batch_size, x, y, z, time, modality]\n # here enqueue_batch_size = 1 as we only have one sample\n # per image\n if self.csv_reader is not None:\n _, label_dict, _ = self.csv_reader(idx=image_id)\n output_dict.update(label_dict)\n for name in self.csv_reader.names:\n output_dict[name + '_location'] = output_dict['image_location']\n return output_dict\n\n\ndef zoom_3d(image, ratio, interp_order):\n \"\"\"\n Taking 5D image as input, and zoom each 3D slice independently\n \"\"\"\n assert image.ndim == 5, \"input images should be 5D array\"\n output = []\n for time_pt in range(image.shape[3]):\n output_mod = []\n for mod in range(image.shape[4]):\n zoomed = scipy.ndimage.zoom(\n image[..., time_pt, mod], ratio[:3], order=interp_order)\n output_mod.append(zoomed[..., np.newaxis, np.newaxis])\n output.append(np.concatenate(output_mod, axis=-1))\n return np.concatenate(output, axis=-2)\n",
"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, print_function\n\nimport tensorflow as tf\nfrom tensorflow.keras import regularizers\n\nfrom niftynet.layer.gn import GNLayer\nfrom tests.niftynet_testcase import NiftyNetTestCase\n\nclass GNTest(NiftyNetTestCase):\n def get_3d_input(self):\n input_shape = (2, 16, 16, 16, 8)\n x = tf.ones(input_shape)\n return x\n\n def get_2d_input(self):\n input_shape = (2, 16, 16, 8)\n x = tf.ones(input_shape)\n return x\n\n def test_3d_gn_shape(self):\n x = self.get_3d_input()\n gn_layer = GNLayer(4)\n print(gn_layer)\n out_gn = gn_layer(x)\n print(gn_layer)\n\n with self.cached_session() as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n\n out = sess.run(out_gn)\n x_shape = tuple(x.shape.as_list())\n self.assertAllClose(x_shape, out.shape)\n # self.assertAllClose(np.zeros(x_shape), out)\n\n def test_3d_gn_reg_shape(self):\n x = self.get_3d_input()\n gn_layer = GNLayer(4, regularizer=regularizers.L2(0.5))\n out_gn = gn_layer(x)\n test_gn = gn_layer(x)\n print(gn_layer)\n\n with self.cached_session() as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n\n out = sess.run(out_gn)\n x_shape = tuple(x.shape.as_list())\n self.assertAllClose(x_shape, out.shape)\n # self.assertAllClose(np.zeros(x_shape), out)\n\n out = sess.run(test_gn)\n self.assertAllClose(x_shape, out.shape)\n # self.assertAllClose(np.zeros(x_shape), out)\n\n def test_2d_gn_shape(self):\n x = self.get_2d_input()\n gn_layer = GNLayer(4)\n out_gn = gn_layer(x)\n print(gn_layer)\n\n with self.cached_session() as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n\n out = sess.run(out_gn)\n x_shape = tuple(x.shape.as_list())\n self.assertAllClose(x_shape, out.shape)\n # self.assertAllClose(np.zeros(x_shape), out)\n\n def test_2d_gn_reg_shape(self):\n x = self.get_2d_input()\n gn_layer = GNLayer(4, regularizer=regularizers.L2(0.5))\n out_gn = gn_layer(x)\n test_gn = gn_layer(x)\n print(gn_layer)\n reg_loss = tf.add_n(gn_layer.regularizer_loss())\n\n with self.cached_session() as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n\n out = sess.run(out_gn)\n x_shape = tuple(x.shape.as_list())\n self.assertAllClose(x_shape, out.shape)\n # self.assertAllClose(np.zeros(x_shape), out)\n\n out = sess.run(test_gn)\n self.assertAllClose(x_shape, out.shape)\n # self.assertAllClose(np.zeros(x_shape), out)\n\n out = sess.run(reg_loss)\n self.assertAlmostEqual(out, 2.0)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n"
]
| [
[
"numpy.concatenate",
"tensorflow.compat.v1.logging.info"
],
[
"tensorflow.keras.regularizers.L2",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.ones",
"tensorflow.test.main"
]
]
|
python-bookworm/mmdetection-new | [
"add3ab512b98f9d0996ad26b5b9e5737bcde9fde"
]
| [
"mmdet/datasets/coco.py"
]
| [
"import numpy as np\nfrom pycocotools.coco import COCO\n\nfrom .custom import CustomDataset\nfrom .registry import DATASETS\n\n\[email protected]_module\nclass CocoDataset(CustomDataset):\n\n # CLASSES = ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',\n # 'train', 'truck', 'boat', 'traffic_light', 'fire_hydrant',\n # 'stop_sign', 'parking_meter', 'bench', 'bird', 'cat', 'dog',\n # 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe',\n # 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',\n # 'skis', 'snowboard', 'sports_ball', 'kite', 'baseball_bat',\n # 'baseball_glove', 'skateboard', 'surfboard', 'tennis_racket',\n # 'bottle', 'wine_glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',\n # 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot',\n # 'hot_dog', 'pizza', 'donut', 'cake', 'chair', 'couch',\n # 'potted_plant', 'bed', 'dining_table', 'toilet', 'tv', 'laptop',\n # 'mouse', 'remote', 'keyboard', 'cell_phone', 'microwave',\n # 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock',\n # 'vase', 'scissors', 'teddy_bear', 'hair_drier', 'toothbrush')\n CLASSES = (\"1\",\"2\",\"3\",\"4\",\"5\")\n\n def load_annotations(self, ann_file):\n self.coco = COCO(ann_file)\n self.cat_ids = self.coco.getCatIds()\n self.cat2label = {\n cat_id: i + 1\n for i, cat_id in enumerate(self.cat_ids)\n }\n self.img_ids = self.coco.getImgIds()\n img_infos = []\n for i in self.img_ids:\n info = self.coco.loadImgs([i])[0]\n info['filename'] = info['file_name']\n img_infos.append(info)\n return img_infos\n\n def get_ann_info(self, idx):\n img_id = self.img_infos[idx]['id']\n ann_ids = self.coco.getAnnIds(imgIds=[img_id])\n ann_info = self.coco.loadAnns(ann_ids)\n return self._parse_ann_info(self.img_infos[idx], ann_info)\n\n def _filter_imgs(self, min_size=32):\n \"\"\"Filter images too small or without ground truths.\"\"\"\n valid_inds = []\n ids_with_ann = set(_['image_id'] for _ in self.coco.anns.values())\n for i, img_info in enumerate(self.img_infos):\n if self.img_ids[i] not in ids_with_ann:\n continue\n if min(img_info['width'], img_info['height']) >= min_size:\n valid_inds.append(i)\n return valid_inds\n\n def _parse_ann_info(self, img_info, ann_info):\n \"\"\"Parse bbox and mask annotation.\n\n Args:\n ann_info (list[dict]): Annotation info of an image.\n with_mask (bool): Whether to parse mask annotations.\n\n Returns:\n dict: A dict containing the following keys: bboxes, bboxes_ignore,\n labels, masks, seg_map. \"masks\" are raw annotations and not\n decoded into binary masks.\n \"\"\"\n gt_bboxes = []\n gt_labels = []\n gt_bboxes_ignore = []\n gt_masks_ann = []\n\n for i, ann in enumerate(ann_info):\n if ann.get('ignore', False):\n continue\n x1, y1, w, h = ann['bbox']\n if ann['area'] <= 0 or w < 1 or h < 1:\n continue\n bbox = [x1, y1, x1 + w - 1, y1 + h - 1]\n if ann.get('iscrowd', False):\n gt_bboxes_ignore.append(bbox)\n else:\n gt_bboxes.append(bbox)\n gt_labels.append(self.cat2label[ann['category_id']])\n gt_masks_ann.append(ann['segmentation'])\n\n if gt_bboxes:\n gt_bboxes = np.array(gt_bboxes, dtype=np.float32)\n gt_labels = np.array(gt_labels, dtype=np.int64)\n else:\n gt_bboxes = np.zeros((0, 4), dtype=np.float32)\n gt_labels = np.array([], dtype=np.int64)\n\n if gt_bboxes_ignore:\n gt_bboxes_ignore = np.array(gt_bboxes_ignore, dtype=np.float32)\n else:\n gt_bboxes_ignore = np.zeros((0, 4), dtype=np.float32)\n\n seg_map = img_info['filename'].replace('jpg', 'png')\n\n ann = dict(\n bboxes=gt_bboxes,\n labels=gt_labels,\n bboxes_ignore=gt_bboxes_ignore,\n masks=gt_masks_ann,\n seg_map=seg_map)\n\n return ann\n"
]
| [
[
"numpy.array",
"numpy.zeros"
]
]
|
sliderSun/bert | [
"c9e16d652f85398fbb6ca6aea72f11f82166c672"
]
| [
"bert_tsim/similarity.py"
]
| [
"import os\nimport random\nfrom queue import Queue\nfrom threading import Thread\n\nimport pandas as pd\nimport tensorflow as tf\nimport collections\nimport args\nimport tokenization\nimport modeling\nimport optimization\n\n\n# os.environ['CUDA_VISIBLE_DEVICES'] = '1'\n\n\nclass InputExample(object):\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\n\n def __init__(self, guid, text_a, text_b=None, label=None):\n \"\"\"Constructs a InputExample.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self, input_ids, input_mask, segment_ids, label_id):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.label_id = label_id\n\n\nclass DataProcessor(object):\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\n raise NotImplementedError()\n\n def get_dev_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\n raise NotImplementedError()\n\n def get_test_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for prediction.\"\"\"\n raise NotImplementedError()\n\n def get_labels(self):\n \"\"\"Gets the list of labels for this data set.\"\"\"\n raise NotImplementedError()\n\n\nclass SimProcessor(DataProcessor):\n def get_train_examples(self, data_dir):\n file_path = os.path.join(data_dir, 'train.csv')\n train_df = pd.read_csv(file_path, encoding='utf-8')\n train_data = []\n for index, train in enumerate(train_df.values):\n guid = 'train-%d' % index\n text_a = tokenization.convert_to_unicode(str(train[0]))\n text_b = tokenization.convert_to_unicode(str(train[1]))\n label = str(train[2])\n train_data.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n random.shuffle(train_data)\n return train_data\n\n def get_dev_examples(self, data_dir):\n file_path = os.path.join(data_dir, 'dev.csv')\n dev_df = pd.read_csv(file_path, encoding='utf-8')\n dev_data = []\n for index, dev in enumerate(dev_df.values):\n guid = 'test-%d' % index\n text_a = tokenization.convert_to_unicode(str(dev[0]))\n text_b = tokenization.convert_to_unicode(str(dev[1]))\n label = str(dev[2])\n dev_data.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n random.shuffle(dev_data)\n return dev_data\n\n def get_test_examples(self, data_dir):\n file_path = os.path.join(data_dir, 'test.csv')\n test_df = pd.read_csv(file_path, encoding='utf-8')\n test_data = []\n for index, test in enumerate(test_df.values):\n guid = 'test-%d' % index\n text_a = tokenization.convert_to_unicode(str(test[0]))\n text_b = tokenization.convert_to_unicode(str(test[1]))\n label = str(test[2])\n test_data.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n random.shuffle(test_data)\n return test_data\n\n def get_sentence_examples(self, questions):\n for index, data in enumerate(questions):\n guid = 'test-%d' % index\n text_a = tokenization.convert_to_unicode(str(data[0]))\n text_b = tokenization.convert_to_unicode(str(data[1]))\n label = str(0)\n yield InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)\n\n def get_labels(self):\n return ['0', '1']\n\n\nclass BertSim:\n\n def __init__(self, batch_size=args.batch_size):\n self.mode = None\n self.max_seq_length = args.max_seq_len\n self.tokenizer = tokenization.FullTokenizer(vocab_file=args.vocab_file, do_lower_case=True)\n self.batch_size = batch_size\n self.estimator = None\n self.processor = SimProcessor()\n tf.logging.set_verbosity(tf.logging.INFO)\n\n def set_mode(self, mode):\n self.mode = mode\n self.estimator = self.get_estimator()\n if mode == tf.estimator.ModeKeys.PREDICT:\n self.input_queue = Queue(maxsize=1)\n self.output_queue = Queue(maxsize=1)\n self.predict_thread = Thread(target=self.predict_from_queue, daemon=True)\n self.predict_thread.start()\n\n @staticmethod\n def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,\n labels, num_labels, 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 # In the demo, we are doing a simple classification task on the entire\n # segment.\n #\n # If you want to use the token-level output, use model.get_sequence_output()\n # instead.\n output_layer = model.get_pooled_output()\n\n hidden_size = output_layer.shape[-1].value\n\n output_weights = tf.get_variable(\n \"output_weights\", [num_labels, hidden_size],\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n\n output_bias = tf.get_variable(\n \"output_bias\", [num_labels], initializer=tf.zeros_initializer())\n\n with tf.variable_scope(\"loss\"):\n if is_training:\n # I.e., 0.1 dropout\n output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)\n\n logits = tf.matmul(output_layer, output_weights, transpose_b=True)\n logits = tf.nn.bias_add(logits, output_bias)\n probabilities = tf.nn.softmax(logits, axis=-1)\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n\n one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)\n\n per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)\n loss = tf.reduce_mean(per_example_loss)\n\n return (loss, per_example_loss, logits, probabilities)\n\n def model_fn_builder(self, bert_config, num_labels, init_checkpoint, learning_rate,\n num_train_steps, num_warmup_steps,\n use_one_hot_embeddings):\n \"\"\"Returns `model_fn` closurimport_tfe for TPUEstimator.\"\"\"\n\n def model_fn(features, labels, mode, params): # pylint: disable=unused-argument\n from tensorflow.python.estimator.model_fn import EstimatorSpec\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 input_ids = features[\"input_ids\"]\n input_mask = features[\"input_mask\"]\n segment_ids = features[\"segment_ids\"]\n label_ids = features[\"label_ids\"]\n\n is_training = (mode == tf.estimator.ModeKeys.TRAIN)\n\n (total_loss, per_example_loss, logits, probabilities) = BertSim.create_model(\n bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,\n num_labels, use_one_hot_embeddings)\n\n tvars = tf.trainable_variables()\n initialized_variable_names = {}\n\n if init_checkpoint:\n (assignment_map, initialized_variable_names) \\\n = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)\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 if mode == tf.estimator.ModeKeys.TRAIN:\n\n train_op = optimization.create_optimizer(\n total_loss, learning_rate, num_train_steps, num_warmup_steps, False)\n\n output_spec = EstimatorSpec(\n mode=mode,\n loss=total_loss,\n train_op=train_op)\n elif mode == tf.estimator.ModeKeys.EVAL:\n\n def metric_fn(per_example_loss, label_ids, logits):\n predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)\n accuracy = tf.metrics.accuracy(label_ids, predictions)\n auc = tf.metrics.auc(label_ids, predictions)\n loss = tf.metrics.mean(per_example_loss)\n return {\n \"eval_accuracy\": accuracy,\n \"eval_auc\": auc,\n \"eval_loss\": loss,\n }\n\n eval_metrics = metric_fn(per_example_loss, label_ids, logits)\n output_spec = EstimatorSpec(\n mode=mode,\n loss=total_loss,\n eval_metric_ops=eval_metrics)\n else:\n output_spec = EstimatorSpec(mode=mode, predictions=probabilities)\n\n return output_spec\n\n return model_fn\n\n def get_estimator(self):\n\n from tensorflow.python.estimator.estimator import Estimator\n from tensorflow.python.estimator.run_config import RunConfig\n\n bert_config = modeling.BertConfig.from_json_file(args.config_name)\n label_list = self.processor.get_labels()\n train_examples = self.processor.get_train_examples(args.data_dir)\n num_train_steps = int(\n len(train_examples) / self.batch_size * args.num_train_epochs)\n num_warmup_steps = int(num_train_steps * 0.1)\n\n if self.mode == tf.estimator.ModeKeys.TRAIN:\n init_checkpoint = args.ckpt_name\n else:\n init_checkpoint = args.output_dir\n\n model_fn = self.model_fn_builder(\n bert_config=bert_config,\n num_labels=len(label_list),\n init_checkpoint=init_checkpoint,\n learning_rate=args.learning_rate,\n num_train_steps=num_train_steps,\n num_warmup_steps=num_warmup_steps,\n use_one_hot_embeddings=False)\n\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n config.gpu_options.per_process_gpu_memory_fraction = args.gpu_memory_fraction\n config.log_device_placement = False\n\n return Estimator(model_fn=model_fn, config=RunConfig(session_config=config), model_dir=args.output_dir,\n params={'batch_size': self.batch_size})\n\n def predict_from_queue(self):\n for i in self.estimator.predict(input_fn=self.queue_predict_input_fn, yield_single_examples=False):\n self.output_queue.put(i)\n\n def queue_predict_input_fn(self):\n return (tf.data.Dataset.from_generator(\n self.generate_from_queue,\n output_types={\n 'input_ids': tf.int32,\n 'input_mask': tf.int32,\n 'segment_ids': tf.int32,\n 'label_ids': tf.int32},\n output_shapes={\n 'input_ids': (None, self.max_seq_length),\n 'input_mask': (None, self.max_seq_length),\n 'segment_ids': (None, self.max_seq_length),\n 'label_ids': (1,)}).prefetch(10))\n\n def convert_examples_to_features(self, examples, label_list, max_seq_length, tokenizer):\n \"\"\"Convert a set of `InputExample`s to a list of `InputFeatures`.\"\"\"\n\n for (ex_index, example) in enumerate(examples):\n label_map = {}\n for (i, label) in enumerate(label_list):\n label_map[label] = i\n\n tokens_a = tokenizer.tokenize(example.text_a)\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n\n if tokens_b:\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n self._truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[0:(max_seq_length - 2)]\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambiguously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = []\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in tokens_a:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n if tokens_b:\n for token in tokens_b:\n tokens.append(token)\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 label_id = label_map[example.label]\n if ex_index < 5:\n tf.logging.info(\"*** Example ***\")\n tf.logging.info(\"guid: %s\" % (example.guid))\n tf.logging.info(\"tokens: %s\" % \" \".join(\n [tokenization.printable_text(x) for x in tokens]))\n tf.logging.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n tf.logging.info(\"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n tf.logging.info(\"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n tf.logging.info(\"label: %s (id = %d)\" % (example.label, label_id))\n\n feature = InputFeatures(\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id)\n\n yield feature\n\n def generate_from_queue(self):\n while True:\n predict_examples = self.processor.get_sentence_examples(self.input_queue.get())\n features = list(self.convert_examples_to_features(predict_examples, self.processor.get_labels(),\n args.max_seq_len, self.tokenizer))\n yield {\n 'input_ids': [f.input_ids for f in features],\n 'input_mask': [f.input_mask for f in features],\n 'segment_ids': [f.segment_ids for f in features],\n 'label_ids': [f.label_id for f in features]\n }\n\n def _truncate_seq_pair(self, tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n def convert_single_example(self, ex_index, example, label_list, max_seq_length, tokenizer):\n \"\"\"Converts a single `InputExample` into a single `InputFeatures`.\"\"\"\n label_map = {}\n for (i, label) in enumerate(label_list):\n label_map[label] = i\n\n tokens_a = tokenizer.tokenize(example.text_a)\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n\n if tokens_b:\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n self._truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[0:(max_seq_length - 2)]\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambiguously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = []\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in tokens_a:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n if tokens_b:\n for token in tokens_b:\n tokens.append(token)\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 label_id = label_map[example.label]\n if ex_index < 5:\n tf.logging.info(\"*** Example ***\")\n tf.logging.info(\"guid: %s\" % (example.guid))\n tf.logging.info(\"tokens: %s\" % \" \".join(\n [tokenization.printable_text(x) for x in tokens]))\n tf.logging.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n tf.logging.info(\"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n tf.logging.info(\"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n tf.logging.info(\"label: %s (id = %d)\" % (example.label, label_id))\n\n feature = InputFeatures(\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id)\n return feature\n\n def file_based_convert_examples_to_features(self, examples, label_list, max_seq_length, tokenizer, output_file):\n \"\"\"Convert a set of `InputExample`s to a TFRecord file.\"\"\"\n\n writer = tf.python_io.TFRecordWriter(output_file)\n\n for (ex_index, example) in enumerate(examples):\n if ex_index % 10000 == 0:\n tf.logging.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n\n feature = self.convert_single_example(ex_index, example, label_list,\n max_seq_length, tokenizer)\n\n def create_int_feature(values):\n f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))\n return f\n\n features = collections.OrderedDict()\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 features[\"label_ids\"] = create_int_feature([feature.label_id])\n\n tf_example = tf.train.Example(features=tf.train.Features(feature=features))\n writer.write(tf_example.SerializeToString())\n\n def file_based_input_fn_builder(self, 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 \"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 \"label_ids\": tf.FixedLenFeature([], tf.int64),\n }\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 def train(self):\n if self.mode is None:\n raise ValueError(\"Please set the 'mode' parameter\")\n\n bert_config = modeling.BertConfig.from_json_file(args.config_name)\n\n if args.max_seq_len > 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 (args.max_seq_len, bert_config.max_position_embeddings))\n\n tf.gfile.MakeDirs(args.output_dir)\n\n label_list = self.processor.get_labels()\n\n train_examples = self.processor.get_train_examples(args.data_dir)\n num_train_steps = int(len(train_examples) / args.batch_size * args.num_train_epochs)\n\n estimator = self.get_estimator()\n\n train_file = os.path.join(args.output_dir, \"train.tf_record\")\n self.file_based_convert_examples_to_features(train_examples, label_list, args.max_seq_len, self.tokenizer,\n train_file)\n tf.logging.info(\"***** Running training *****\")\n tf.logging.info(\" Num examples = %d\", len(train_examples))\n tf.logging.info(\" Batch size = %d\", args.batch_size)\n tf.logging.info(\" Num steps = %d\", num_train_steps)\n train_input_fn = self.file_based_input_fn_builder(input_file=train_file, seq_length=args.max_seq_len,\n is_training=True,\n drop_remainder=True)\n\n # early_stopping = tf.contrib.estimator.stop_if_no_decrease_hook(\n # estimator,\n # metric_name='loss',\n # max_steps_without_decrease=10,\n # min_steps=num_train_steps)\n\n # estimator.train(input_fn=train_input_fn, hooks=[early_stopping])\n estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)\n\n def eval(self):\n if self.mode is None:\n raise ValueError(\"Please set the 'mode' parameter\")\n eval_examples = self.processor.get_dev_examples(args.data_dir)\n eval_file = os.path.join(args.output_dir, \"eval.tf_record\")\n label_list = self.processor.get_labels()\n self.file_based_convert_examples_to_features(\n eval_examples, label_list, args.max_seq_len, self.tokenizer, eval_file)\n\n tf.logging.info(\"***** Running evaluation *****\")\n tf.logging.info(\" Num examples = %d\", len(eval_examples))\n tf.logging.info(\" Batch size = %d\", self.batch_size)\n\n eval_input_fn = self.file_based_input_fn_builder(\n input_file=eval_file,\n seq_length=args.max_seq_len,\n is_training=False,\n drop_remainder=False)\n\n estimator = self.get_estimator()\n result = estimator.evaluate(input_fn=eval_input_fn, steps=None)\n\n output_eval_file = os.path.join(args.output_dir, \"eval_results.txt\")\n with tf.gfile.GFile(output_eval_file, \"w\") as writer:\n tf.logging.info(\"***** Eval results *****\")\n for key in sorted(result.keys()):\n tf.logging.info(\" %s = %s\", key, str(result[key]))\n writer.write(\"%s = %s\\n\" % (key, str(result[key])))\n\n def predict(self, sentence1, sentence2):\n if self.mode is None:\n raise ValueError(\"Please set the 'mode' parameter\")\n self.input_queue.put([(sentence1, sentence2)])\n prediction = self.output_queue.get()\n return prediction\n\n\nif __name__ == '__main__':\n sim = BertSim()\n # sim.set_mode(tf.estimator.ModeKeys.TRAIN)\n # sim.train()\n # sim.set_mode(tf.estimator.ModeKeys.EVAL)\n # sim.eval()\n sim.set_mode(tf.estimator.ModeKeys.PREDICT)\n while True:\n sentence1 = input('sentence1: ')\n sentence2 = input('sentence2: ')\n import time\n s = time.time()\n predict = sim.predict(sentence1, sentence2)\n print(time.time() - s)\n print(f'similarity:{predict[0][1]}')\n"
]
| [
[
"tensorflow.data.TFRecordDataset",
"tensorflow.train.Features",
"tensorflow.metrics.auc",
"tensorflow.matmul",
"tensorflow.metrics.mean",
"tensorflow.nn.softmax",
"tensorflow.one_hot",
"pandas.read_csv",
"tensorflow.parse_single_example",
"tensorflow.trainable_variables",
"tensorflow.FixedLenFeature",
"tensorflow.argmax",
"tensorflow.logging.info",
"tensorflow.ConfigProto",
"tensorflow.gfile.MakeDirs",
"tensorflow.variable_scope",
"tensorflow.nn.bias_add",
"tensorflow.nn.log_softmax",
"tensorflow.nn.dropout",
"tensorflow.logging.set_verbosity",
"tensorflow.python_io.TFRecordWriter",
"tensorflow.gfile.GFile",
"tensorflow.metrics.accuracy",
"tensorflow.reduce_sum",
"tensorflow.train.init_from_checkpoint",
"tensorflow.to_int32",
"tensorflow.zeros_initializer",
"tensorflow.data.Dataset.from_generator",
"tensorflow.python.estimator.model_fn.EstimatorSpec",
"tensorflow.python.estimator.run_config.RunConfig",
"tensorflow.truncated_normal_initializer",
"tensorflow.reduce_mean"
]
]
|
bhadreshpsavani/TAPER-EHR | [
"ab938749756fcaaef52a7002a074421f483e3562"
]
| [
"model/bert_things/pytorch_pretrained_bert/modeling.py"
]
| [
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"PyTorch BERT model.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport copy\nimport json\nimport logging\nimport math\nimport os\nimport shutil\nimport tarfile\nimport tempfile\nimport sys\nfrom io import open\n\nimport torch\nfrom torch import nn\nfrom torch.nn import CrossEntropyLoss\n\nfrom .file_utils import cached_path\n\nlogger = logging.getLogger(__name__)\n\nPRETRAINED_MODEL_ARCHIVE_MAP = {\n 'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased.tar.gz\",\n 'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased.tar.gz\",\n 'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased.tar.gz\",\n 'bert-large-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased.tar.gz\",\n 'bert-base-multilingual-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased.tar.gz\",\n 'bert-base-multilingual-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased.tar.gz\",\n 'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese.tar.gz\",\n}\nCONFIG_NAME = 'bert_config.json'\nWEIGHTS_NAME = 'pytorch_model.bin'\nTF_WEIGHTS_NAME = 'model.ckpt'\n\ndef load_tf_weights_in_bert(model, tf_checkpoint_path):\n \"\"\" Load tf checkpoints in a pytorch model\n \"\"\"\n try:\n import re\n import numpy as np\n import tensorflow as tf\n except ImportError:\n print(\"Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see \"\n \"https://www.tensorflow.org/install/ for installation instructions.\")\n raise\n tf_path = os.path.abspath(tf_checkpoint_path)\n print(\"Converting TensorFlow checkpoint from {}\".format(tf_path))\n # Load weights from TF model\n init_vars = tf.train.list_variables(tf_path)\n names = []\n arrays = []\n for name, shape in init_vars:\n print(\"Loading TF weight {} with shape {}\".format(name, shape))\n array = tf.train.load_variable(tf_path, name)\n names.append(name)\n arrays.append(array)\n\n for name, array in zip(names, arrays):\n name = name.split('/')\n # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v\n # which are not required for using pretrained model\n if any(n in [\"adam_v\", \"adam_m\", \"global_step\"] for n in name):\n print(\"Skipping {}\".format(\"/\".join(name)))\n continue\n pointer = model\n for m_name in name:\n if re.fullmatch(r'[A-Za-z]+_\\d+', m_name):\n l = re.split(r'_(\\d+)', m_name)\n else:\n l = [m_name]\n if l[0] == 'kernel' or l[0] == 'gamma':\n pointer = getattr(pointer, 'weight')\n elif l[0] == 'output_bias' or l[0] == 'beta':\n pointer = getattr(pointer, 'bias')\n elif l[0] == 'output_weights':\n pointer = getattr(pointer, 'weight')\n elif l[0] == 'squad':\n pointer = getattr(pointer, 'classifier')\n else:\n try:\n pointer = getattr(pointer, l[0])\n except AttributeError:\n print(\"Skipping {}\".format(\"/\".join(name)))\n continue\n if len(l) >= 2:\n num = int(l[1])\n pointer = pointer[num]\n if m_name[-11:] == '_embeddings':\n pointer = getattr(pointer, 'weight')\n elif m_name == 'kernel':\n array = np.transpose(array)\n try:\n assert pointer.shape == array.shape\n except AssertionError as e:\n e.args += (pointer.shape, array.shape)\n raise\n print(\"Initialize PyTorch weight {}\".format(name))\n pointer.data = torch.from_numpy(array)\n return model\n\n\ndef gelu(x):\n \"\"\"Implementation of the gelu activation function.\n For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):\n 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))\n Also see https://arxiv.org/abs/1606.08415\n \"\"\"\n return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))\n\n\ndef swish(x):\n return x * torch.sigmoid(x)\n\n\nACT2FN = {\"gelu\": gelu, \"relu\": torch.nn.functional.relu, \"swish\": swish}\n\n\nclass BertConfig(object):\n \"\"\"Configuration class to store the configuration of a `BertModel`.\n \"\"\"\n def __init__(self,\n vocab_size_or_config_json_file,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02):\n \"\"\"Constructs BertConfig.\n\n Args:\n vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `BertModel`.\n hidden_size: Size of the encoder layers and the pooler layer.\n num_hidden_layers: Number of hidden layers in the Transformer encoder.\n num_attention_heads: Number of attention heads for each attention layer in\n the Transformer encoder.\n intermediate_size: The size of the \"intermediate\" (i.e., feed-forward)\n layer in the Transformer encoder.\n hidden_act: The non-linear activation function (function or string) in the\n encoder and pooler. If string, \"gelu\", \"relu\" and \"swish\" are supported.\n hidden_dropout_prob: The dropout probabilitiy for all fully connected\n layers in the embeddings, encoder, and pooler.\n attention_probs_dropout_prob: The dropout ratio for the attention\n probabilities.\n max_position_embeddings: The maximum sequence length that this model might\n ever be used with. Typically set this to something large just in case\n (e.g., 512 or 1024 or 2048).\n type_vocab_size: The vocabulary size of the `token_type_ids` passed into\n `BertModel`.\n initializer_range: The sttdev of the truncated_normal_initializer for\n initializing all weight matrices.\n \"\"\"\n if isinstance(vocab_size_or_config_json_file, str) or (sys.version_info[0] == 2\n and isinstance(vocab_size_or_config_json_file, unicode)):\n with open(vocab_size_or_config_json_file, \"r\", encoding='utf-8') as reader:\n json_config = json.loads(reader.read())\n for key, value in json_config.items():\n self.__dict__[key] = value\n elif isinstance(vocab_size_or_config_json_file, int):\n self.vocab_size = vocab_size_or_config_json_file\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n else:\n raise ValueError(\"First argument must be either a vocabulary size (int)\"\n \"or the path to a pretrained model config file (str)\")\n\n @classmethod\n def from_dict(cls, json_object):\n \"\"\"Constructs a `BertConfig` from a Python dictionary of parameters.\"\"\"\n config = BertConfig(vocab_size_or_config_json_file=-1)\n for key, value in json_object.items():\n config.__dict__[key] = value\n return config\n\n @classmethod\n def from_json_file(cls, json_file):\n \"\"\"Constructs a `BertConfig` from a json file of parameters.\"\"\"\n with open(json_file, \"r\", encoding='utf-8') as reader:\n text = reader.read()\n return cls.from_dict(json.loads(text))\n\n def __repr__(self):\n return str(self.to_json_string())\n\n def to_dict(self):\n \"\"\"Serializes this instance to a Python dictionary.\"\"\"\n output = copy.deepcopy(self.__dict__)\n return output\n\n def to_json_string(self):\n \"\"\"Serializes this instance to a JSON string.\"\"\"\n return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"\n\ntry:\n from apex.normalization.fused_layer_norm import FusedLayerNorm as BertLayerNorm\nexcept ImportError:\n logger.info(\"Better speed can be achieved with apex installed from https://www.github.com/nvidia/apex .\")\n class BertLayerNorm(nn.Module):\n def __init__(self, hidden_size, eps=1e-12):\n \"\"\"Construct a layernorm module in the TF style (epsilon inside the square root).\n \"\"\"\n super(BertLayerNorm, self).__init__()\n self.weight = nn.Parameter(torch.ones(hidden_size))\n self.bias = nn.Parameter(torch.zeros(hidden_size))\n self.variance_epsilon = eps\n\n def forward(self, x):\n u = x.mean(-1, keepdim=True)\n s = (x - u).pow(2).mean(-1, keepdim=True)\n x = (x - u) / torch.sqrt(s + self.variance_epsilon)\n return self.weight * x + self.bias\n\nclass BertEmbeddings(nn.Module):\n \"\"\"Construct the embeddings from word, position and token_type embeddings.\n \"\"\"\n def __init__(self, config):\n super(BertEmbeddings, self).__init__()\n self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=0)\n self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)\n self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)\n\n # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load\n # any TensorFlow checkpoint file\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, input_ids, token_type_ids=None):\n seq_length = input_ids.size(1)\n position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device)\n position_ids = position_ids.unsqueeze(0).expand_as(input_ids)\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n\n words_embeddings = self.word_embeddings(input_ids)\n position_embeddings = self.position_embeddings(position_ids)\n token_type_embeddings = self.token_type_embeddings(token_type_ids)\n\n embeddings = words_embeddings + position_embeddings + token_type_embeddings\n embeddings = self.LayerNorm(embeddings)\n embeddings = self.dropout(embeddings)\n return embeddings\n\n\nclass BertSelfAttention(nn.Module):\n def __init__(self, config):\n super(BertSelfAttention, self).__init__()\n if config.hidden_size % config.num_attention_heads != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" % (config.hidden_size, config.num_attention_heads))\n self.num_attention_heads = config.num_attention_heads\n self.attention_head_size = int(config.hidden_size / config.num_attention_heads)\n self.all_head_size = self.num_attention_heads * self.attention_head_size\n\n self.query = nn.Linear(config.hidden_size, self.all_head_size)\n self.key = nn.Linear(config.hidden_size, self.all_head_size)\n self.value = nn.Linear(config.hidden_size, self.all_head_size)\n\n self.dropout = nn.Dropout(config.attention_probs_dropout_prob)\n\n def transpose_for_scores(self, x):\n new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)\n x = x.view(*new_x_shape)\n return x.permute(0, 2, 1, 3)\n\n def forward(self, hidden_states, attention_mask):\n mixed_query_layer = self.query(hidden_states)\n mixed_key_layer = self.key(hidden_states)\n mixed_value_layer = self.value(hidden_states)\n\n query_layer = self.transpose_for_scores(mixed_query_layer)\n key_layer = self.transpose_for_scores(mixed_key_layer)\n value_layer = self.transpose_for_scores(mixed_value_layer)\n\n # Take the dot product between \"query\" and \"key\" to get the raw attention scores.\n attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))\n attention_scores = attention_scores / math.sqrt(self.attention_head_size)\n # Apply the attention mask is (precomputed for all layers in BertModel forward() function)\n attention_scores = attention_scores + attention_mask\n\n # Normalize the attention scores to probabilities.\n attention_probs = nn.Softmax(dim=-1)(attention_scores)\n\n # This is actually dropping out entire tokens to attend to, which might\n # seem a bit unusual, but is taken from the original Transformer paper.\n attention_probs = self.dropout(attention_probs)\n\n context_layer = torch.matmul(attention_probs, value_layer)\n context_layer = context_layer.permute(0, 2, 1, 3).contiguous()\n new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)\n context_layer = context_layer.view(*new_context_layer_shape)\n return context_layer\n\n\nclass BertSelfOutput(nn.Module):\n def __init__(self, config):\n super(BertSelfOutput, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass BertAttention(nn.Module):\n def __init__(self, config):\n super(BertAttention, self).__init__()\n self.self = BertSelfAttention(config)\n self.output = BertSelfOutput(config)\n\n def forward(self, input_tensor, attention_mask):\n self_output = self.self(input_tensor, attention_mask)\n attention_output = self.output(self_output, input_tensor)\n return attention_output\n\n\nclass BertIntermediate(nn.Module):\n def __init__(self, config):\n super(BertIntermediate, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.intermediate_size)\n if isinstance(config.hidden_act, str) or (sys.version_info[0] == 2 and isinstance(config.hidden_act, unicode)):\n self.intermediate_act_fn = ACT2FN[config.hidden_act]\n else:\n self.intermediate_act_fn = config.hidden_act\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.intermediate_act_fn(hidden_states)\n return hidden_states\n\n\nclass BertOutput(nn.Module):\n def __init__(self, config):\n super(BertOutput, self).__init__()\n self.dense = nn.Linear(config.intermediate_size, config.hidden_size)\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass BertLayer(nn.Module):\n def __init__(self, config):\n super(BertLayer, self).__init__()\n self.attention = BertAttention(config)\n self.intermediate = BertIntermediate(config)\n self.output = BertOutput(config)\n\n def forward(self, hidden_states, attention_mask):\n attention_output = self.attention(hidden_states, attention_mask)\n intermediate_output = self.intermediate(attention_output)\n layer_output = self.output(intermediate_output, attention_output)\n return layer_output\n\n\nclass BertEncoder(nn.Module):\n def __init__(self, config):\n super(BertEncoder, self).__init__()\n layer = BertLayer(config)\n self.layer = nn.ModuleList([copy.deepcopy(layer) for _ in range(config.num_hidden_layers)])\n\n def forward(self, hidden_states, attention_mask, output_all_encoded_layers=True):\n all_encoder_layers = []\n for layer_module in self.layer:\n hidden_states = layer_module(hidden_states, attention_mask)\n if output_all_encoded_layers:\n all_encoder_layers.append(hidden_states)\n if not output_all_encoded_layers:\n all_encoder_layers.append(hidden_states)\n return all_encoder_layers\n\n\nclass BertPooler(nn.Module):\n def __init__(self, config):\n super(BertPooler, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.activation = nn.Tanh()\n\n def forward(self, hidden_states):\n # We \"pool\" the model by simply taking the hidden state corresponding\n # to the first token.\n first_token_tensor = hidden_states[:, 0]\n pooled_output = self.dense(first_token_tensor)\n pooled_output = self.activation(pooled_output)\n return pooled_output\n\n\nclass BertPredictionHeadTransform(nn.Module):\n def __init__(self, config):\n super(BertPredictionHeadTransform, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n if isinstance(config.hidden_act, str) or (sys.version_info[0] == 2 and isinstance(config.hidden_act, unicode)):\n self.transform_act_fn = ACT2FN[config.hidden_act]\n else:\n self.transform_act_fn = config.hidden_act\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.transform_act_fn(hidden_states)\n hidden_states = self.LayerNorm(hidden_states)\n return hidden_states\n\n\nclass BertLMPredictionHead(nn.Module):\n def __init__(self, config, bert_model_embedding_weights):\n super(BertLMPredictionHead, self).__init__()\n self.transform = BertPredictionHeadTransform(config)\n\n # The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n self.decoder = nn.Linear(bert_model_embedding_weights.size(1),\n bert_model_embedding_weights.size(0),\n bias=False)\n self.decoder.weight = bert_model_embedding_weights\n self.bias = nn.Parameter(torch.zeros(bert_model_embedding_weights.size(0)))\n\n def forward(self, hidden_states):\n hidden_states = self.transform(hidden_states)\n hidden_states = self.decoder(hidden_states) + self.bias\n return hidden_states\n\n\nclass BertOnlyMLMHead(nn.Module):\n def __init__(self, config, bert_model_embedding_weights):\n super(BertOnlyMLMHead, self).__init__()\n self.predictions = BertLMPredictionHead(config, bert_model_embedding_weights)\n\n def forward(self, sequence_output):\n prediction_scores = self.predictions(sequence_output)\n return prediction_scores\n\n\nclass BertOnlyNSPHead(nn.Module):\n def __init__(self, config):\n super(BertOnlyNSPHead, self).__init__()\n self.seq_relationship = nn.Linear(config.hidden_size, 2)\n\n def forward(self, pooled_output):\n seq_relationship_score = self.seq_relationship(pooled_output)\n return seq_relationship_score\n\n\nclass BertPreTrainingHeads(nn.Module):\n def __init__(self, config, bert_model_embedding_weights):\n super(BertPreTrainingHeads, self).__init__()\n self.predictions = BertLMPredictionHead(config, bert_model_embedding_weights)\n self.seq_relationship = nn.Linear(config.hidden_size, 2)\n\n def forward(self, sequence_output, pooled_output):\n prediction_scores = self.predictions(sequence_output)\n seq_relationship_score = self.seq_relationship(pooled_output)\n return prediction_scores, seq_relationship_score\n\n\nclass BertPreTrainedModel(nn.Module):\n \"\"\" An abstract class to handle weights initialization and\n a simple interface for dowloading and loading pretrained models.\n \"\"\"\n def __init__(self, config, *inputs, **kwargs):\n super(BertPreTrainedModel, self).__init__()\n if not isinstance(config, BertConfig):\n raise ValueError(\n \"Parameter config in `{}(config)` should be an instance of class `BertConfig`. \"\n \"To create a model from a Google pretrained model use \"\n \"`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`\".format(\n self.__class__.__name__, self.__class__.__name__\n ))\n self.config = config\n\n def init_bert_weights(self, module):\n \"\"\" Initialize the weights.\n \"\"\"\n if isinstance(module, (nn.Linear, nn.Embedding)):\n # Slightly different from the TF version which uses truncated_normal for initialization\n # cf https://github.com/pytorch/pytorch/pull/5617\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n elif isinstance(module, BertLayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n\n @classmethod\n def from_pretrained(cls, pretrained_model_name_or_path, state_dict=None, cache_dir=None,\n from_tf=False, *inputs, **kwargs):\n \"\"\"\n Instantiate a BertPreTrainedModel from a pre-trained model file or a pytorch state dict.\n Download and cache the pre-trained model file if needed.\n\n Params:\n pretrained_model_name_or_path: either:\n - a str with the name of a pre-trained model to load selected in the list of:\n . `bert-base-uncased`\n . `bert-large-uncased`\n . `bert-base-cased`\n . `bert-large-cased`\n . `bert-base-multilingual-uncased`\n . `bert-base-multilingual-cased`\n . `bert-base-chinese`\n - a path or url to a pretrained model archive containing:\n . `bert_config.json` a configuration file for the model\n . `pytorch_model.bin` a PyTorch dump of a BertForPreTraining instance\n - a path or url to a pretrained model archive containing:\n . `bert_config.json` a configuration file for the model\n . `model.chkpt` a TensorFlow checkpoint\n from_tf: should we load the weights from a locally saved TensorFlow checkpoint\n cache_dir: an optional path to a folder in which the pre-trained models will be cached.\n state_dict: an optional state dictionnary (collections.OrderedDict object) to use instead of Google pre-trained models\n *inputs, **kwargs: additional input for the specific Bert class\n (ex: num_labels for BertForSequenceClassification)\n \"\"\"\n if pretrained_model_name_or_path in PRETRAINED_MODEL_ARCHIVE_MAP:\n archive_file = PRETRAINED_MODEL_ARCHIVE_MAP[pretrained_model_name_or_path]\n else:\n archive_file = pretrained_model_name_or_path\n # redirect to the cache, if necessary\n try:\n resolved_archive_file = cached_path(archive_file, cache_dir=cache_dir)\n except EnvironmentError:\n logger.error(\n \"Model name '{}' was not found in model name list ({}). \"\n \"We assumed '{}' was a path or url but couldn't find any file \"\n \"associated to this path or url.\".format(\n pretrained_model_name_or_path,\n ', '.join(PRETRAINED_MODEL_ARCHIVE_MAP.keys()),\n archive_file))\n return None\n if resolved_archive_file == archive_file:\n logger.info(\"loading archive file {}\".format(archive_file))\n else:\n logger.info(\"loading archive file {} from cache at {}\".format(\n archive_file, resolved_archive_file))\n tempdir = None\n if os.path.isdir(resolved_archive_file) or from_tf:\n serialization_dir = resolved_archive_file\n else:\n # Extract archive to temp dir\n tempdir = tempfile.mkdtemp()\n logger.info(\"extracting archive file {} to temp dir {}\".format(\n resolved_archive_file, tempdir))\n with tarfile.open(resolved_archive_file, 'r:gz') as archive:\n archive.extractall(tempdir)\n serialization_dir = tempdir\n # Load config\n config_file = os.path.join(serialization_dir, CONFIG_NAME)\n config = BertConfig.from_json_file(config_file)\n logger.info(\"Model config {}\".format(config))\n # Instantiate model.\n model = cls(config, *inputs, **kwargs)\n if state_dict is None and not from_tf:\n weights_path = os.path.join(serialization_dir, WEIGHTS_NAME)\n state_dict = torch.load(weights_path, map_location='cpu' if not torch.cuda.is_available() else None)\n if tempdir:\n # Clean up temp dir\n shutil.rmtree(tempdir)\n if from_tf:\n # Directly load from a TensorFlow checkpoint\n weights_path = os.path.join(serialization_dir, TF_WEIGHTS_NAME)\n return load_tf_weights_in_bert(model, weights_path)\n # Load from a PyTorch state_dict\n old_keys = []\n new_keys = []\n for key in state_dict.keys():\n new_key = None\n if 'gamma' in key:\n new_key = key.replace('gamma', 'weight')\n if 'beta' in key:\n new_key = key.replace('beta', 'bias')\n if new_key:\n old_keys.append(key)\n new_keys.append(new_key)\n for old_key, new_key in zip(old_keys, new_keys):\n state_dict[new_key] = state_dict.pop(old_key)\n\n missing_keys = []\n unexpected_keys = []\n error_msgs = []\n # copy state_dict so _load_from_state_dict can modify it\n metadata = getattr(state_dict, '_metadata', None)\n state_dict = state_dict.copy()\n if metadata is not None:\n state_dict._metadata = metadata\n\n def load(module, prefix=''):\n local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})\n module._load_from_state_dict(\n state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs)\n for name, child in module._modules.items():\n if child is not None:\n load(child, prefix + name + '.')\n start_prefix = ''\n if not hasattr(model, 'bert') and any(s.startswith('bert.') for s in state_dict.keys()):\n start_prefix = 'bert.'\n load(model, prefix=start_prefix)\n if len(missing_keys) > 0:\n logger.info(\"Weights of {} not initialized from pretrained model: {}\".format(\n model.__class__.__name__, missing_keys))\n if len(unexpected_keys) > 0:\n logger.info(\"Weights from pretrained model not used in {}: {}\".format(\n model.__class__.__name__, unexpected_keys))\n if len(error_msgs) > 0:\n raise RuntimeError('Error(s) in loading state_dict for {}:\\n\\t{}'.format(\n model.__class__.__name__, \"\\n\\t\".join(error_msgs)))\n return model\n\n\nclass BertModel(BertPreTrainedModel):\n \"\"\"BERT model (\"Bidirectional Embedding Representations from a Transformer\").\n\n Params:\n config: a BertConfig class instance with the configuration to build a new model\n\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]\n with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token\n types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to\n a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `output_all_encoded_layers`: boolean which controls the content of the `encoded_layers` output as described below. Default: `True`.\n\n Outputs: Tuple of (encoded_layers, pooled_output)\n `encoded_layers`: controled by `output_all_encoded_layers` argument:\n - `output_all_encoded_layers=True`: outputs a list of the full sequences of encoded-hidden-states at the end\n of each attention block (i.e. 12 full sequences for BERT-base, 24 for BERT-large), each\n encoded-hidden-state is a torch.FloatTensor of size [batch_size, sequence_length, hidden_size],\n - `output_all_encoded_layers=False`: outputs only the full sequence of hidden-states corresponding\n to the last attention block of shape [batch_size, sequence_length, hidden_size],\n `pooled_output`: a torch.FloatTensor of size [batch_size, hidden_size] which is the output of a\n classifier pretrained on top of the hidden state associated to the first character of the\n input (`CLS`) to train on the Next-Sentence task (see BERT's paper).\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])\n input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])\n token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])\n\n config = modeling.BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,\n num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)\n\n model = modeling.BertModel(config=config)\n all_encoder_layers, pooled_output = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n def __init__(self, config):\n super(BertModel, self).__init__(config)\n self.embeddings = BertEmbeddings(config)\n self.encoder = BertEncoder(config)\n self.pooler = BertPooler(config)\n self.apply(self.init_bert_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, output_all_encoded_layers=True):\n if attention_mask is None:\n attention_mask = torch.ones_like(input_ids)\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n\n # We create a 3D attention mask from a 2D tensor mask.\n # Sizes are [batch_size, 1, 1, to_seq_length]\n # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]\n # this attention mask is more simple than the triangular masking of causal attention\n # used in OpenAI GPT, we just need to prepare the broadcast dimension here.\n extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n\n embedding_output = self.embeddings(input_ids, token_type_ids)\n encoded_layers = self.encoder(embedding_output,\n extended_attention_mask,\n output_all_encoded_layers=output_all_encoded_layers)\n sequence_output = encoded_layers[-1]\n pooled_output = self.pooler(sequence_output)\n if not output_all_encoded_layers:\n encoded_layers = encoded_layers[-1]\n return encoded_layers, pooled_output\n\n\nclass BertForPreTraining(BertPreTrainedModel):\n \"\"\"BERT model with pre-training heads.\n This module comprises the BERT model followed by the two pre-training heads:\n - the masked language modeling head, and\n - the next sentence classification head.\n\n Params:\n config: a BertConfig class instance with the configuration to build a new model.\n\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]\n with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token\n types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to\n a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `masked_lm_labels`: optional masked language modeling labels: torch.LongTensor of shape [batch_size, sequence_length]\n with indices selected in [-1, 0, ..., vocab_size]. All labels set to -1 are ignored (masked), the loss\n is only computed for the labels set in [0, ..., vocab_size]\n `next_sentence_label`: optional next sentence classification loss: torch.LongTensor of shape [batch_size]\n with indices selected in [0, 1].\n 0 => next sentence is the continuation, 1 => next sentence is a random sentence.\n\n Outputs:\n if `masked_lm_labels` and `next_sentence_label` are not `None`:\n Outputs the total_loss which is the sum of the masked language modeling loss and the next\n sentence classification loss.\n if `masked_lm_labels` or `next_sentence_label` is `None`:\n Outputs a tuple comprising\n - the masked language modeling logits of shape [batch_size, sequence_length, vocab_size], and\n - the next sentence classification logits of shape [batch_size, 2].\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])\n input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])\n token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])\n\n config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,\n num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)\n\n model = BertForPreTraining(config)\n masked_lm_logits_scores, seq_relationship_logits = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n def __init__(self, config):\n super(BertForPreTraining, self).__init__(config)\n self.bert = BertModel(config)\n self.cls = BertPreTrainingHeads(config, self.bert.embeddings.word_embeddings.weight)\n self.apply(self.init_bert_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None, next_sentence_label=None):\n sequence_output, pooled_output = self.bert(input_ids, token_type_ids, attention_mask,\n output_all_encoded_layers=False)\n prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)\n\n if masked_lm_labels is not None and next_sentence_label is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-1)\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))\n next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))\n total_loss = masked_lm_loss + next_sentence_loss\n return total_loss\n else:\n return prediction_scores, seq_relationship_score\n\n\nclass BertForMaskedLM(BertPreTrainedModel):\n \"\"\"BERT model with the masked language modeling head.\n This module comprises the BERT model followed by the masked language modeling head.\n\n Params:\n config: a BertConfig class instance with the configuration to build a new model.\n\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]\n with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token\n types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to\n a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `masked_lm_labels`: masked language modeling labels: torch.LongTensor of shape [batch_size, sequence_length]\n with indices selected in [-1, 0, ..., vocab_size]. All labels set to -1 are ignored (masked), the loss\n is only computed for the labels set in [0, ..., vocab_size]\n\n Outputs:\n if `masked_lm_labels` is not `None`:\n Outputs the masked language modeling loss.\n if `masked_lm_labels` is `None`:\n Outputs the masked language modeling logits of shape [batch_size, sequence_length, vocab_size].\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])\n input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])\n token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])\n\n config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,\n num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)\n\n model = BertForMaskedLM(config)\n masked_lm_logits_scores = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n def __init__(self, config):\n super(BertForMaskedLM, self).__init__(config)\n self.bert = BertModel(config)\n self.cls = BertOnlyMLMHead(config, self.bert.embeddings.word_embeddings.weight)\n self.apply(self.init_bert_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None):\n sequence_output, _ = self.bert(input_ids, token_type_ids, attention_mask,\n output_all_encoded_layers=False)\n prediction_scores = self.cls(sequence_output)\n\n if masked_lm_labels is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-1)\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))\n return masked_lm_loss\n else:\n return prediction_scores\n\n\nclass BertForNextSentencePrediction(BertPreTrainedModel):\n \"\"\"BERT model with next sentence prediction head.\n This module comprises the BERT model followed by the next sentence classification head.\n\n Params:\n config: a BertConfig class instance with the configuration to build a new model.\n\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]\n with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token\n types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to\n a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `next_sentence_label`: next sentence classification loss: torch.LongTensor of shape [batch_size]\n with indices selected in [0, 1].\n 0 => next sentence is the continuation, 1 => next sentence is a random sentence.\n\n Outputs:\n if `next_sentence_label` is not `None`:\n Outputs the total_loss which is the sum of the masked language modeling loss and the next\n sentence classification loss.\n if `next_sentence_label` is `None`:\n Outputs the next sentence classification logits of shape [batch_size, 2].\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])\n input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])\n token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])\n\n config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,\n num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)\n\n model = BertForNextSentencePrediction(config)\n seq_relationship_logits = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n def __init__(self, config):\n super(BertForNextSentencePrediction, self).__init__(config)\n self.bert = BertModel(config)\n self.cls = BertOnlyNSPHead(config)\n self.apply(self.init_bert_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, next_sentence_label=None):\n _, pooled_output = self.bert(input_ids, token_type_ids, attention_mask,\n output_all_encoded_layers=False)\n seq_relationship_score = self.cls( pooled_output)\n\n if next_sentence_label is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-1)\n next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))\n return next_sentence_loss\n else:\n return seq_relationship_score\n\n\nclass BertForSequenceClassification(BertPreTrainedModel):\n \"\"\"BERT model for classification.\n This module is composed of the BERT model with a linear layer on top of\n the pooled output.\n\n Params:\n `config`: a BertConfig class instance with the configuration to build a new model.\n `num_labels`: the number of classes for the classifier. Default = 2.\n\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]\n with the word token indices in the vocabulary. Items in the batch should begin with the special \"CLS\" token. (see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token\n types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to\n a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `labels`: labels for the classification output: torch.LongTensor of shape [batch_size]\n with indices selected in [0, ..., num_labels].\n\n Outputs:\n if `labels` is not `None`:\n Outputs the CrossEntropy classification loss of the output with the labels.\n if `labels` is `None`:\n Outputs the classification logits of shape [batch_size, num_labels].\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])\n input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])\n token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])\n\n config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,\n num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)\n\n num_labels = 2\n\n model = BertForSequenceClassification(config, num_labels)\n logits = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n def __init__(self, config, num_labels):\n super(BertForSequenceClassification, self).__init__(config)\n self.num_labels = num_labels\n self.bert = BertModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, num_labels)\n self.apply(self.init_bert_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None):\n _, pooled_output = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)\n pooled_output = self.dropout(pooled_output)\n logits = self.classifier(pooled_output)\n\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n return loss\n else:\n return logits\n\n\nclass BertForMultipleChoice(BertPreTrainedModel):\n \"\"\"BERT model for multiple choice tasks.\n This module is composed of the BERT model with a linear layer on top of\n the pooled output.\n\n Params:\n `config`: a BertConfig class instance with the configuration to build a new model.\n `num_choices`: the number of classes for the classifier. Default = 2.\n\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, num_choices, sequence_length]\n with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, num_choices, sequence_length]\n with the token types indices selected in [0, 1]. Type 0 corresponds to a `sentence A`\n and type 1 corresponds to a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, num_choices, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `labels`: labels for the classification output: torch.LongTensor of shape [batch_size]\n with indices selected in [0, ..., num_choices].\n\n Outputs:\n if `labels` is not `None`:\n Outputs the CrossEntropy classification loss of the output with the labels.\n if `labels` is `None`:\n Outputs the classification logits of shape [batch_size, num_labels].\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[[31, 51, 99], [15, 5, 0]], [[12, 16, 42], [14, 28, 57]]])\n input_mask = torch.LongTensor([[[1, 1, 1], [1, 1, 0]],[[1,1,0], [1, 0, 0]]])\n token_type_ids = torch.LongTensor([[[0, 0, 1], [0, 1, 0]],[[0, 1, 1], [0, 0, 1]]])\n config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,\n num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)\n\n num_choices = 2\n\n model = BertForMultipleChoice(config, num_choices)\n logits = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n def __init__(self, config, num_choices):\n super(BertForMultipleChoice, self).__init__(config)\n self.num_choices = num_choices\n self.bert = BertModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, 1)\n self.apply(self.init_bert_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None):\n flat_input_ids = input_ids.view(-1, input_ids.size(-1))\n flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1))\n flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1))\n _, pooled_output = self.bert(flat_input_ids, flat_token_type_ids, flat_attention_mask, output_all_encoded_layers=False)\n pooled_output = self.dropout(pooled_output)\n logits = self.classifier(pooled_output)\n reshaped_logits = logits.view(-1, self.num_choices)\n\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(reshaped_logits, labels)\n return loss\n else:\n return reshaped_logits\n\n\nclass BertForTokenClassification(BertPreTrainedModel):\n \"\"\"BERT model for token-level classification.\n This module is composed of the BERT model with a linear layer on top of\n the full hidden state of the last layer.\n\n Params:\n `config`: a BertConfig class instance with the configuration to build a new model.\n `num_labels`: the number of classes for the classifier. Default = 2.\n\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]\n with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token\n types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to\n a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `labels`: labels for the classification output: torch.LongTensor of shape [batch_size, sequence_length]\n with indices selected in [0, ..., num_labels].\n\n Outputs:\n if `labels` is not `None`:\n Outputs the CrossEntropy classification loss of the output with the labels.\n if `labels` is `None`:\n Outputs the classification logits of shape [batch_size, sequence_length, num_labels].\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])\n input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])\n token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])\n\n config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,\n num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)\n\n num_labels = 2\n\n model = BertForTokenClassification(config, num_labels)\n logits = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n def __init__(self, config, num_labels):\n super(BertForTokenClassification, self).__init__(config)\n self.num_labels = num_labels\n self.bert = BertModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, num_labels)\n self.apply(self.init_bert_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None):\n sequence_output, _ = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)\n sequence_output = self.dropout(sequence_output)\n logits = self.classifier(sequence_output)\n\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n # Only keep active parts of the loss\n if attention_mask is not None:\n active_loss = attention_mask.view(-1) == 1\n active_logits = logits.view(-1, self.num_labels)[active_loss]\n active_labels = labels.view(-1)[active_loss]\n loss = loss_fct(active_logits, active_labels)\n else:\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n return loss\n else:\n return logits\n\n\nclass BertForQuestionAnswering(BertPreTrainedModel):\n \"\"\"BERT model for Question Answering (span extraction).\n This module is composed of the BERT model with a linear layer on top of\n the sequence output that computes start_logits and end_logits\n\n Params:\n `config`: a BertConfig class instance with the configuration to build a new model.\n\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]\n with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token\n types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to\n a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `start_positions`: position of the first token for the labeled span: torch.LongTensor of shape [batch_size].\n Positions are clamped to the length of the sequence and position outside of the sequence are not taken\n into account for computing the loss.\n `end_positions`: position of the last token for the labeled span: torch.LongTensor of shape [batch_size].\n Positions are clamped to the length of the sequence and position outside of the sequence are not taken\n into account for computing the loss.\n\n Outputs:\n if `start_positions` and `end_positions` are not `None`:\n Outputs the total_loss which is the sum of the CrossEntropy loss for the start and end token positions.\n if `start_positions` or `end_positions` is `None`:\n Outputs a tuple of start_logits, end_logits which are the logits respectively for the start and end\n position tokens of shape [batch_size, sequence_length].\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])\n input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])\n token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])\n\n config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,\n num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)\n\n model = BertForQuestionAnswering(config)\n start_logits, end_logits = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n def __init__(self, config):\n super(BertForQuestionAnswering, self).__init__(config)\n self.bert = BertModel(config)\n # TODO check with Google if it's normal there is no dropout on the token classifier of SQuAD in the TF version\n # self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.qa_outputs = nn.Linear(config.hidden_size, 2)\n self.apply(self.init_bert_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, start_positions=None, end_positions=None):\n sequence_output, _ = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1)\n end_logits = end_logits.squeeze(-1)\n\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions.clamp_(0, ignored_index)\n end_positions.clamp_(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n return total_loss\n else:\n return start_logits, end_logits\n"
]
| [
[
"torch.nn.Linear",
"torch.ones",
"torch.cuda.is_available",
"torch.nn.CrossEntropyLoss",
"torch.sigmoid",
"torch.sqrt",
"torch.nn.Softmax",
"tensorflow.train.list_variables",
"numpy.transpose",
"torch.zeros_like",
"torch.zeros",
"tensorflow.train.load_variable",
"torch.nn.Tanh",
"torch.matmul",
"torch.nn.Dropout",
"torch.arange",
"torch.from_numpy",
"torch.ones_like",
"torch.nn.Embedding"
]
]
|
LOVEChen/raspberry-pilot | [
"4f01dcad4629577bcb268118375fae7473103a53"
]
| [
"selfdrive/controls/lib/pid.py"
]
| [
"import numpy as np\r\nfrom common.numpy_fast import clip, interp\r\n\r\ndef apply_deadzone(error, deadzone):\r\n if error > deadzone:\r\n error -= deadzone\r\n elif error < - deadzone:\r\n error += deadzone\r\n else:\r\n error = 0.\r\n return error\r\n\r\nclass PIController(object):\r\n def __init__(self, k_p, k_i, k_f=1., pos_limit=None, neg_limit=None, rate=100, sat_limit=0.8, convert=None):\r\n self._k_p = k_p # proportional gain\r\n self._k_i = k_i # integral gain\r\n self.k_f = k_f # feedforward gain\r\n\r\n self.pos_limit = 1.0\r\n self.neg_limit = -1.0\r\n\r\n self.sat_count_rate = 1.0 / rate\r\n self.i_unwind_rate = 0.3 / rate\r\n self.i_rate = 1.0 / rate\r\n self.sat_limit = sat_limit\r\n self.convert = convert\r\n\r\n self.reset()\r\n\r\n @property\r\n def k_p(self):\r\n return interp(self.speed, self._k_p[0], self._k_p[1])\r\n\r\n @property\r\n def k_i(self):\r\n return interp(self.speed, self._k_i[0], self._k_i[1])\r\n\r\n def _check_saturation(self, control, override, error):\r\n saturated = (control < self.neg_limit) or (control > self.pos_limit)\r\n\r\n if saturated and not override and abs(error) > 0.1:\r\n self.sat_count += self.sat_count_rate\r\n else:\r\n self.sat_count -= self.sat_count_rate\r\n\r\n self.sat_count = clip(self.sat_count, 0.0, 1.0)\r\n\r\n return self.sat_count > self.sat_limit\r\n\r\n def reset(self):\r\n self.p = 0.0\r\n self.p2 = 0.0\r\n self.i = 0.0\r\n self.f = 0.0\r\n self.sat_count = 0.0\r\n self.saturated = False\r\n self.control = 0\r\n\r\n def update(self, setpoint, measurement, speed=0.0, check_saturation=True, override=False, feedforward=0., deadzone=0., freeze_integrator=False, add_error=0.0, p_scale=1.0):\r\n self.speed = speed\r\n\r\n error = float(apply_deadzone(setpoint - measurement, deadzone))\r\n self.p = error * self.k_p * p_scale\r\n self.p2 = add_error * self.k_p\r\n self.f = feedforward * self.k_f\r\n\r\n if override and not self.saturated:\r\n self.i -= self.i_unwind_rate * float(np.sign(self.i))\r\n else:\r\n i = self.i + error * self.k_i * self.i_rate\r\n control = self.p + self.p2 + self.f + i\r\n\r\n if self.convert is not None:\r\n control = self.convert(control, speed=self.speed)\r\n\r\n # Update when changing i will move the control away from the limits\r\n # or when i will move towards the sign of the error\r\n if ((error >= 0 and (control <= self.pos_limit or i < 0.0)) or \\\r\n (error <= 0 and (control >= self.neg_limit or i > 0.0))) and \\\r\n not freeze_integrator and not error * add_error < 0:\r\n self.i = i\r\n\r\n control = self.p + self.p2 + self.f + self.i\r\n if self.convert is not None:\r\n control = self.convert(control, speed=self.speed)\r\n\r\n if check_saturation:\r\n self.saturated = self._check_saturation(control, override, (error + add_error))\r\n else:\r\n self.saturated = False\r\n\r\n self.control = clip(control, self.neg_limit, self.pos_limit)\r\n return self.control\r\n"
]
| [
[
"numpy.sign"
]
]
|
kamilszewc/smoothie | [
"bc19eb1c296b102370d4a44dc870a14aa3fabf8b"
]
| [
"cSPH2d/Postproc/PostProc/Field.py"
]
| [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# All right reserved by Kamil Szewc, Gdansk 2009 \n\n\nimport numpy as np\nfrom Point import Point\ntry:\n from multiprocessing import Process, Queue, cpu_count\n class Multi(Process):\n pass\nexcept ImportError:\n from threading import Thread\n from Queue import Queue\n class Multi(Thread):\n pass\n def cpu_count():\n return 1\n\nclass Field:\n def __init__(self, d, *arg):\n if arg != (): d.NX = arg[0]; d.NY = arg[1]\n self.dx = d.XCV/float(d.NX)\n self.dy = d.YCV/float(d.NY)\n self.x = np.linspace(self.dx*0.5, self.dx*0.5+self.dx*float(d.NX-1), d.NX)\n self.y = np.linspace(self.dy*0.5, self.dy*0.5+self.dy*float(d.NY-1), d.NY)\n self.u = np.zeros( (len(self.y),len(self.x)) )\n self.v = np.zeros( (len(self.y),len(self.x)) )\n self.p = np.zeros( (len(self.y),len(self.x)) )\n self.d = np.zeros( (len(self.y),len(self.x)) )\n self.tp = np.zeros( (len(self.y),len(self.x)) )\n\n ncpu = cpu_count()\n clen = len(self.x)*len(self.y)\n clist = range(clen)\n clen = clen/2\n clists = [ clist[n*clen:(n+1)*clen] for n in range(ncpu)[:-1] ]\n clists.append(clist[(ncpu-1)*clen:])\n\n qs = [Queue() for n in range(ncpu)]\n ps = [Multi(target=self._point, args=(clists[n],d,qs[n],)) for n in range(ncpu)]\n for n in range(ncpu): ps[n].start()\n for n in range(ncpu): qs[n] = qs[n].get()\n for n in range(ncpu): ps[n].join()\n for n in range(ncpu):\n self.u += qs[n][0]\n self.v += qs[n][1]\n self.p += qs[n][2]\n self.d += qs[n][3]\n self.tp+= qs[n][4]\n self.x,self.y = np.meshgrid(self.x,self.y)\n\n def _point(self, clist, d, q):\n for c in clist:\n i = c%len(self.x)\n j = ((c-i)/len(self.x))%len(self.y)\n values = Point(self.x[i], self.y[j], d)\n self.u[j,i] = values.u\n self.v[j,i] = values.v\n self.p[j,i] = values.p\n self.d[j,i] = values.d\n self.tp[j,i] = values.tp\n q.put((self.u,self.v,self.p,self.d,self.tp))\n\nclass FieldS:\n def __init__(self, d):\n self.dx = d.XCV/float(d.NX)\n self.dy = d.YCV/float(d.NY)\n self.x = np.linspace(self.dx*0.5, self.dx*0.5+self.dx*float(d.NX-1), d.NX)\n self.y = np.linspace(self.dy*0.5, self.dy*0.5+self.dy*float(d.NY-1), d.NY)\n self.u = np.zeros( (len(self.y),len(self.x)) )\n self.v = np.zeros( (len(self.y),len(self.x)) )\n self.p = np.zeros( (len(self.y),len(self.x)) )\n self.d = np.zeros( (len(self.y),len(self.x)) )\n self.tp = np.zeros( (len(self.y),len(self.x)) )\n for i in range(d.NX):\n for j in range(d.NY):\n values = Point(self.x[i], self.y[j], d)\n self.u[j,i] = values.u\n self.v[j,i] = values.v\n self.p[j,i] = values.p\n self.d[j,i] = values.d\n self.tp[j,i] = values.tp\n\n\nclass PField:\n def __init__(self, x, y, data):\n self.x, self.y = x, y\n self.u, self.v, self.p, self.d, self.tp = [], [], [], [], []\n for i in range(len(x)):\n values = Point(x[i], y[i], data)\n self.u.append(values.u)\n self.v.append(values.v)\n self.p.append(values.p)\n self.d.append(values.d)\n self.tp.append(values.tp)\n \nclass XField:\n def __init__(self, x, y, data):\n self.x = x\n self.ny, self.u, self.v, self.p, self.d, self.tp = [], [], [], [], [], []\n for i in range(len(x)):\n values = Point(x[i], y, data)\n self.ny.append(y)\n self.u.append(values.u)\n self.v.append(values.v)\n self.p.append(values.p)\n self.d.append(values.d)\n self.tp.append(values.tp)\n \nclass YField:\n def __init__(self, x, y, data):\n self.y = y\n self.nx, self.u, self.v, self.p, self.d, self.tp = [], [], [], [], [], []\n for i in range(len(y)):\n values = Point(x, y[i], data)\n self.nx.append(x)\n self.u.append(values.u)\n self.v.append(values.v)\n self.p.append(values.p)\n self.d.append(values.d)\n self.tp.append(values.tp)\n"
]
| [
[
"numpy.meshgrid"
]
]
|
rzats/3DDFA | [
"5c90675ac02c90edfd964f7324cc997b16ebd6c8"
]
| [
"utils/inference.py"
]
| [
"#!/usr/bin/env python3\n# coding: utf-8\n__author__ = 'cleardusk'\n\nimport numpy as np\nfrom math import sqrt\nimport scipy.io as sio\nimport matplotlib.pyplot as plt\nfrom .ddfa import reconstruct_vertex\n\n\ndef get_suffix(filename):\n \"\"\"a.jpg -> jpg\"\"\"\n pos = filename.rfind('.')\n if pos == -1:\n return ''\n return filename[pos:]\n\n\ndef crop_img(img, roi_box):\n h, w = img.shape[:2]\n\n sx, sy, ex, ey = [int(round(_)) for _ in roi_box]\n dh, dw = ey - sy, ex - sx\n if len(img.shape) == 3:\n res = np.zeros((dh, dw, 3), dtype=np.uint8)\n else:\n res = np.zeros((dh, dw), dtype=np.uint8)\n if sx < 0:\n sx, dsx = 0, -sx\n else:\n dsx = 0\n\n if ex > w:\n ex, dex = w, dw - (ex - w)\n else:\n dex = dw\n\n if sy < 0:\n sy, dsy = 0, -sy\n else:\n dsy = 0\n\n if ey > h:\n ey, dey = h, dh - (ey - h)\n else:\n dey = dh\n\n res[dsy:dey, dsx:dex] = img[sy:ey, sx:ex]\n return res\n\n\ndef calc_hypotenuse(pts):\n bbox = [min(pts[0, :]), min(pts[1, :]), max(pts[0, :]), max(pts[1, :])]\n center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]\n radius = max(bbox[2] - bbox[0], bbox[3] - bbox[1]) / 2\n bbox = [center[0] - radius, center[1] - radius, center[0] + radius, center[1] + radius]\n llength = sqrt((bbox[2] - bbox[0]) ** 2 + (bbox[3] - bbox[1]) ** 2)\n return llength / 3\n\n\ndef parse_roi_box_from_landmark(pts):\n \"\"\"calc roi box from landmark\"\"\"\n bbox = [min(pts[0, :]), min(pts[1, :]), max(pts[0, :]), max(pts[1, :])]\n center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]\n radius = max(bbox[2] - bbox[0], bbox[3] - bbox[1]) / 2\n bbox = [center[0] - radius, center[1] - radius, center[0] + radius, center[1] + radius]\n\n llength = sqrt((bbox[2] - bbox[0]) ** 2 + (bbox[3] - bbox[1]) ** 2)\n center_x = (bbox[2] + bbox[0]) / 2\n center_y = (bbox[3] + bbox[1]) / 2\n\n roi_box = [0] * 4\n roi_box[0] = center_x - llength / 2\n roi_box[1] = center_y - llength / 2\n roi_box[2] = roi_box[0] + llength\n roi_box[3] = roi_box[1] + llength\n\n return roi_box\n\n\ndef parse_roi_box_from_bbox(bbox):\n left, top, right, bottom = bbox\n old_size = (right - left + bottom - top) / 2\n center_x = right - (right - left) / 2.0\n center_y = bottom - (bottom - top) / 2.0 + old_size * 0.14\n size = int(old_size * 1.58)\n roi_box = [0] * 4\n roi_box[0] = center_x - size / 2\n roi_box[1] = center_y - size / 2\n roi_box[2] = roi_box[0] + size\n roi_box[3] = roi_box[1] + size\n return roi_box\n\n\ndef dump_to_ply(vertex, tri, wfp):\n header = \"\"\"ply\n format ascii 1.0\n element vertex {}\n property float x\n property float y\n property float z\n element face {}\n property list uchar int vertex_indices\n end_header\"\"\"\n\n n_vertex = vertex.shape[1]\n n_face = tri.shape[1]\n header = header.format(n_vertex, n_face)\n\n with open(wfp, 'w') as f:\n f.write(header + '\\n')\n for i in range(n_vertex):\n x, y, z = vertex[:, i]\n f.write('{:.4f} {:.4f} {:.4f}\\n'.format(x, y, z))\n for i in range(n_face):\n idx1, idx2, idx3 = tri[:, i]\n f.write('3 {} {} {}\\n'.format(idx1 - 1, idx2 - 1, idx3 - 1))\n print('Dump tp {}'.format(wfp))\n\n\ndef dump_vertex(vertex, wfp):\n sio.savemat(wfp, {'vertex': vertex})\n print('Dump to {}'.format(wfp))\n\n\ndef _predict_vertices(param, roi_bbox, dense, transform=True):\n vertex = reconstruct_vertex(param, dense=dense)\n sx, sy, ex, ey = roi_bbox\n scale_x = (ex - sx) / 120\n scale_y = (ey - sy) / 120\n vertex[0, :] = vertex[0, :] * scale_x + sx\n vertex[1, :] = vertex[1, :] * scale_y + sy\n\n s = (scale_x + scale_y) / 2\n vertex[2, :] *= s\n\n return vertex\n\n\ndef predict_68pts(param, roi_box):\n return _predict_vertices(param, roi_box, dense=False)\n\n\ndef predict_dense(param, roi_box):\n return _predict_vertices(param, roi_box, dense=True)\n\n\ndef draw_landmarks(img, pts, style='fancy', wfp=None, show_flg=False, **kwargs):\n \"\"\"Draw landmarks using matplotlib\"\"\"\n height, width = img.shape[:2]\n plt.figure(figsize=(12, height / width * 12))\n plt.imshow(img[:, :, ::-1])\n plt.subplots_adjust(left=0, right=1, top=1, bottom=0)\n plt.axis('off')\n\n if not type(pts) in [tuple, list]:\n pts = [pts]\n for i in range(len(pts)):\n if style == 'simple':\n plt.plot(pts[i][0, :], pts[i][1, :], 'o', markersize=4, color='g')\n\n elif style == 'fancy':\n alpha = 0.8\n markersize = 4\n lw = 1.5\n color = kwargs.get('color', 'w')\n markeredgecolor = kwargs.get('markeredgecolor', 'black')\n\n nums = [0, 17, 22, 27, 31, 36, 42, 48, 60, 68]\n face_polygon = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17]\n\n # close eyes and mouths\n #plot_close = lambda i1, i2: plt.plot([pts[i][0, i1], pts[i][0, i2]], [pts[i][1, i1], pts[i][1, i2]],\n # color=color, lw=lw, alpha=alpha - 0.1)\n #plot_close(41, 36)\n #plot_close(47, 42)\n #plot_close(59, 48)\n #plot_close(67, 60)\n\n #for ind in range(len(nums) - 1):\n # l, r = nums[ind], nums[ind + 1]\n # plt.plot(pts[i][0, l:r], pts[i][1, l:r], color=color, lw=lw, alpha=alpha - 0.1)\n\n # plt.plot(pts[i][0, l:r], pts[i][1, l:r], marker='o', linestyle='None', markersize=markersize,\n # color=color,\n # markeredgecolor=markeredgecolor, alpha=alpha)\n for ind in range(68):\n plt.text(pts[i][0, ind], pts[i][1, ind], ind)\n plt.plot([pts[i][0, 0], pts[i][0, face_polygon[len(face_polygon)-1]]], [pts[i][1, 0], pts[i][1, face_polygon[len(face_polygon)-1]]], color=color, lw=lw, alpha=alpha - 0.1)\n for ind in range(len(face_polygon) - 1):\n l, r = face_polygon[ind], face_polygon[ind + 1]\n plt.plot([pts[i][0, l], pts[i][0, r]], [pts[i][1, l], pts[i][1, r]], color=color, lw=lw, alpha=alpha - 0.1)\n\n plt.plot([pts[i][0, l], pts[i][0, r]], [pts[i][1, l], pts[i][1, r]], marker='o', linestyle='None', markersize=markersize,\n color=color,\n markeredgecolor=markeredgecolor, alpha=alpha)\n\n if wfp is not None:\n plt.savefig(wfp, dpi=200)\n print('Save visualization result to {}'.format(wfp))\n if show_flg:\n plt.show()\n\n\ndef get_colors(image, vertices):\n [h, w, _] = image.shape\n vertices[0, :] = np.minimum(np.maximum(vertices[0, :], 0), w - 1) # x\n vertices[1, :] = np.minimum(np.maximum(vertices[1, :], 0), h - 1) # y\n ind = np.round(vertices).astype(np.int32)\n colors = image[ind[1, :], ind[0, :], :] # n x 3\n\n return colors\n\n\ndef write_obj_with_colors(obj_name, vertices, triangles, colors):\n triangles = triangles.copy() # meshlab start with 1\n\n if obj_name.split('.')[-1] != 'obj':\n obj_name = obj_name + '.obj'\n\n # write obj\n with open(obj_name, 'w') as f:\n # write vertices & colors\n for i in range(vertices.shape[1]):\n s = 'v {:.4f} {:.4f} {:.4f} {} {} {}\\n'.format(vertices[1, i], vertices[0, i], vertices[2, i], colors[i, 2],\n colors[i, 1], colors[i, 0])\n f.write(s)\n\n # write f: ver ind/ uv ind\n for i in range(triangles.shape[1]):\n s = 'f {} {} {}\\n'.format(triangles[0, i], triangles[1, i], triangles[2, i])\n f.write(s)\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n"
]
| [
[
"matplotlib.pyplot.text",
"numpy.zeros",
"numpy.round",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.figure",
"scipy.io.savemat",
"numpy.maximum",
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.imshow"
]
]
|
MatthewAbugeja/agw | [
"51c3d549e3cb8cecfd21e7b73af81b73d8996357"
]
| [
"video-reid-AWG/models/non_local.py"
]
| [
"# encoding: utf-8\n\nimport torch\nfrom torch import nn\n\n\nclass Non_local(nn.Module):\n def __init__(self, in_channels, reduc_ratio=2):\n super(Non_local, self).__init__()\n\n self.in_channels = in_channels\n self.inter_channels = reduc_ratio // reduc_ratio\n\n self.g = nn.Conv2d(in_channels=self.in_channels, out_channels=self.inter_channels,\n kernel_size=1, stride=1, padding=0)\n\n self.W = nn.Sequential(\n nn.Conv2d(in_channels=self.inter_channels, out_channels=self.in_channels,\n kernel_size=1, stride=1, padding=0),\n nn.BatchNorm2d(self.in_channels),\n )\n nn.init.constant_(self.W[1].weight, 0.0)\n nn.init.constant_(self.W[1].bias, 0.0)\n\n self.theta = nn.Conv2d(in_channels=self.in_channels, out_channels=self.inter_channels,\n kernel_size=1, stride=1, padding=0)\n\n self.phi = nn.Conv2d(in_channels=self.in_channels, out_channels=self.inter_channels,\n kernel_size=1, stride=1, padding=0)\n\n def forward(self, x):\n '''\n :param x: (b, c, h, w)\n :return x: (b, c, h, w)\n '''\n batch_size = x.size(0)\n g_x = self.g(x).view(batch_size, self.inter_channels, -1)\n g_x = g_x.permute(0, 2, 1)\n\n theta_x = self.theta(x).view(batch_size, self.inter_channels, -1)\n theta_x = theta_x.permute(0, 2, 1)\n phi_x = self.phi(x).view(batch_size, self.inter_channels, -1)\n f = torch.matmul(theta_x, phi_x)\n N = f.size(-1)\n f_div_C = f / N\n\n y = torch.matmul(f_div_C, g_x)\n y = y.permute(0, 2, 1).contiguous()\n y = y.view(batch_size, self.inter_channels, *x.size()[2:])\n W_y = self.W(y)\n z = W_y + x\n return z\n"
]
| [
[
"torch.nn.Conv2d",
"torch.nn.BatchNorm2d",
"torch.matmul",
"torch.nn.init.constant_"
]
]
|
huangjun12/Paddle | [
"780140599f7b4621bd29066a8ced1be120862a89"
]
| [
"python/paddle/fluid/layers/loss.py"
]
| [
"# Copyright (c) 2019 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\nfrom __future__ import print_function\n\nimport numpy as np\nfrom functools import partial, reduce\nfrom paddle.utils import deprecated\nfrom . import nn\nfrom .layer_function_generator import templatedoc\nfrom ..layer_helper import LayerHelper\nfrom ..framework import Variable, in_dygraph_mode\nfrom .. import core\nfrom ..data_feeder import check_variable_and_dtype, check_type\nfrom ..param_attr import ParamAttr\nfrom ..initializer import NumpyArrayInitializer, Constant\nfrom .. import core\n\n__all__ = [\n 'center_loss',\n 'bpr_loss',\n 'cross_entropy',\n 'square_error_cost',\n 'edit_distance',\n 'warpctc',\n 'nce',\n 'hsigmoid',\n 'sampled_softmax_with_cross_entropy',\n 'softmax_with_cross_entropy',\n 'rank_loss',\n 'margin_rank_loss',\n 'sigmoid_cross_entropy_with_logits',\n 'teacher_student_sigmoid_loss',\n 'huber_loss',\n 'kldiv_loss',\n 'npair_loss',\n 'mse_loss',\n]\n\nkIgnoreIndex = -100\n\n\ndef center_loss(input,\n label,\n num_classes,\n alpha,\n param_attr,\n update_center=True):\n \"\"\"\n :api_attr: Static Graph\n\t:alias_main: paddle.nn.functional.center_loss\n\t:alias: paddle.nn.functional.center_loss,paddle.nn.functional.loss.center_loss\n\t:old_api: paddle.fluid.layers.center_loss\n\n **Center loss Cost layer**\n \n This OP accepts input (deep features,the output of the last hidden layer)\n and target label and return the center loss cost. The average of the \n distances of each sample in the mini-batch from the center of the \n corresponding category is calculated as the center loss.\n \n For deep features, :math:`X`, and target labels, :math:`Y`, the equation is:\n \n .. math::\n\n Out = \\\\frac{1}{2}(X - Y)^2\n\n Args:\n input (Variable): a 2-D tensor with shape[N x M]. Its dtype should be float32 or float64.\n label (Variable): the groud truth which is a 2-D tensor\n with shape[N x 1],where N is the batch size. Its dtype should be int32.\n num_classes (int): the number of classification categories.\n alpha (float|Variable): learning rate of centers.\n param_attr (ParamAttr): Attribute initializer of centers. \n update_center (bool): whether to update value of center.\n\n Returns:\n Variable: 2-D tensor with shape [N * 1] \n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid \n\n input = fluid.data(name='x',shape=[20,30],dtype='float32')\n label = fluid.data(name='y',shape=[20,1],dtype='int64')\n num_classes = 1000\n alpha = 0.01\n param_attr = fluid.initializer.Xavier(uniform=False)\n center_loss=fluid.layers.center_loss(input=input,\n label=label,\n num_classes=1000,\n alpha=alpha,\n param_attr=fluid.initializer.Xavier(uniform=False),\n update_center=True)\n \"\"\"\n helper = LayerHelper('center_loss', **locals())\n dtype = helper.input_dtype()\n check_variable_and_dtype(input, 'input', ['float32', 'float64'],\n 'center_loss')\n check_variable_and_dtype(label, 'label', ['int32', 'int64'], 'center_loss')\n\n centers_shape = [num_classes, input.shape[1]]\n centers_param = helper.create_parameter(\n attr=param_attr, shape=centers_shape, dtype=dtype)\n centers_param.stop_gradient = True\n\n if isinstance(alpha, Variable):\n alpha_param = alpha\n check_variable_and_dtype(alpha, 'alpha', ['float32', 'float64'],\n 'center_loss')\n else:\n assert isinstance(alpha, float)\n alpha_param = helper.create_variable(\n name=\"centerloss_alpha\",\n shape=[1],\n dtype=\"float32\",\n type=core.VarDesc.VarType.LOD_TENSOR,\n persistable=True,\n stop_gradient=True,\n initializer=Constant(alpha))\n\n centersdiff = helper.create_variable_for_type_inference(dtype=input.dtype)\n loss = helper.create_variable_for_type_inference(dtype=input.dtype)\n helper.append_op(\n type='center_loss',\n inputs={\n 'X': [input],\n 'Label': [label],\n 'Centers': [centers_param],\n 'CenterUpdateRate': [alpha_param]\n },\n outputs={\n 'SampleCenterDiff': [centersdiff],\n 'Loss': [loss],\n 'CentersOut': [centers_param]\n },\n attrs={'cluster_num': num_classes,\n 'need_update': update_center})\n return loss\n\n\ndef bpr_loss(input, label, name=None):\n \"\"\"\n :alias_main: paddle.nn.functional.bpr_loss\n\t:alias: paddle.nn.functional.bpr_loss,paddle.nn.functional.loss.bpr_loss\n\t:old_api: paddle.fluid.layers.bpr_loss\n\n **Bayesian Personalized Ranking Loss Operator**\n\n This operator belongs to pairwise ranking loss. Label is the desired item.\n The loss at a given point in one session is defined as:\n\n .. math::\n Y[i] = 1/(N[i] - 1) * \\sum_j{\\log(\\sigma(X[i, Label[i]]-X[i, j]))}\n\n Learn more details by reading paper <session-based recommendations with recurrent\n neural networks>.\n\n Args:\n input (Variable|list): a 2-D tensor with shape [N x D], where N is the\n batch size and D is the number of positive classes and negative classes\n This input is not probability but logits.\n label (Variable|list): the ground truth which is a 2-D tensor. `label`\n is a tensor<int64> with shape [N x 1].\n name (str|None): A name for this layer(optional). If set None, the\n layer will be named automatically. Default: None.\n Returns:\n A 2-D tensor with shape [N x 1], the bpr loss.\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n neg_size = 10\n label = fluid.data(\n name=\"label\", shape=[3, 1], dtype=\"int64\")\n predict = fluid.data(\n name=\"predict\", shape=[3, neg_size + 1], dtype=\"float32\")\n cost = fluid.layers.bpr_loss(input=predict, label=label)\n \"\"\"\n helper = LayerHelper('bpr_loss', **locals())\n out = helper.create_variable_for_type_inference(dtype=input.dtype)\n check_variable_and_dtype(input, 'input', ['float16', 'float32', 'float64'],\n 'bpr_loss')\n helper.append_op(\n type='bpr_loss',\n inputs={'X': [input],\n 'Label': [label]},\n outputs={'Y': [out]})\n return out\n\n\ndef cross_entropy(input, label, soft_label=False, ignore_index=kIgnoreIndex):\n \"\"\"\n :alias_main: paddle.nn.functional.cross_entropy\n\t:alias: paddle.nn.functional.cross_entropy,paddle.nn.functional.loss.cross_entropy\n\t:old_api: paddle.fluid.layers.cross_entropy\n\n This operator computes the cross entropy between input and label. It\n supports both hard-label and and soft-label cross entropy computation.\n\n 1. Hard-label cross entropy: if soft_label=False, :math:`label[i_1, i_2, ..., i_k]`\n is the hard label of each sample.\n\n .. math::\n\n output[i_1, i_2, ..., i_k]=-log(input[i_1, i_2, ..., i_k, j]), label[i_1, i_2, ..., i_k] = j, j != ignore\\_index\n\n 2. Soft-label cross entropy: if soft_label=True, :math:`label[i_1, i_2, ..., i_k, j]`\n is the soft label of each sample corresponding to the j-th class.\n\n .. math::\n\n output[i_1, i_2, ..., i_k]= -\\sum_{j}label[i_1,i_2,...,i_k,j]*log(input[i_1, i_2, ..., i_k,j])\n\n Args:\n input (Variable): a multidimensional Tensor with shape\n :math:`[N_1, N_2, ..., N_k, D]`, where the last dimension D is\n the class number. The data type should be float32 or float64.\n label (Variable): label value corresponding to input. If\n soft_label=False, the dimension of label should be :math:`[N_1, N_2, ..., N_k]`\n or :math:`[N_1, N_2, ..., N_k, 1]` , and its data type should be int64,\n and the value must be inside [0, D). If soft_label=True, the shape,\n data type of label should be the same with input, and the sum of\n soft label value of each sample should be 1.\n soft_label (bool): indicate whether label is soft. Default False, meaning that\n the label is hard. If soft_label=True, the label is soft.\n ignore_index (int): specify an ignorable label value. The ignored label would be\n omitted when computing. If it is a negative integer, no label would\n be ignored. Only valid when soft_label=False. Default -100.\n\n Returns:\n A Variable holding Tensor representing the cross entropy, whose data type is the same with input.\n If soft_label=False, the shape of output is the same with label.\n If soft_label=True, the shape of output is :math:`[N_1, N_2, ..., N_k, 1]` .\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n class_num = 7\n x = fluid.data(name='x', shape=[None, 3, 10], dtype='float32')\n label = fluid.data(name='label', shape=[None, 1], dtype='int64')\n predict = fluid.layers.fc(input=x, size=class_num, act='softmax')\n cost = fluid.layers.cross_entropy(input=predict, label=label)\n \"\"\"\n if not soft_label:\n return cross_entropy2(input, label, ignore_index)\n\n if in_dygraph_mode():\n return core.ops.cross_entropy(input, label, \"soft_label\", soft_label,\n \"ignore_index\", ignore_index)\n\n inputs = {'X': [input], 'Label': [label]}\n attrs = {\"soft_label\": soft_label, \"ignore_index\": ignore_index}\n\n check_variable_and_dtype(input, 'input', ['float16', 'float32', 'float64'],\n 'cross_entropy')\n helper = LayerHelper('cross_entropy', **locals())\n out = helper.create_variable_for_type_inference(dtype=input.dtype)\n helper.append_op(\n type='cross_entropy', inputs=inputs, outputs={'Y': [out]}, attrs=attrs)\n return out\n\n\ndef cross_entropy2(input, label, ignore_index=kIgnoreIndex):\n if in_dygraph_mode():\n loss, _, _ = core.ops.cross_entropy2(input, label, 'ignore_index',\n ignore_index)\n return loss\n\n inputs = {'X': [input], 'Label': [label]}\n attrs = {'ignore_index': ignore_index}\n check_variable_and_dtype(input, 'input', ['float16', 'float32', 'float64'],\n 'cross_entropy2')\n helper = LayerHelper('cross_entropy2', **locals())\n out = helper.create_variable_for_type_inference(dtype=input.dtype)\n xshape = helper.create_variable_for_type_inference(dtype=input.dtype)\n match_x = helper.create_variable_for_type_inference(dtype=input.dtype)\n helper.append_op(\n type='cross_entropy2',\n inputs=inputs,\n outputs={'Y': [out],\n 'MatchX': [match_x],\n 'XShape': [xshape]},\n attrs=attrs)\n return out\n\n\ndef square_error_cost(input, label):\n \"\"\"\n :alias_main: paddle.nn.functional.square_error_cost\n\t:alias: paddle.nn.functional.square_error_cost,paddle.nn.functional.loss.square_error_cost\n\t:old_api: paddle.fluid.layers.square_error_cost\n\n This op accepts input predictions and target label and returns the\n squared error cost.\n\n For predictions label, and target label, the equation is:\n\n .. math::\n\n Out = (input - label)^2\n\n Parameters:\n input (Variable): Input tensor, the data type should be float32.\n label (Variable): Label tensor, the data type should be float32.\n\n Returns:\n The tensor variable storing the element-wise squared error \\\n difference between input and label.\n\n Return type: Variable.\n\n Examples:\n\n .. code-block:: python\n\n\t # declarative mode\n\t import paddle.fluid as fluid\n\t import numpy as np\n\t input = fluid.data(name=\"input\", shape=[1])\n\t label = fluid.data(name=\"label\", shape=[1])\n\t output = fluid.layers.square_error_cost(input,label)\n\t place = fluid.CPUPlace()\n\t exe = fluid.Executor(place)\n\t exe.run(fluid.default_startup_program())\n \n\t input_data = np.array([1.5]).astype(\"float32\")\n\t label_data = np.array([1.7]).astype(\"float32\")\n\t output_data = exe.run(fluid.default_main_program(),\n feed={\"input\":input_data, \"label\":label_data},\n fetch_list=[output],\n return_numpy=True)\n \n\t print(output_data)\n\t # [array([0.04000002], dtype=float32)]\n\t \n\t # imperative mode\n\t import paddle.fluid.dygraph as dg\n\n\t with dg.guard(place) as g:\n \t\tinput = dg.to_variable(input_data)\n \t\tlabel = dg.to_variable(label_data)\n \t\toutput = fluid.layers.square_error_cost(input, label)\n \t\tprint(output.numpy())\n\t \n\t # [0.04000002]\n \"\"\"\n check_variable_and_dtype(input, \"input\", ['float32', 'float64'],\n 'square_error_cost')\n check_variable_and_dtype(label, \"label\", ['float32', 'float64'],\n 'square_error_cost')\n helper = LayerHelper('square_error_cost', **locals())\n minus_out = helper.create_variable_for_type_inference(dtype=input.dtype)\n helper.append_op(\n type='elementwise_sub',\n inputs={'X': [input],\n 'Y': [label]},\n outputs={'Out': [minus_out]})\n\n square_out = helper.create_variable_for_type_inference(dtype=input.dtype)\n helper.append_op(\n type='square', inputs={'X': [minus_out]},\n outputs={'Out': [square_out]})\n return square_out\n\n\ndef edit_distance(input,\n label,\n normalized=True,\n ignored_tokens=None,\n input_length=None,\n label_length=None):\n \"\"\"\n This op computes the edit distances, also called Levenshtein distance, between a batch of\n hypothesis strings and their references. It measures how dissimilar two strings are by counting\n the minimum number of operations to transform one string into another.\n The operations include insertion, deletion, and substitution.\n\n For example, given hypothesis string A = \"kitten\" and reference\n B = \"sitting\", A will be transformed into B\n at least after two substitutions and one insertion:\n\n \"kitten\" -> \"sitten\" -> \"sittin\" -> \"sitting\"\n\n So the edit distance between A and B is 3.\n\n The input is a LoDTensor or Tensor.\n If it is a LoDTensor, The separation is specified by the LoD information.\n If it is a Tensor, The input_length and label_length should be supported.\n\n The `batch_size` of labels should be same as `input`.\n\n The output include the edit distance value between every pair of input and related label, and the number of sequence.\n If Attr(normalized) is true,\n the edit distance value will be divided by the length of label.\n\n Parameters:\n input(Variable): The input variable which is a tensor or LoDTensor, its rank should be equal to 2 and its data type should be int64.\n label(Variable): The label variable which is a tensor or LoDTensor, its rank should be equal to 2 and its data type should be int64.\n normalized(bool, default True): Indicated whether to normalize the edit distance.\n ignored_tokens(list<int>, default None): Tokens that will be removed before\n calculating edit distance.\n input_length(Variable): The length for each sequence in `input` if it's of Tensor type, it should have shape `(batch_size, )` and its data type should be int64.\n label_length(Variable): The length for each sequence in `label` if it's of Tensor type, it should have shape `(batch_size, )` and its data type should be int64.\n NOTE: To be avoid unexpected result, the value of every elements in input_length and label_length should be equal to the value of the second dimension of input and label. For example, The input: [[1,2,3,4],[5,6,7,8],[9,10,11,12]], the shape of input is [3,4] and the input_length should be [4,4,4]\n NOTE: This Api is different from fluid.metrics.EditDistance\n\n Returns:\n\tTuple:\n\n distance(Variable): edit distance result, its data type is float32, and its shape is (batch_size, 1).\n sequence_num(Variable): sequence number, its data type is float32, and its shape is (1,).\n\n Examples:\n .. code-block:: python\n \n import paddle.fluid as fluid\n import numpy as np\n\n # using LoDTensor\n x_lod = fluid.data(name='x_lod', shape=[None,1], dtype='int64', lod_level=1)\n y_lod = fluid.data(name='y_lod', shape=[None,1], dtype='int64', lod_level=1)\n distance_lod, seq_num_lod = fluid.layers.edit_distance(input=x_lod, label=y_lod)\n\n # using Tensor\n input_data = np.array([[1,2,3],[4,5,6],[4,4,4],[1,1,1]]).astype('int64')\n label_data = np.array([[1,3,4,1],[4,5,8,1],[7,7,7,1],[1,1,1,1]]).astype('int64')\n input_len = np.array([3,3,3,3]).astype('int64')\n label_len = np.array([4,4,4,4]).astype('int64')\n\n input_t = fluid.data(name='input', shape=[None,3], dtype='int64')\n label_t = fluid.data(name='label', shape=[None,4], dtype='int64')\n input_len_t = fluid.data(name='input_length', shape=[None], dtype='int64')\n label_len_t = fluid.data(name='label_length', shape=[None], dtype='int64')\n\n distance, sequence_num = fluid.layers.edit_distance(input=input_t, label=label_t, input_length=input_len_t, label_length=label_len_t,normalized=False)\n\n # print(input_data.shape, label_data.shape)\n # ((4,3), (4,4))\n\n place = fluid.CPUPlace()\n exe = fluid.Executor(place)\n exe.run(fluid.default_startup_program())\n dis, seq_num = exe.run(fluid.default_main_program(),\n feed={\"input\":input_data,\n \"label\":label_data,\n \"input_length\": input_len,\n \"label_length\": label_len},\n fetch_list=[distance,sequence_num])\n # print(dis)\n # [[3.]\n # [2.]\n # [4.]\n # [1.]]\n # if set normalized to True\n # [[0.75]\n # [0.5 ]\n # [1. ]\n # [0.25]\n #\n # print(seq_num)\n # [4]\n\n \"\"\"\n check_variable_and_dtype(input, 'input', ['int64'], 'edit_distance')\n check_variable_and_dtype(label, 'label', ['int64'], 'edit_distance')\n helper = LayerHelper(\"edit_distance\", **locals())\n\n # remove some tokens from input and labels\n if ignored_tokens is not None and len(ignored_tokens) > 0:\n erased_input = helper.create_variable_for_type_inference(dtype=\"int64\")\n erased_label = helper.create_variable_for_type_inference(dtype=\"int64\")\n\n helper.append_op(\n type=\"sequence_erase\",\n inputs={\"X\": [input]},\n outputs={\"Out\": [erased_input]},\n attrs={\"tokens\": ignored_tokens})\n input = erased_input\n\n helper.append_op(\n type=\"sequence_erase\",\n inputs={\"X\": [label]},\n outputs={\"Out\": [erased_label]},\n attrs={\"tokens\": ignored_tokens})\n label = erased_label\n\n this_inputs = {\"Hyps\": [input], \"Refs\": [label]}\n if input_length is not None and label_length is not None:\n this_inputs['HypsLength'] = [input_length]\n this_inputs['RefsLength'] = [label_length]\n\n # edit distance op\n edit_distance_out = helper.create_variable_for_type_inference(dtype=\"int64\")\n sequence_num = helper.create_variable_for_type_inference(dtype=\"int64\")\n helper.append_op(\n type=\"edit_distance\",\n inputs=this_inputs,\n outputs={\"Out\": [edit_distance_out],\n \"SequenceNum\": [sequence_num]},\n attrs={\"normalized\": normalized})\n\n return edit_distance_out, sequence_num\n\n\ndef warpctc(input,\n label,\n blank=0,\n norm_by_times=False,\n input_length=None,\n label_length=None):\n \"\"\"\n An operator integrating the open source Warp-CTC library\n (https://github.com/baidu-research/warp-ctc)\n to compute Connectionist Temporal Classification (CTC) loss.\n It can be aliased as softmax with CTC, since a native softmax activation is\n interated to the Warp-CTC library to normalize values for each row of the\n input tensor.\n\n Args:\n input (Variable): The unscaled probabilities of variable-length sequences,\n which is a 2-D Tensor with LoD information, or a 3-D Tensor without Lod\n information. When it is a 2-D LodTensor, its shape is \n `[Lp, num_classes + 1]`, where `Lp` is the sum of all input\n sequences' length and `num_classes` is the true number of classes.\n (not including the blank label). When it is a 3-D Tensor, its shape \n is `[max_logit_length, batch_size, num_classes + 1]`,\n where `max_logit_length` is the longest length of\n input logit sequence. The data type should be float32 or float64.\n label (Variable): The ground truth of variable-length sequence,\n which must be a 2-D Tensor with LoD information or a 3-D Tensor without\n LoD information, needs to be consistent with the coressponding input. \n When it is a 2-D LoDTensor, its shape is `[Lg, 1]`, where `Lg` is the sum \n of all labels' length. When it is a 3-D Tensor, its shape is \n `[batch_size, max_label_length]`, where `max_label_length` is the longest\n length of label sequence. Data type must be int32.\n blank (int, default 0): The blank label index of Connectionist\n Temporal Classification (CTC) loss, which is in the\n half-opened interval `[0, num_classes + 1)`. The data type must be int32. \n norm_by_times(bool, default false): Whether to normalize the gradients\n by the number of time-step, which is also the sequence's length.\n There is no need to normalize the gradients if warpctc layer was\n followed by a mean_op.\n input_length(Variable): The length for each input sequence if it is \n of Tensor type, it should have shape `[batch_size]` and dtype int64.\n label_length(Variable): The length for each label sequence if it is\n of Tensor type, it should have shape `[batch_size]` and dtype int64.\n\n Returns:\n Variable: The Connectionist Temporal Classification (CTC) loss,\n which is a 2-D Tensor with the shape `[batch_size, 1]`.\n The date type is the same as input.\n\n Examples:\n\n .. code-block:: python\n\n # using LoDTensor\n import paddle\n import paddle.fluid as fluid\n import numpy as np\n\n # lengths of logit sequences\n seq_lens = [2,6]\n # lengths of label sequences\n label_lens = [2,3]\n # class num\n class_num = 5\n\n paddle.enable_static()\n logits = fluid.data(name='logits',shape=[None, class_num+1],\n dtype='float32',lod_level=1)\n label = fluid.data(name='label', shape=[None, 1],\n dtype='int32', lod_level=1)\n cost = fluid.layers.warpctc(input=logits, label=label)\n place = fluid.CPUPlace()\n x = fluid.create_lod_tensor(\n np.random.rand(np.sum(seq_lens), class_num+1).astype(\"float32\"), \n [seq_lens], place)\n y = fluid.create_lod_tensor(\n np.random.randint(0, class_num, [np.sum(label_lens), 1]).astype(\"int32\"), \n [label_lens], place)\n exe = fluid.Executor(place)\n output= exe.run(fluid.default_main_program(),\n feed={\"logits\": x,\"label\": y},\n fetch_list=[cost.name])\n print(output)\n\n .. code-block:: python\n\n # using Tensor\n import paddle\n import paddle.fluid as fluid\n import numpy as np\n\n # length of the longest logit sequence\n max_seq_length = 5\n #length of the longest label sequence\n max_label_length = 3\n # number of logit sequences\n batch_size = 16\n # class num\n class_num = 5\n paddle.enable_static()\n logits = fluid.data(name='logits',\n shape=[max_seq_length, batch_size, class_num+1],\n dtype='float32')\n logits_length = fluid.data(name='logits_length', shape=[None],\n dtype='int64')\n label = fluid.data(name='label', shape=[batch_size, max_label_length],\n dtype='int32')\n label_length = fluid.data(name='labels_length', shape=[None],\n dtype='int64')\n cost = fluid.layers.warpctc(input=logits, label=label,\n input_length=logits_length,\n label_length=label_length)\n place = fluid.CPUPlace()\n x = np.random.rand(max_seq_length, batch_size, class_num+1).astype(\"float32\")\n y = np.random.randint(0, class_num, [batch_size, max_label_length]).astype(\"int32\")\n exe = fluid.Executor(place)\n output= exe.run(fluid.default_main_program(),\n feed={\"logits\": x,\n \"label\": y,\n \"logits_length\": np.array([max_seq_length]*batch_size).astype(\"int64\"),\n \"labels_length\": np.array([max_label_length]*batch_size).astype(\"int64\")},\n fetch_list=[cost.name])\n print(output)\n \"\"\"\n if in_dygraph_mode():\n if input_length is None or label_length is None:\n raise ValueError(\n \"input_length and label_length must not be None in dygraph mode!\"\n )\n grad, loss_out = core.ops.warpctc(\n input,\n label,\n input_length,\n label_length,\n 'blank',\n blank,\n 'norm_by_times',\n norm_by_times, )\n return loss_out\n helper = LayerHelper('warpctc', **locals())\n check_variable_and_dtype(input, 'input', ['float32', 'float64'], \"warpctc\")\n check_variable_and_dtype(label, 'label', ['int32'], \"warpctc\")\n this_inputs = {'Logits': [input], 'Label': [label]}\n if input_length is not None and label_length is not None:\n check_variable_and_dtype(input_length, 'LogitsLength', ['int64'],\n \"warpctc\")\n check_variable_and_dtype(label_length, 'LabelLength', ['int64'],\n \"warpctc\")\n this_inputs['LogitsLength'] = [input_length]\n this_inputs['LabelLength'] = [label_length]\n\n loss_out = helper.create_variable_for_type_inference(dtype=input.dtype)\n grad_out = helper.create_variable_for_type_inference(dtype=input.dtype)\n\n helper.append_op(\n type='warpctc',\n inputs=this_inputs,\n outputs={'WarpCTCGrad': [grad_out],\n 'Loss': [loss_out]},\n attrs={\n 'blank': blank,\n 'norm_by_times': norm_by_times,\n })\n return loss_out\n\n\n# FIXME(wuyi): let docstring_checker.py understand @autodoc.\n# For now, the comments in c++ use types like Tensor, but in python side\n# the type is often \"Variable\", and arguments may vary.\n@templatedoc(op_type=\"nce\")\ndef nce(input,\n label,\n num_total_classes,\n sample_weight=None,\n param_attr=None,\n bias_attr=None,\n num_neg_samples=None,\n name=None,\n sampler=\"uniform\",\n custom_dist=None,\n seed=0,\n is_sparse=False):\n \"\"\"\n :api_attr: Static Graph\n\n ${comment}\n\n Args:\n input (Variable): Input variable, 2-D tensor with shape [batch_size, dim], \n and data type is float32 or float64.\n label (Variable): Input label, 2-D tensor with shape [batch_size, num_true_class],\n and data type is int64.\n num_total_classes (int):${num_total_classes_comment}.\n sample_weight (Variable|None): A Variable of shape [batch_size, 1]\n storing a weight for each sample. The default weight for each\n sample is 1.0.\n param_attr (ParamAttr|None): To specify the weight parameter attribute. \n Default: None, which means the default weight parameter property is \n used. See usage for details in :ref:`api_fluid_ParamAttr` .\n bias_attr (ParamAttr|None): To specify the bias parameter attribute. \n Default: None, which means the default bias parameter property is \n used. See usage for details in :ref:`api_fluid_ParamAttr` .\n num_neg_samples (int): ${num_neg_samples_comment}.\n name(str|None): For detailed information, please refer to \n :ref:`api_guide_Name` . Usually name is no need to set and None by default.\n sampler (str, optional): The sampler used to sample class from negative classes.\n It can be 'uniform', 'log_uniform' or 'custom_dist'.\n default: 'uniform'.\n custom_dist (nd.array|None): A numpy ndarray with size=num_total_classes.\n It is used when sampler is set to 'custom_dist'.\n custom_dist[i] is the probability of i-th class to be sampled.\n default: None.\n seed (int, optional): The seed used in sampler. Default 0, means no random seed.\n is_sparse(bool, optional): The flag indicating whether to use sparse update, \n the weight@GRAD and bias@GRAD will be changed to SelectedRows. Default False.\n\n Returns:\n Variable: The output nce loss.\n\n Examples:\n .. code-block:: python\n\n\n import paddle.fluid as fluid\n import numpy as np\n\n window_size = 5\n words = []\n for i in range(window_size):\n words.append(fluid.data(\n name='word_{0}'.format(i), shape=[-1, 1], dtype='int64'))\n\n dict_size = 10000\n label_word = int(window_size / 2) + 1\n\n embs = []\n for i in range(window_size):\n if i == label_word:\n continue\n\n emb = fluid.layers.embedding(input=words[i], size=[dict_size, 32],\n param_attr='embed', is_sparse=True)\n embs.append(emb)\n\n embs = fluid.layers.concat(input=embs, axis=1)\n loss = fluid.layers.nce(input=embs, label=words[label_word],\n num_total_classes=dict_size, param_attr='nce.w_0',\n bias_attr='nce.b_0')\n\n #or use custom distribution\n dist = np.array([0.05,0.5,0.1,0.3,0.05])\n loss = fluid.layers.nce(input=embs, label=words[label_word],\n num_total_classes=5, param_attr='nce.w_1',\n bias_attr='nce.b_1',\n num_neg_samples=3,\n sampler=\"custom_dist\",\n custom_dist=dist)\n \"\"\"\n helper = LayerHelper('nce', **locals())\n check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'nce')\n check_variable_and_dtype(label, 'label', ['int64'], 'nce')\n\n dim = input.shape[1]\n num_true_class = label.shape[1]\n w = helper.create_parameter(\n attr=helper.param_attr,\n shape=[num_total_classes, dim],\n is_bias=False,\n dtype=input.dtype)\n inputs = {}\n if helper.bias_attr:\n b = helper.create_parameter(\n attr=helper.bias_attr,\n shape=[num_total_classes, 1],\n is_bias=True,\n dtype=input.dtype)\n inputs['Bias'] = b\n cost = helper.create_variable_for_type_inference(dtype=input.dtype)\n sample_logits = helper.create_variable_for_type_inference(dtype=input.dtype)\n sample_labels = helper.create_variable_for_type_inference(dtype=label.dtype)\n\n inputs['Input'] = input\n inputs['Label'] = label\n inputs['Weight'] = w\n inputs['SampleWeight'] = sample_weight if sample_weight is not None else []\n\n if sampler == \"uniform\":\n sampler = 0\n elif sampler == \"log_uniform\":\n sampler = 1\n elif sampler == \"custom_dist\":\n assert custom_dist is not None\n\n custom_dist_len = num_total_classes\n alias_probs_ = [0] * custom_dist_len\n alias_ = [0] * custom_dist_len\n bigs = []\n littles = []\n for i in range(custom_dist_len):\n normal_prob = custom_dist[i] * custom_dist_len\n if normal_prob - 1.0 > 0:\n bigs.append((i, normal_prob))\n elif 1.0 - normal_prob > 0:\n littles.append((i, normal_prob))\n else:\n alias_probs_[i] = normal_prob\n alias_[i] = -1\n\n while len(bigs) and len(littles):\n big = bigs.pop(0)\n little = littles.pop(0)\n\n big_idx = big[0]\n big_prob = big[1]\n\n alias_probs_[little[0]] = little[1]\n alias_[little[0]] = big_idx\n big_left = big[1] + little[1] - 1\n if big_left - 1.0 > 0:\n bigs.append((big_idx, big_left))\n elif 1.0 - big_left > 0:\n littles.append((big_idx, big_left))\n else:\n alias_probs_[big_idx] = big_left\n alias_[big_idx] = -1\n\n if len(bigs):\n big = bigs.pop(0)\n alias_probs_[big[0]] = 1.0\n alias_[big[0]] = -1\n if len(littles):\n little = littles.pop(0)\n alias_probs_[little[0]] = 1.0\n alias_[little[0]] = -1\n\n def _init_by_numpy_array(numpy_array):\n ret = helper.create_parameter(\n attr=ParamAttr(),\n shape=numpy_array.shape,\n dtype=numpy_array.dtype,\n default_initializer=NumpyArrayInitializer(numpy_array))\n ret.stop_gradient = True\n return ret\n\n inputs['CustomDistProbs'] = _init_by_numpy_array(\n np.array(custom_dist).astype('float32'))\n inputs['CustomDistAlias'] = _init_by_numpy_array(\n np.array(alias_).astype('int32'))\n inputs['CustomDistAliasProbs'] = _init_by_numpy_array(\n np.array(alias_probs_).astype('float32'))\n sampler = 2\n else:\n raise Exception(\"Unsupported sampler type.\")\n\n if num_neg_samples is None:\n num_neg_samples = 10\n else:\n num_neg_samples = int(num_neg_samples)\n\n remote_prefetch = is_sparse\n print(\n \"With sparse mode, if your models has only small parameter prefetch may cause speed down\"\n )\n\n attrs = {\n 'num_total_classes': int(num_total_classes),\n 'num_neg_samples': num_neg_samples,\n 'seed': seed,\n 'sampler': sampler,\n 'is_sparse': is_sparse,\n 'remote_prefetch': remote_prefetch\n }\n\n helper.append_op(\n type='nce',\n inputs=inputs,\n outputs={\n 'Cost': cost,\n 'SampleLogits': sample_logits,\n 'SampleLabels': sample_labels\n },\n attrs=attrs)\n return cost / (num_neg_samples + 1)\n\n\ndef hsigmoid(input,\n label,\n num_classes,\n param_attr=None,\n bias_attr=None,\n name=None,\n path_table=None,\n path_code=None,\n is_custom=False,\n is_sparse=False):\n \"\"\"\n :api_attr: Static Graph\n \n The hierarchical sigmoid organizes the classes into a complete binary tree to reduce the computational complexity\n and speed up the model training, especially the training of language model.\n Each leaf node of the complete binary tree represents a class(word) and each non-leaf node acts as a binary classifier.\n For each class(word), there's a unique path from root to itself, hsigmoid calculate the cost for each non-leaf node on\n the path, and sum them to get a total cost.\n Comparing to softmax, the OP can reduce the computational complexity from :math:`O(N)` to :math:`O(logN)`, where :math:`N`\n represents the number of classes or the size of word dict.\n\n The OP supports default tree and custom tree. For the default tree, you can refer to `Hierarchical Probabilistic Neural\n Network Language Model <http://www.iro.umontreal.ca/~lisa/pointeurs/hierarchical-nnlm-aistats05.pdf>`. For the custom\n tree, you need to set :attr:`is_custom` to True, and do the following steps (take the language model as an example):\n\n 1. Using a custom word dict to build a binary tree, each leaf node should be an word in the word dict.\n 2. Creating a dict map word_id -> path that from the word to the root node, we call it path_table.\n 3. Creating a dict map word_id -> code of path that from the word to the root node, we call it path_code.\n Code means the label of each binary classifier, 1 indicate true, 0 indicate false.\n 4. Now, each word should has its path and code along the path, you can pass a batch of path and code related\n to the same batch of inputs.\n\n Parameters:\n input (Variable): A tensor with the shape [N, D], where N is the size of mini-batch,\n and D is the feature size. Its data type supports float32 and float64.\n label (Variable): A tensor contains the labels of training data. Its shape is [N, 1]\n and data type is int64.\n num_classes (int): The number of classes or the size of word dict, must be greater than 2.\n If the default tree is used (:attr:`is_custom` is set to False), :attr:`num_classes`\n should not be None. If the custom tree is used (:attr:`is_custom` is set to True),\n :attr:`num_classes` should be the number of non-leaf nodes, which indicates the num of\n classes using by the binary classifier.\n param_attr (ParamAttr, optional): The parameter attribute for the learnable parameters/weights\n of hsigmoid. If it is set to None or one attribute of ParamAttr, hsigmoid will create a\n ParamAttr as param_attr. If the Initializer of the param_attr is not set, the parameter is\n initialized with Xavier. Default: None.\n bias_attr (ParamAttr|bool, optional): The parameter attribute for the bias of hsigmoid. If it\n is set to False, no bias will be added. If it is set to None or one attribute of ParamAttr,\n hsigmoid will create a ParamAttr as bias_attr. If the Initializer of the bias_attr is not\n set, the bias is initialized zero. Default: None.\n name (str, optional): Normally there is no need for user to set this property. For more information,\n please refer to :ref:`api_guide_Name`. Default: None.\n path_table (Variable, optional): A tensor that stores each batch of samples' path from leaf to root\n node, its shape is [N, L] and data type is int64, where L is the length of path. For each sample i,\n path_table[i] is a np.array like structure and each element in this array is the indexes in parent\n nodes' weight matrix. Default: None.\n path_code (Variable, optional): A tensor that stores each batch of samples' code of path from leaf\n to root node, its shape is [N, L] and data type is int64, which is the same as :attr:`path_table`.\n Each code of path is consisted with the code of nodes from leaf to root node. Default: None.\n is_custom (bool, optional): Whether use custom binary tree. If it's True, :attr:`path_table`,\n :attr:`path_code` and :attr:`num_classes` should be set, otherwise :attr:`num_classes` should\n be set. Default: False.\n is_sparse (bool, optional): Whether use sparse updating instead of dense updating, if it's True, the\n gradient of W and input will be sparse. Default: False.\n\n Returns:\n Variable: A tensor with the cost of hierarchical sigmoid, its shape is [N, 1] and data type is the same as :attr:`input`.\n\n Examples:\n\n .. code-block:: python\n\n import paddle.fluid as fluid\n x = fluid.layers.fill_constant(shape=[4, 3], value=0.9, dtype='float32')\n # x = [[0.9, 0.9, 0.9], [0.9, 0.9, 0.9], [0.9, 0.9, 0.9], [0.9, 0.9, 0.9]]\n y = fluid.layers.fill_constant(\n shape=[4, 1], value=1, dtype='int64')\n # y = [[1], [1], [1], [1]]\n out = fluid.layers.hsigmoid(input=x, label=y, num_classes=2, param_attr=fluid.initializer.Constant(\n value=0.05), bias_attr=fluid.initializer.Constant(value=.0))\n # out = [[0.62792355], [0.62792355], [0.62792355], [0.62792355]]\n \"\"\"\n check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'hsigmoid')\n check_variable_and_dtype(label, 'label', ['int64'], 'hsigmoid')\n\n helper = LayerHelper('hierarchical_sigmoid', **locals())\n dtype = helper.input_dtype()\n out = helper.create_variable_for_type_inference(dtype)\n pre_out = helper.create_variable_for_type_inference(dtype)\n dim = input.shape[1]\n if ((num_classes is None) or (num_classes < 2)) and (not is_custom):\n raise ValueError(\n \"num_classes must not be less than 2 with default tree\")\n\n if (not is_custom) and (is_sparse):\n print(\"Sparse mode should not be used without custom tree\")\n is_sparse = False\n\n if (not is_custom) and ((path_table is not None) or\n (path_code is not None)):\n raise ValueError(\n \"only num_classes should be passed without custom tree\")\n\n if (is_custom) and (path_code is None):\n raise ValueError(\"path_code should not be None with custom tree\")\n elif (is_custom) and (path_table is None):\n raise ValueError(\"path_table should not be None with custom tree\")\n elif (is_custom) and (num_classes is None):\n raise ValueError(\"num_classes should not be None with custom tree\")\n else:\n pass\n\n weights = None\n remote_prefetch = is_sparse\n print(\n \"With sparse mode, if your models has only small parameter prefetch may cause speed down\"\n )\n if not is_custom:\n weights = helper.create_parameter(\n attr=helper.param_attr,\n shape=[num_classes - 1, dim],\n is_bias=False,\n dtype=input.dtype)\n else:\n weights = helper.create_parameter(\n attr=helper.param_attr,\n shape=[num_classes, dim],\n is_bias=False,\n dtype=input.dtype)\n inputs = {\n \"X\": input,\n \"W\": weights,\n \"PathTable\": path_table,\n \"PathCode\": path_code,\n \"Label\": label\n }\n if helper.bias_attr:\n if not is_custom:\n bias = helper.create_parameter(\n attr=helper.bias_attr,\n shape=[num_classes - 1, 1],\n is_bias=True,\n dtype=input.dtype)\n inputs['Bias'] = bias\n else:\n bias = helper.create_parameter(\n attr=helper.bias_attr,\n shape=[num_classes, 1],\n is_bias=True,\n dtype=input.dtype)\n inputs['Bias'] = bias\n helper.append_op(\n type=\"hierarchical_sigmoid\",\n inputs=inputs,\n outputs={\"Out\": out,\n \"PreOut\": pre_out,\n \"W_Out\": weights},\n attrs={\n \"num_classes\": num_classes,\n \"is_sparse\": is_sparse,\n \"remote_prefetch\": remote_prefetch\n })\n return out\n\n\ndef sampled_softmax_with_cross_entropy(logits,\n label,\n num_samples,\n num_true=1,\n remove_accidental_hits=True,\n use_customized_samples=False,\n customized_samples=None,\n customized_probabilities=None,\n seed=0):\n \"\"\"\n **Sampled Softmax With Cross Entropy Operator.**\n\n Cross entropy loss with sampled softmax is used as the output layer for \n larger output classes extensively. This operator samples a number of samples\n for all examples, and computes the softmax normalized values for each \n row of the sampled tensor, after which cross-entropy loss is computed. \n\n Because this operator performs a softmax on logits internally, it expects\n unscaled logits. This operator should not be used with the output of\n softmax operator since that would produce incorrect results.\n \n For examples with T true labels (T >= 1), we assume that each true label has\n a probability of 1/T. For each sample, S samples are generated using a\n log uniform distribution. True labels are concatenated with these samples to\n form T + S samples for each example. So, assume the shape of logits is\n [N x K], the shape for samples is [N x (T+S)]. For each sampled label, a \n probability is calculated, which corresponds to the Q(y|x) in \n [Jean et al., 2014](http://arxiv.org/abs/1412.2007).\n \n Logits are sampled according to the sampled labels. Then if \n remove_accidental_hits is True, if a sample[i, j] accidentally hits true \n labels, then the corresponding sampled_logits[i, j] is minus by 1e20 to \n make its softmax result close to zero. Then sampled logits are subtracted by\n logQ(y|x), these sampled logits and re-indexed labels are used to compute \n a softmax with cross entropy.\n\n Args:\n logits (Variable): The unscaled log probabilities, which is a 2-D tensor\n with shape [N x K]. N is the batch_size, and K is the class number.\n label (Variable): The ground truth which is a 2-D tensor. Label is a \n Tensor<int64> with shape [N x T], where T is the number of true \n labels per example. \n num_samples (int): The number for each example, num_samples should be \n less than the number of class.\n num_true(int): The number of target classes per training example.\n remove_accidental_hits (bool): A flag indicating whether to remove \n accidental hits when sampling. If True and if a sample[i, j] \n accidentally hits true labels, then the corresponding \n sampled_logits[i, j] is minus by 1e20 to make its softmax result \n close to zero. Default is True.\n use_customized_samples (bool): Whether to use custom samples and probabities to sample\n logits.\n customized_samples (Variable): User defined samples, which is a 2-D tensor\n with shape [N, T + S]. S is the num_samples, and T is the number of true \n labels per example. \n customized_probabilities (Variable): User defined probabilities of samples, \n a 2-D tensor which has the same shape with customized_samples.\n seed (int): The random seed for generating random number, which is used\n in the process of sampling. Default is 0.\n\n Returns:\n Variable: Return the cross entropy loss which is a 2-D tensor with shape\n [N x 1].\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n input = fluid.layers.data(name='data', shape=[256], dtype='float32')\n label = fluid.layers.data(name='label', shape=[1], dtype='int64')\n fc = fluid.layers.fc(input=input, size=100)\n out = fluid.layers.sampled_softmax_with_cross_entropy(\n logits=fc, label=label, num_samples=25)\n \"\"\"\n helper = LayerHelper('sample_logits', **locals())\n samples = customized_samples if use_customized_samples else helper.create_variable_for_type_inference(\n dtype='int64')\n probabilities = customized_probabilities if use_customized_samples else helper.create_variable_for_type_inference(\n dtype=logits.dtype)\n sampled_logits \\\n = helper.create_variable_for_type_inference(dtype=logits.dtype)\n sampled_label = helper.create_variable_for_type_inference(dtype='int64')\n sampled_softlabel = helper.create_variable_for_type_inference(\n dtype=logits.dtype)\n logits_dim = helper.create_variable_for_type_inference(dtype=logits.dtype)\n labels_dim = helper.create_variable_for_type_inference(dtype=label.type)\n\n helper.append_op(\n type='sample_logits',\n inputs={\n 'Logits': logits,\n 'Labels': label,\n 'CustomizedSamples': customized_samples,\n 'CustomizedProbabilities': customized_probabilities\n },\n outputs={\n 'Samples': samples,\n 'Probabilities': probabilities,\n 'SampledLabels': sampled_label,\n 'SampledLogits': sampled_logits,\n 'LogitsDim': logits_dim,\n 'LabelsDim': labels_dim\n },\n attrs={\n 'use_customized_samples': use_customized_samples,\n 'uniq': True,\n 'remove_accidental_hits': remove_accidental_hits,\n 'num_samples': num_samples,\n 'seed': seed\n })\n loss = helper.create_variable_for_type_inference(dtype=logits.dtype)\n softmax = helper.create_variable_for_type_inference(dtype=logits.dtype)\n helper.append_op(\n type='one_hot',\n inputs={'X': sampled_label},\n attrs={'depth': num_samples + 1},\n outputs={'Out': sampled_softlabel})\n\n helper.append_op(\n type='softmax_with_cross_entropy',\n inputs={'Logits': sampled_logits,\n 'Label': sampled_softlabel},\n outputs={'Softmax': softmax,\n 'Loss': loss},\n attrs={\n 'soft_label': True,\n 'ignore_index': False,\n 'numeric_stable_mode': False\n })\n return loss / num_true\n\n\ndef softmax_with_cross_entropy(logits,\n label,\n soft_label=False,\n ignore_index=kIgnoreIndex,\n numeric_stable_mode=True,\n return_softmax=False,\n axis=-1):\n \"\"\"\n :alias_main: paddle.nn.functional.softmax_with_cross_entropy\n\t:alias: paddle.nn.functional.softmax_with_cross_entropy,paddle.nn.functional.loss.softmax_with_cross_entropy\n\t:old_api: paddle.fluid.layers.softmax_with_cross_entropy\n\n This operator implements the cross entropy loss function with softmax. This function \n combines the calculation of the softmax operation and the cross entropy loss function \n to provide a more numerically stable gradient.\n\n Because this operator performs a softmax on logits internally, it expects\n unscaled logits. This operator should not be used with the output of\n softmax operator since that would produce incorrect results.\n\n When the attribute :attr:`soft_label` is set :attr:`False`, this operators \n expects mutually exclusive hard labels, each sample in a batch is in exactly \n one class with a probability of 1.0. Each sample in the batch will have a \n single label.\n\n The equation is as follows:\n\n 1) Hard label (one-hot label, so every sample has exactly one class)\n\n .. math::\n\n loss_j = -\\\\text{logits}_{label_j} +\n \\\\log\\\\left(\\\\sum_{i=0}^{K}\\\\exp(\\\\text{logits}_i)\\\\right), j = 1,..., K\n\n 2) Soft label (each sample can have a distribution over all classes)\n\n .. math::\n\n loss_j = -\\\\sum_{i=0}^{K}\\\\text{label}_i\n \\\\left(\\\\text{logits}_i - \\\\log\\\\left(\\\\sum_{i=0}^{K}\n \\\\exp(\\\\text{logits}_i)\\\\right)\\\\right), j = 1,...,K\n\n 3) If :attr:`numeric_stable_mode` is :attr:`True`, softmax is calculated first by:\n\n .. math::\n\n max_j &= \\\\max_{i=0}^{K}{\\\\text{logits}_i}\n\n log\\\\_max\\\\_sum_j &= \\\\log\\\\sum_{i=0}^{K}\\\\exp(logits_i - max_j)\n\n softmax_j &= \\\\exp(logits_j - max_j - {log\\\\_max\\\\_sum}_j)\n\n and then cross entropy loss is calculated by softmax and label.\n\n Args:\n logits (Variable): A multi-dimension ``Tensor`` , and the data type is float32 or float64. The input tensor of unscaled log probabilities.\n label (Variable): The ground truth ``Tensor`` , data type is the same\n as the ``logits`` . If :attr:`soft_label` is set to :attr:`True`, \n Label is a ``Tensor`` in the same shape with :attr:`logits`. \n If :attr:`soft_label` is set to :attr:`True`, Label is a ``Tensor`` \n in the same shape with :attr:`logits` expect shape in dimension :attr:`axis` as 1.\n soft_label (bool, optional): A flag to indicate whether to interpretant the given\n labels as soft labels. Default False.\n ignore_index (int, optional): Specifies a target value that is ignored and does\n not contribute to the input gradient. Only valid\n if :attr:`soft_label` is set to :attr:`False`. \n Default: kIgnoreIndex(-100).\n numeric_stable_mode (bool, optional): A flag to indicate whether to use a more\n numerically stable algorithm. Only valid\n when :attr:`soft_label` is :attr:`False` \n and GPU is used. When :attr:`soft_label` \n is :attr:`True` or CPU is used, the \n algorithm is always numerically stable.\n Note that the speed may be slower when use\n stable algorithm. Default: True.\n return_softmax (bool, optional): A flag indicating whether to return the softmax\n along with the cross entropy loss. Default: False.\n axis (int, optional): The index of dimension to perform softmax calculations. It \n should be in range :math:`[-1, rank - 1]`, while :math:`rank`\n is the rank of input :attr:`logits`. Default: -1.\n\n Returns:\n ``Variable`` or Tuple of two ``Variable`` : Return the cross entropy loss if \\\n `return_softmax` is False, otherwise the tuple \\\n (loss, softmax), softmax is in the same shape \\\n with input logits and cross entropy loss is in \\\n the same shape with input logits except shape \\\n in dimension :attr:`axis` as 1.\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n data = fluid.data(name='data', shape=[-1, 128], dtype='float32')\n label = fluid.data(name='label', shape=[-1, 1], dtype='int64')\n fc = fluid.layers.fc(input=data, size=100)\n out = fluid.layers.softmax_with_cross_entropy(\n logits=fc, label=label)\n \"\"\"\n if in_dygraph_mode():\n softmax, loss = core.ops.softmax_with_cross_entropy(\n logits, label, 'soft_label', soft_label, 'ignore_index',\n ignore_index, 'numeric_stable_mode', numeric_stable_mode, 'axis',\n axis)\n if not return_softmax:\n return loss\n else:\n return loss, softmax\n\n attrs = {\n 'soft_label': soft_label,\n 'ignore_index': ignore_index,\n 'numeric_stable_mode': numeric_stable_mode,\n 'axis': axis\n }\n helper = LayerHelper('softmax_with_cross_entropy', **locals())\n softmax = helper.create_variable_for_type_inference(dtype=logits.dtype)\n loss = helper.create_variable_for_type_inference(dtype=logits.dtype)\n helper.append_op(\n type='softmax_with_cross_entropy',\n inputs={'Logits': logits,\n 'Label': label},\n outputs={'Softmax': softmax,\n 'Loss': loss},\n attrs=attrs)\n\n if return_softmax:\n return loss, softmax\n\n return loss\n\n\ndef rank_loss(label, left, right, name=None):\n \"\"\"\n :alias_main: paddle.nn.functional.rank_loss\n\t:alias: paddle.nn.functional.rank_loss,paddle.nn.functional.loss.rank_loss\n\t:old_api: paddle.fluid.layers.rank_loss\n\n This operator implements the sort loss layer in the RankNet model. RankNet is a pairwise ranking model \n with a training sample consisting of a pair of documents (A and B), The label (P) \n indicates whether A is ranked higher than B or not. Please refer to more details: \n `RankNet <http://icml.cc/2015/wp-content/uploads/2015/06/icml_ranking.pdf>`_\n\n Rank loss layer takes three inputs: left ( :math:`o_i` ), right ( :math:`o_j` ) and\n label ( :math:`P_{i,j}` ). The inputs respectively represent RankNet's output scores\n for documents A and B and the value of label P. Rank loss layer takes batch inputs \n with size batch_size (batch_size >= 1), P = {0, 1} or {0, 0.5, 1}, \n where 0.5 means that there is no information about the rank of the input pair.\n The following equation computes rank loss C_{i,j} from the inputs:\n\n .. math::\n C_{i,j} &= -\\\\tilde{P_{ij}} * o_{i,j} + \\log(1 + e^{o_{i,j}}) \\\\\\\\\n .. math::\n o_{i,j} &= o_i - o_j \\\\\\\\\n .. math::\n \\\\tilde{P_{i,j}} &= \\\\left \\{0, 0.5, 1 \\\\right \\} \\ or \\ \\\\left \\{0, 1 \\\\right \\}\n\n Parameters:\n label (Variable): 2-D ``Tensor`` with the shape of :math:`[batch,1]`, the data type is float32, batch indicates the size of the data. Indicats whether A ranked higher than B or not.\n left (Variable): 2-D ``Tensor`` with the shape of :math:`[batch,1]`, the data type is float32. RankNet's output score for doc A.\n right (Variable): 2-D ``Tensor`` with the shape of :math:`[batch,1]`, the data type is float32. RankNet's output score for doc B.\n name(str|None): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` .\n\n Returns:\n Variable: ``Tensor`` indicating the output value of the sort loss layer, the data type is float32, and the return value's shape is :math:`[batch,1]` .\n\n Raises:\n ValueError: Any of label, left, and right is not a ``Variable`` .\n\n Examples:\n\n .. code-block:: python\n\n import paddle.fluid as fluid\n label = fluid.data(name=\"label\", shape=[-1, 1], dtype=\"float32\")\n left = fluid.data(name=\"left\", shape=[-1, 1], dtype=\"float32\")\n right = fluid.data(name=\"right\", shape=[-1, 1], dtype=\"float32\")\n out = fluid.layers.rank_loss(label, left, right)\n\n \"\"\"\n helper = LayerHelper('rank_loss', **locals())\n check_variable_and_dtype(label, 'label', ['float32'], \"rank_loss\")\n check_variable_and_dtype(left, 'left', ['float32'], \"rank_loss\")\n check_variable_and_dtype(right, 'right', ['float32'], \"rank_loss\")\n\n out = helper.create_variable_for_type_inference(\"float32\")\n\n helper.append_op(\n type='rank_loss',\n inputs={\"Label\": label,\n \"Left\": left,\n \"Right\": right},\n outputs={'Out': out})\n return out\n\n\ndef margin_rank_loss(label, left, right, margin=0.1, name=None):\n \"\"\"\n Margin Ranking Loss Layer for ranking problem,\n which compares left score and right score passed in.\n The ranking loss can be defined as following equation:\n\n .. math::\n\n rank\\_loss = max(0, -label * (left - right) + margin)\n\n Args:\n label (Variable): Indicates whether the left is ranked higher than the right or not.\n Data type is float32.\n left (Variable): Ranking score for left. Data type float32.\n right (Variable): Ranking score for right. Data type float32.\n margin (float): Indicates the given margin.\n name(str|None): For detailed information, please refer to \n :ref:`api_guide_Name` . Usually name is no need to set and None by default.\n\n Returns:\n Variable: The ranking loss.\n\n Raises:\n ValueError: Any of label, left, and right is not a Variable.\n\n Examples:\n\n .. code-block:: python\n\n import paddle.fluid as fluid\n label = fluid.data(name=\"label\", shape=[-1, 1], dtype=\"float32\")\n left = fluid.data(name=\"left\", shape=[-1, 1], dtype=\"float32\")\n right = fluid.data(name=\"right\", shape=[-1, 1], dtype=\"float32\")\n out = fluid.layers.margin_rank_loss(label, left, right)\n \"\"\"\n helper = LayerHelper('margin_rank_loss', **locals())\n check_variable_and_dtype(label, 'label', ['float32'], 'margin_rank_loss')\n check_variable_and_dtype(label, 'left', ['float32'], 'margin_rank_loss')\n check_variable_and_dtype(label, 'right', ['float32'], 'margin_rank_loss')\n out = helper.create_variable_for_type_inference(left.dtype)\n act = helper.create_variable_for_type_inference(left.dtype)\n helper.append_op(\n type='margin_rank_loss',\n inputs={\"Label\": label,\n \"X1\": left,\n \"X2\": right},\n outputs={'Out': out,\n 'Activated': act},\n attrs={'margin': margin})\n return out\n\n\n@templatedoc()\ndef sigmoid_cross_entropy_with_logits(x,\n label,\n ignore_index=kIgnoreIndex,\n name=None,\n normalize=False):\n \"\"\"\n :alias_main: paddle.nn.functional.sigmoid_cross_entropy_with_logits\n\t:alias: paddle.nn.functional.sigmoid_cross_entropy_with_logits,paddle.nn.functional.loss.sigmoid_cross_entropy_with_logits\n\t:old_api: paddle.fluid.layers.sigmoid_cross_entropy_with_logits\n\n ${comment}\n\n Args:\n x(Variable): a 2-D tensor with shape N x D, where N is the batch size and\n D is the number of classes. This input is a tensor of logits computed\n by the previous operator. Logits are unscaled log probabilities given\n as log(p/(1-p)) The data type should be float32 or float64.\n label (Variable): a 2-D tensor of the same type and shape as X.\n This input is a tensor of probabalistic labels for each logit.\n ignore_index(int): Specifies a target value that is ignored and \n does not contribute to the input gradient.\n name(str|None): The default value is None. Normally there is\n no need for user to set this property. For more information,\n please refer to :ref:`api_guide_Name`\n normalize(bool): If true, divide the output by the number of\n targets != ignore_index.\n\n Returns:\n out(${out_type}): ${out_comment}\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n input = fluid.data(\n name='data', shape=[10], dtype='float32')\n label = fluid.data(\n name='data', shape=[10], dtype='float32')\n loss = fluid.layers.sigmoid_cross_entropy_with_logits(\n x=input,\n label=label,\n ignore_index=-1,\n normalize=True) # or False\n # loss = fluid.layers.reduce_sum(loss) # summation of loss\n \"\"\"\n check_variable_and_dtype(x, 'input', ['float16', 'float32', 'float64'],\n 'sigmoid_cross_entropy_with_logits')\n\n helper = LayerHelper(\"sigmoid_cross_entropy_with_logits\", **locals())\n\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n\n helper.append_op(\n type=\"sigmoid_cross_entropy_with_logits\",\n inputs={\"X\": x,\n \"Label\": label},\n attrs={\"ignore_index\": ignore_index,\n 'normalize': normalize},\n outputs={\"Out\": out})\n return out\n\n\ndef teacher_student_sigmoid_loss(input,\n label,\n soft_max_up_bound=15.0,\n soft_max_lower_bound=-15.0):\n \"\"\"\n :alias_main: paddle.nn.functional.teacher_student_sigmoid_loss\n\t:alias: paddle.nn.functional.teacher_student_sigmoid_loss,paddle.nn.functional.loss.teacher_student_sigmoid_loss\n\t:old_api: paddle.fluid.layers.teacher_student_sigmoid_loss\n\n **Teacher Student Log Loss Layer**\n\n This layer accepts input predictions and target label and returns the\n teacher_student loss. Z is click or not, z' is value of teacher loss, label = {-2, -1, [0, 2]}\n when z' is not exist, clk = 0 : label = -2; when z' is not exist, clk = 1 : label = -1;\n when z' is exist , clk = 0 : label = 0 + z'; when z' is exist , clk = 1 : label = 1 + z'\n\n .. math::\n loss = max(x, 0) - x * z + log(1 + exp(-abs(x))) + max(x, 0) - x * z' + log(1 + exp(-abs(x)))\n\n Args:\n input (Variable|list): a 2-D tensor with shape [N x 1], where N is the\n batch size. This input is a probability computed\n by the previous operator.\n label (Variable|list): the ground truth which is a 2-D tensor with\n shape [N x 1], where N is the batch size.\n soft_max_up_bound (float): if input > soft_max_up_bound, will be bound\n soft_max_lower_bound (float): if input < soft_max_lower_bound, will be bound\n\n Returns:\n Variable: A 2-D tensor with shape [N x 1], the teacher_student_sigmoid_loss.\n\n Examples:\n .. code-block:: python\n \n import paddle.fluid as fluid\n\n batch_size = 64\n label = fluid.data(\n name=\"label\", shape=[batch_size, 1], dtype=\"int64\")\n similarity = fluid.data(\n name=\"similarity\", shape=[batch_size, 1], dtype=\"float32\")\n cost = fluid.layers.teacher_student_sigmoid_loss(input=similarity, label=label)\n\n \"\"\"\n check_variable_and_dtype(input, \"input\",\n ['float32', 'float64', 'int32', 'int64'],\n 'teacher_student_sigmoid_loss')\n check_variable_and_dtype(label, \"label\",\n ['float32', 'float64', 'int32', 'int64'],\n 'teacher_student_sigmoid_loss')\n\n helper = LayerHelper('teacher_student_sigmoid_loss', **locals())\n out = helper.create_variable(dtype=input.dtype)\n helper.append_op(\n type='teacher_student_sigmoid_loss',\n inputs={'X': [input],\n 'Label': [label]},\n outputs={'Y': [out]},\n attrs={\"soft_max_lower_bound\": float(soft_max_lower_bound), \\\n \"soft_max_up_bound\": float(soft_max_up_bound)})\n return out\n\n\ndef huber_loss(input, label, delta):\n \"\"\"\n This operator computes the Huber loss between input and label.\n Huber loss is commonly used in regression tasks. Compared to square_error_cost, Huber loss is more robust and less sensitivity to outliers.\n\n When the absolute difference between input and label is greater than delta, the linear error is calculated:\n\n .. math::\n huber\\_loss = delta * (label - input) - 0.5 * delta * delta\n\n When the absolute difference between input and label is greater than delta, the square error is calculated:\n\n .. math::\n huber\\_loss = 0.5 * (label - input) * (label - input)\n\n\n Args:\n input (Variable): Predicted data, 2D-Tensor with the shape of [batch_size, 1]. The data type should be float32.\n label (Variable): Ground truth label, 2D-Tensor with the shape of [batch_size, 1]. The data type should be float32.\n delta (float): The threshold for Huber loss, which is used to control the balance between the linear error and square error. The data type should be float32.\n\n Returns:\n Variable: The huber loss, a tensor with the same shape and data type as input.\n\n\n Examples:\n\n .. code-block:: python\n\n import paddle.fluid as fluid\n import numpy as np\n\n DATATYPE='float32'\n input_data = np.array([[1.],[2.],[3.],[4.]]).astype(DATATYPE)\n label_data = np.array([[3.],[3.],[4.],[4.]]).astype(DATATYPE)\n\n x = fluid.data(name='input', shape=[None, 1], dtype=DATATYPE)\n y = fluid.data(name='label', shape=[None, 1], dtype=DATATYPE)\n loss = fluid.layers.huber_loss(input=x, label=y, delta=1.0)\n\n place = fluid.CPUPlace()\n #place = fluid.CUDAPlace(0)\n exe = fluid.Executor(place)\n HuberLoss, = exe.run(feed={'input':input_data ,'label':label_data}, fetch_list=[loss.name])\n print(HuberLoss) #[[1.5], [0.5], [0.5], [0. ]], dtype=float32\n \"\"\"\n helper = LayerHelper('huber_loss', **locals())\n check_variable_and_dtype(input, 'input', ['float32', 'float64'],\n 'huber_loss')\n check_variable_and_dtype(label, 'label', ['float32', 'float64'],\n 'huber_loss')\n residual = helper.create_variable_for_type_inference(\n dtype=helper.input_dtype())\n out = helper.create_variable_for_type_inference(dtype=helper.input_dtype())\n helper.append_op(\n type='huber_loss',\n inputs={'X': input,\n 'Y': label},\n outputs={'Out': out,\n 'Residual': residual},\n attrs={'delta': delta})\n return out\n\n\n@deprecated(since=\"2.0.0\", update_to=\"paddle.nn.functional.kl_div\")\n@templatedoc()\ndef kldiv_loss(x, target, reduction='mean', name=None):\n \"\"\"\n :alias_main: paddle.nn.functional.kldiv_loss\n\t:alias: paddle.nn.functional.kldiv_loss,paddle.nn.functional.loss.kldiv_loss\n\t:old_api: paddle.fluid.layers.kldiv_loss\n\n ${comment}\n\n Args:\n x (Variable): ${x_comment}\n target (Variable): ${target_comment}\n reduction (Variable): ${reduction_comment}\n name(str, optional): For detailed information, please refer\n to :ref:`api_guide_Name`. Usually name is no need to set and\n None by default.\n\n Returns:\n Variable(Tensor): The KL divergence loss. The data type is same as input tensor\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n \n # 'batchmean' reduction, loss shape will be [N]\n x = fluid.data(name='x', shape=[None,4,2,2], dtype='float32') # shape=[-1, 4, 2, 2]\n target = fluid.layers.data(name='target', shape=[4,2,2], dtype='float32')\n loss = fluid.layers.kldiv_loss(x=x, target=target, reduction='batchmean') # shape=[-1]\n \n # 'mean' reduction, loss shape will be [1]\n x = fluid.data(name='x', shape=[None,4,2,2], dtype='float32') # shape=[-1, 4, 2, 2]\n target = fluid.layers.data(name='target', shape=[4,2,2], dtype='float32')\n loss = fluid.layers.kldiv_loss(x=x, target=target, reduction='mean') # shape=[1]\n \n # 'sum' reduction, loss shape will be [1]\n x = fluid.data(name='x', shape=[None,4,2,2], dtype='float32') # shape=[-1, 4, 2, 2]\n target = fluid.layers.data(name='target', shape=[4,2,2], dtype='float32')\n loss = fluid.layers.kldiv_loss(x=x, target=target, reduction='sum') # shape=[1]\n \n # 'none' reduction, loss shape is same with X shape\n x = fluid.data(name='x', shape=[None,4,2,2], dtype='float32') # shape=[-1, 4, 2, 2]\n target = fluid.layers.data(name='target', shape=[4,2,2], dtype='float32')\n loss = fluid.layers.kldiv_loss(x=x, target=target, reduction='none') # shape=[-1, 4, 2, 2]\n\n \"\"\"\n helper = LayerHelper('kldiv_loss', **locals())\n check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'kldiv_loss')\n check_variable_and_dtype(target, 'target', ['float32', 'float64'],\n 'kldiv_loss')\n check_type(reduction, 'reduction', str, 'kldiv_loss')\n loss = helper.create_variable_for_type_inference(dtype=x.dtype)\n helper.append_op(\n type='kldiv_loss',\n inputs={'X': x,\n 'Target': target},\n outputs={'Loss': loss},\n attrs={'reduction': reduction})\n return loss\n\n\nfrom .ops import square\nfrom .control_flow import equal\n\n\ndef npair_loss(anchor, positive, labels, l2_reg=0.002):\n '''\n :alias_main: paddle.nn.functional.npair_loss\n\t:alias: paddle.nn.functional.npair_loss,paddle.nn.functional.loss.npair_loss\n\t:old_api: paddle.fluid.layers.npair_loss\n\n **Npair Loss Layer**\n\n Read `Improved Deep Metric Learning with Multi class N pair Loss Objective\\\n <http://www.nec-labs.com/uploads/images/Department-Images/MediaAnalytics/\\\n papers/nips16_npairmetriclearning.pdf>`_ .\n\n Npair loss requires paired data. Npair loss has two parts: the first part is L2\n regularizer on the embedding vector; the second part is cross entropy loss which\n takes the similarity matrix of anchor and positive as logits.\n\n Args:\n anchor(Variable): embedding vector for the anchor image. shape=[batch_size, embedding_dims], \n the data type is float32 or float64.\n positive(Variable): embedding vector for the positive image. shape=[batch_size, embedding_dims], \n the data type is float32 or float64.\n labels(Variable): 1-D tensor. shape=[batch_size], the data type is float32 or float64 or int64.\n l2_reg(float32): L2 regularization term on embedding vector, default: 0.002.\n\n Returns:\n A Variable holding Tensor representing the npair loss, the data type is the same as \n anchor, the shape is [1].\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n anchor = fluid.data(\n name = 'anchor', shape = [18, 6], dtype = 'float32')\n positive = fluid.data(\n name = 'positive', shape = [18, 6], dtype = 'float32')\n labels = fluid.data(\n name = 'labels', shape = [18], dtype = 'float32')\n\n npair_loss = fluid.layers.npair_loss(anchor, positive, labels, l2_reg = 0.002)\n '''\n check_variable_and_dtype(anchor, 'anchor', ['float32', 'float64'],\n 'npair_loss')\n check_variable_and_dtype(positive, 'positive', ['float32', 'float64'],\n 'positive')\n check_variable_and_dtype(labels, 'labels', ['float32', 'float64', 'int64'],\n 'labels')\n Beta = 0.25\n batch_size = labels.shape[0]\n\n labels = nn.reshape(labels, shape=[batch_size, 1], inplace=True)\n labels = nn.expand(labels, expand_times=[1, batch_size])\n\n labels = equal(labels, nn.transpose(labels, perm=[1, 0])).astype('float32')\n labels = labels / nn.reduce_sum(labels, dim=1, keep_dim=True)\n\n l2loss = nn.reduce_mean(nn.reduce_sum(square(anchor), 1)) \\\n + nn.reduce_mean(nn.reduce_sum(square(positive), 1))\n l2loss = l2loss * Beta * l2_reg\n\n similarity_matrix = nn.matmul(\n anchor, positive, transpose_x=False, transpose_y=True)\n softmax_ce = softmax_with_cross_entropy(\n logits=similarity_matrix, label=labels, soft_label=True)\n cross_entropy = nn.reduce_sum(labels * softmax_ce, 0)\n celoss = nn.reduce_mean(cross_entropy)\n\n return l2loss + celoss\n\n\ndef mse_loss(input, label):\n \"\"\"\n :alias_main: paddle.nn.functional.mse_loss\n\t:alias: paddle.nn.functional.mse_loss,paddle.nn.functional.loss.mse_loss\n\t:old_api: paddle.fluid.layers.mse_loss\n\n This op accepts input predications and target label and returns the mean square error.\n\n The loss can be described as:\n\n .. math::\n \n Out = MEAN((input - label)^2)\n\n Parameters: \n input (Variable): Input tensor, the data type should be float32.\n label (Variable): Label tensor, the data type should be float32.\n\n Returns:\n Variable: The tensor variable storing the mean square error difference of input and label.\n\n Return type: Variable.\n \n Examples:\n .. code-block:: python\n\t # declarative mode\n\t import paddle.fluid as fluid\n\t import numpy as np\n\t input = fluid.data(name=\"input\", shape=[1])\n\t label = fluid.data(name=\"label\", shape=[1])\n\t output = fluid.layers.mse_loss(input,label)\n\t place = fluid.CPUPlace()\n\t exe = fluid.Executor(place)\n\t exe.run(fluid.default_startup_program())\n \n\t input_data = np.array([1.5]).astype(\"float32\")\n\t label_data = np.array([1.7]).astype(\"float32\")\n\t output_data = exe.run(fluid.default_main_program(),\n feed={\"input\":input_data, \"label\":label_data},\n fetch_list=[output],\n return_numpy=True)\n \n\t print(output_data)\n\t # [array([0.04000002], dtype=float32)]\n\t \n\t # imperative mode\n\t import paddle.fluid.dygraph as dg\n\n\t with dg.guard(place) as g:\n \t\tinput = dg.to_variable(input_data)\n \t\tlabel = dg.to_variable(label_data)\n \t\toutput = fluid.layers.mse_loss(input, label)\n \t\tprint(output.numpy())\n\t \n\t # [0.04000002]\n\n \"\"\"\n check_variable_and_dtype(input, \"input\", ['float32', 'float64'], 'mse_loss')\n check_variable_and_dtype(label, \"label\", ['float32', 'float64'], 'mse_loss')\n return nn.reduce_mean(square_error_cost(input, label))\n"
]
| [
[
"numpy.array"
]
]
|
lionheartStark/GCN-graduate-design | [
"a0da3bda3eaf2e9b447915dbc968dc21cfe07639"
]
| [
"log/new_data/qy_Elliptic_dataset_EGCN.py"
]
| [
"#!/usr/bin/env python\n# coding: utf-8\n\n# <a href=\"https://colab.research.google.com/github/JungWoo-Chae/GCN_Elliptic_dataset/blob/main/Elliptic_dataset_GCN.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n\n# # Bitcoin Fraud Detection System with GCN\n\n# ## Pytorch Geometric Environment Setting\n\n# In[ ]:\n\n\n# Install required packages.\n# get_ipython().system('pip install -q torch-scatter==latest+cu101 -f https://pytorch-geometric.com/whl/torch-1.7.0.html')\n# get_ipython().system('pip install -q torch-sparse==latest+cu101 -f https://pytorch-geometric.com/whl/torch-1.7.0.html')\n# get_ipython().system('pip install -q git+https://github.com/rusty1s/pytorch_geometric.git')\n\n\n# ## Library Import\n\n# In[9]:\n\n\nimport numpy as np\nimport networkx as nx\nimport os\nimport pandas as pd\nfrom sklearn.metrics import f1_score, precision_score, recall_score\nfrom sklearn.manifold import TSNE\nimport matplotlib.pyplot as plt\nimport pickle\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import Embedding\nfrom torch.nn import Parameter\nfrom torch_geometric.data import Data, DataLoader\nfrom torch_geometric.nn import GCNConv, GATConv\nfrom torch_geometric_temporal.nn.recurrent import EvolveGCNO\n\nfrom torch_geometric.utils.convert import to_networkx\nfrom torch_geometric.utils import to_undirected\n\nfrom modle_GCN2layer import GCN as GCN2layer\nfrom try_EGCNO import RecurrentGCN as EGCNO\nfrom myevolvegcno import EvolveGCNO\n\nCHOOSE_MODE = {\n \"GCN\": GCN2layer,\n \"EGCN_H\": EGCNO\n}\n# In[10]:\nuse_dev = 'cuda' if torch.cuda.is_available() else 'cpu'\nprint(use_dev)\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\n# # **Please insert Kaggle username and kaggle key**\n\n# In[ ]:\n\n\n# os.environ['KAGGLE_USERNAME'] = \"@@@@@@@@@\" # username from the json file\n# os.environ['KAGGLE_KEY'] = \"####################\" # key from the json file\n# get_ipython().system('kaggle datasets download -d ellipticco/elliptic-data-set')\n# get_ipython().system('unzip elliptic-data-set.zip')\n# get_ipython().system('mkdir elliptic_bitcoin_dataset_cont')\n\n\n# ## Data Preparation\n\n# In[ ]:\n\n\ndef make_data(tag=\"mkdat\"):\n if os.path.exists('dat_' + f'{tag}'):\n with open('dat_' + f'{tag}', \"rb\") as f:\n ALL_DATA = pickle.load(f)\n return ALL_DATA\n\n # Load Dataframe\n df_edge = pd.read_csv('elliptic_bitcoin_dataset/elliptic_txs_edgelist.csv')\n df_class = pd.read_csv('elliptic_bitcoin_dataset/elliptic_txs_classes.csv')\n df_features = pd.read_csv('elliptic_bitcoin_dataset/elliptic_txs_features.csv', header=None)\n\n # Setting Column name\n df_features.columns = ['id', 'time step'] + [f'trans_feat_{i}' for i in range(93)] + [f'agg_feat_{i}' for i in\n range(72)]\n\n print('Number of edges: {}'.format(len(df_edge)))\n\n # ## Get Node Index\n\n # In[ ]:\n\n all_nodes = list(\n set(df_edge['txId1']).union(set(df_edge['txId2'])).union(set(df_class['txId'])).union(set(df_features['id'])))\n nodes_df = pd.DataFrame(all_nodes, columns=['id']).reset_index()\n NUM_NODES = len(nodes_df)\n print('Number of nodes: {}'.format(NUM_NODES))\n NUM_FEAT = 166\n # ## Fix id index\n\n # In[ ]:\n\n df_edge = df_edge.join(nodes_df.rename(columns={'id': 'txId1'}).set_index('txId1'), on='txId1', how='inner').join(\n nodes_df.rename(columns={'id': 'txId2'}).set_index('txId2'), on='txId2', how='inner', rsuffix='2').drop(\n columns=['txId1', 'txId2']).rename(columns={'index': 'txId1', 'index2': 'txId2'})\n df_edge.head()\n\n # In[ ]:\n\n df_class = df_class.join(nodes_df.rename(columns={'id': 'txId'}).set_index('txId'), on='txId', how='inner').drop(\n columns=['txId']).rename(columns={'index': 'txId'})[['txId', 'class']]\n df_class.head()\n\n # In[ ]:\n\n df_features = df_features.join(nodes_df.set_index('id'), on='id', how='inner').drop(columns=['id']).rename(\n columns={'index': 'id'})\n df_features = df_features[['id'] + list(df_features.drop(columns=['id']).columns)]\n df_features.head()\n\n # In[ ]:\n\n df_edge_time = df_edge.join(df_features[['id', 'time step']].rename(columns={'id': 'txId1'}).set_index('txId1'),\n on='txId1', how='left', rsuffix='1').join(\n df_features[['id', 'time step']].rename(columns={'id': 'txId2'}).set_index('txId2'), on='txId2', how='left',\n rsuffix='2')\n df_edge_time['is_time_same'] = df_edge_time['time step'] == df_edge_time['time step2']\n df_edge_time_fin = df_edge_time[['txId1', 'txId2', 'time step']].rename(\n columns={'txId1': 'source', 'txId2': 'target', 'time step': 'time'})\n\n # ## Create csv from Dataframe\n\n # In[ ]:\n\n df_features.drop(columns=['time step']).to_csv('elliptic_bitcoin_dataset_cont/elliptic_txs_features.csv',\n index=False,\n header=None)\n df_class.rename(columns={'txId': 'nid', 'class': 'label'})[['nid', 'label']].sort_values(by='nid').to_csv(\n 'elliptic_bitcoin_dataset_cont/elliptic_txs_classes.csv', index=False, header=None)\n df_features[['id', 'time step']].rename(columns={'id': 'nid', 'time step': 'time'})[['nid', 'time']].sort_values(\n by='nid').to_csv('elliptic_bitcoin_dataset_cont/elliptic_txs_nodetime.csv', index=False, header=None)\n df_edge_time_fin[['source', 'target', 'time']].to_csv(\n 'elliptic_bitcoin_dataset_cont/elliptic_txs_edgelist_timed.csv',\n index=False, header=None)\n\n # ## Graph Preprocessing\n\n # In[ ]:\n\n node_label = df_class.rename(columns={'txId': 'nid', 'class': 'label'})[['nid', 'label']].sort_values(\n by='nid').merge(\n df_features[['id', 'time step']].rename(columns={'id': 'nid', 'time step': 'time'}), on='nid', how='left')\n node_label['label'] = node_label['label'].apply(lambda x: '3' if x == 'unknown' else x).astype(int) - 1\n node_label.head()\n\n # In[ ]:\n\n merged_nodes_df = node_label.merge(\n df_features.rename(columns={'id': 'nid', 'time step': 'time'}).drop(columns=['time']), on='nid', how='left')\n merged_nodes_df.head()\n\n # In[ ]:\n\n train_dataset = []\n test_dataset = []\n test_dataset2 = []\n for i in range(49):\n nodes_df_tmp = merged_nodes_df[merged_nodes_df['time'] == i + 1].reset_index()\n nodes_df_tmp['index'] = nodes_df_tmp.index\n df_edge_tmp = df_edge_time_fin.join(\n nodes_df_tmp.rename(columns={'nid': 'source'})[['source', 'index']].set_index('source'), on='source',\n how='inner').join(nodes_df_tmp.rename(columns={'nid': 'target'})[['target', 'index']].set_index('target'),\n on='target', how='inner', rsuffix='2').drop(columns=['source', 'target']).rename(\n columns={'index': 'source', 'index2': 'target'})\n x = torch.tensor(np.array(nodes_df_tmp.sort_values(by='index').drop(columns=['index', 'nid', 'label'])),\n dtype=torch.float)\n edge_index = torch.tensor(np.array(df_edge_tmp[['source', 'target']]).T, dtype=torch.long)\n edge_index = to_undirected(edge_index)\n mask = nodes_df_tmp['label'] != 2\n y = torch.tensor(np.array(nodes_df_tmp['label']))\n # 划分测试集\n if i + 1 < 35:\n data = Data(x=x, edge_index=edge_index, train_mask=mask, y=y)\n train_dataset.append(data)\n else:\n data = Data(x=x, edge_index=edge_index, test_mask=mask, y=y)\n test_dataset.append(data)\n # elif i+1 < 35+5:\n # data = Data(x=x, edge_index=edge_index, test_mask=mask, y=y)\n # test_dataset.append(data)\n # else:\n # data = Data(x=x, edge_index=edge_index, test_mask=mask, y=y)\n # test_dataset2.append(data)\n\n train_loader = DataLoader(train_dataset, batch_size=1, shuffle=False)\n test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False)\n # test_loader2 = DataLoader(test_dataset2, batch_size=1, shuffle=False)\n ALL_DATA = [NUM_NODES, NUM_FEAT, train_loader, test_loader]\n pickle.dump(ALL_DATA, open('dat_' + f'{tag}', 'wb'))\n with open('dat_' + f'{tag}', \"rb\") as f:\n ALL_DATA = pickle.load(f)\n return ALL_DATA\n\n\n# ## Model\n\n# In[ ]:\n\n# In[ ]:\n\n\n# ## Train\n\n# #### Hyperparameter\n\n# In[ ]:\n\ndef tain_model(train_loader, test_loader, model, use_criterion, epoches=1000, tag=\"\"):\n patience = 50\n lr = 0.001\n epoches = epoches\n\n # In[ ]:\n\n optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n criterion = use_criterion\n # criterion = torch.nn.CrossEntropyLoss(weight=torch.tensor([0.7, 0.3]).to(device))\n # criterion = F.nll_loss\n train_losses = []\n val_losses = []\n accuracies = []\n if1 = []\n precisions = []\n recalls = []\n iterations = []\n logf = f\"log_{tag}\"\n all_logstr = \"\"\n for epoch in range(epoches):\n\n model.train()\n train_loss = 0\n\n for data in train_loader:\n data = data.to(device)\n optimizer.zero_grad()\n out = model(data)\n loss = criterion(out[data.train_mask], data.y[data.train_mask].long())\n _, pred = out[data.train_mask].max(dim=1)\n loss.backward()\n train_loss += loss.item() * data.num_graphs\n optimizer.step()\n train_loss /= len(train_loader.dataset)\n # 评估验证集\n if (epoch + 1) % 50 == 0:\n model.eval()\n ys, preds = [], []\n val_loss = 0\n for data in test_loader:\n data = data.to(device)\n out = model(data)\n loss = criterion(out[data.test_mask], data.y[data.test_mask].long())\n val_loss += loss.item() * data.num_graphs\n _, pred = out[data.test_mask].max(dim=1)\n ys.append(data.y[data.test_mask].cpu())\n preds.append(pred.cpu())\n\n y, pred = torch.cat(ys, dim=0).numpy(), torch.cat(preds, dim=0).numpy()\n val_loss /= len(test_loader.dataset)\n f1 = f1_score(y, pred, average=None)\n mf1 = f1_score(y, pred, average='micro')\n precision = precision_score(y, pred, average=None)\n recall = recall_score(y, pred, average=None)\n\n iterations.append(epoch + 1)\n train_losses.append(train_loss)\n val_losses.append(val_loss)\n if1.append(f1[0])\n accuracies.append(mf1)\n precisions.append(precision[0])\n recalls.append(recall[0])\n log_str = 'Epoch: {:02d}, Train_Loss: {:.4f}, Val_Loss: {:.4f}, Precision: {:.4f}, Recall: {:.4f}, Illicit f1: {:.4f}, mF1: {:.4f}'.format(\n epoch + 1, train_loss, val_loss, precision[0], recall[0], f1[0], mf1) + \"\\n\" + \\\n f'T class precision: {precision[1]}, recall: {recall[1]}, f1: {f1[1]}\\n'\n print(log_str\n )\n all_logstr += log_str\n\n # In[ ]:\n with open(logf, \"w+\") as f:\n f.write(all_logstr)\n\n a, b, c, d = train_losses, val_losses, if1, accuracies\n\n import pickle\n\n g = [a, b, c, d]\n pickle.dump(g, open('res_' + f'{tag}', 'wb'))\n with open('res_' + f'{tag}', \"rb\") as f:\n g = pickle.load(f)\n a, b, c, d = g\n\n ep = [i for i in range(patience, epoches + 1, patience)]\n plt.figure()\n plt.plot(np.array(ep), np.array(a), 'r', label='Train loss')\n plt.plot(np.array(ep), np.array(b), 'g', label='Valid loss')\n plt.plot(np.array(ep), np.array(c), 'black', label='Illicit F1')\n plt.plot(np.array(ep), np.array(d), 'orange', label='mF1')\n plt.legend(['Train loss', 'Valid loss', 'Illicit F1', 'mF1'])\n plt.ylim([0, 1.0])\n plt.xlim([patience, epoches])\n plt.savefig(f\"pic_{tag}.png\")\n\n\nif __name__ == \"__main__\":\n # In[ ]:\n GCNN = EGCNO\n NUM_NODES, NUM_FEAT, train_loader, test_loader = make_data()\n epoches = 1000\n print(f\"make_data ok!!!, epoches = {epoches}\")\n for i in [\n (\"EGCN_EGCN\", EvolveGCNO, EvolveGCNO, True)]:\n\n print(i[0])\n tag, conv1, conv2, useskip = i\n tag = tag + \"_skip\" + str(useskip)\n model = EGCNO(NUM_FEAT, 2)\n model.to(device)\n lossf = torch.nn.CrossEntropyLoss(weight=torch.tensor([0.9, 0.1]).to(device))\n tain_model(train_loader, test_loader, model, lossf, epoches=epoches, tag=tag)\n torch.save(model.state_dict(), f'model_{tag}.pkl')\n # break\n # 加载\n # model = torch.load(f'\\model_{tag}.pkl')\n # model.load_state_dict(torch.load('\\parameter.pkl'))\n"
]
| [
[
"numpy.array",
"torch.cat",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylim",
"pandas.DataFrame",
"matplotlib.pyplot.legend",
"sklearn.metrics.precision_score",
"matplotlib.pyplot.figure",
"torch.cuda.is_available",
"torch.tensor",
"pandas.read_csv",
"sklearn.metrics.f1_score",
"sklearn.metrics.recall_score"
]
]
|
favitor/im2avatar | [
"d5f0fc181b8594cd443f63a6aeb0d9731b491265"
]
| [
"train_shape.py"
]
| [
"import tensorflow as tf\nimport numpy as np\nimport os\nimport sys\nsys.path.append('./utils')\nsys.path.append('./models')\n\nimport dataset as dataset\nimport model_shape as model\n\nFLAGS = tf.app.flags.FLAGS\ntf.app.flags.DEFINE_string('train_dir', './train_shape',\n \"\"\"Directory where to write summaries and checkpoint.\"\"\")\ntf.app.flags.DEFINE_string('base_dir', './data/ShapeNetCore_im2avatar', \n \"\"\"The path containing all the samples.\"\"\")\ntf.app.flags.DEFINE_string('cat_id', '02958343', \n \"\"\"The category id for each category: 02958343, 03001627, 03467517, 04379243\"\"\")\ntf.app.flags.DEFINE_string('data_list_path', './data_list', \n \"\"\"The path containing data lists.\"\"\")\n\ntf.app.flags.DEFINE_integer('train_epochs', 501, \"\"\"Training epochs.\"\"\")\ntf.app.flags.DEFINE_integer('batch_size', 60, \"\"\"Batch size.\"\"\")\ntf.app.flags.DEFINE_integer('gpu', 0, \"\"\"\"\"\")\ntf.app.flags.DEFINE_float('learning_rate', 0.0003, \"\"\"\"\"\")\ntf.app.flags.DEFINE_float('wd', 0.00001, \"\"\"\"\"\")\ntf.app.flags.DEFINE_integer('epochs_to_save',20, \"\"\"\"\"\")\ntf.app.flags.DEFINE_integer('decay_step',20000, \"\"\"for lr\"\"\")\ntf.app.flags.DEFINE_float('decay_rate', 0.7, \"\"\"for lr\"\"\")\n\nIM_DIM = 128 \nVOL_DIM = 64 \n\nBATCH_SIZE = FLAGS.batch_size\nTRAIN_EPOCHS = FLAGS.train_epochs\nGPU_INDEX = FLAGS.gpu\nBASE_LEARNING_RATE = FLAGS.learning_rate\nDECAY_STEP = FLAGS.decay_step\nDECAY_RATE = FLAGS.decay_rate\n\nBN_INIT_DECAY = 0.5\nBN_DECAY_DECAY_RATE = 0.5\nBN_DECAY_DECAY_STEP = float(DECAY_STEP)\nBN_DECAY_CLIP = 0.99\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = str(GPU_INDEX)\n\nTRAIN_DIR = os.path.join(FLAGS.train_dir, FLAGS.cat_id)\nif not os.path.exists(TRAIN_DIR): \n os.makedirs(TRAIN_DIR)\nLOG_FOUT = open(os.path.join(TRAIN_DIR, 'log_train.txt'), 'w')\nLOG_FOUT.write(str(tf.flags._global_parser.parse_args())+'\\n')\n\ndef log_string(out_str):\n LOG_FOUT.write(out_str+'\\n')\n LOG_FOUT.flush()\n print(out_str)\n\n\ndef get_learning_rate(batch):\n learning_rate = tf.train.exponential_decay(\n BASE_LEARNING_RATE, # Base learning rate.\n batch * BATCH_SIZE, # Current index into the dataset.\n DECAY_STEP, # Decay step.\n DECAY_RATE, # Decay rate.\n staircase=True)\n learning_rate = tf.maximum(learning_rate, 0.00001) # CLIP THE LEARNING RATE!\n return learning_rate \n\n\ndef get_bn_decay(batch):\n bn_momentum = tf.train.exponential_decay(\n BN_INIT_DECAY,\n batch*BATCH_SIZE,\n BN_DECAY_DECAY_STEP,\n BN_DECAY_DECAY_RATE,\n staircase=True)\n bn_decay = tf.minimum(BN_DECAY_CLIP, 1 - bn_momentum)\n return bn_decay \n\n\ndef train(dataset_):\n with tf.Graph().as_default():\n with tf.device('/gpu:'+str(GPU_INDEX)):\n is_train_pl = tf.placeholder(tf.bool)\n img_pl, vol_pl = model.placeholder_inputs(BATCH_SIZE, IM_DIM, VOL_DIM)\n\n global_step = tf.Variable(0)\n bn_decay = get_bn_decay(global_step)\n tf.summary.scalar('bn_decay', bn_decay)\n\n pred = model.get_model(img_pl, is_train_pl, weight_decay=FLAGS.wd, bn_decay=bn_decay)\n loss = model.get_MSFE_cross_entropy_loss(pred, vol_pl)\n tf.summary.scalar('loss', loss)\n\n learning_rate = get_learning_rate(global_step)\n tf.summary.scalar('learning_rate', learning_rate)\n optimizer = tf.train.AdamOptimizer(learning_rate)\n train_op = optimizer.minimize(loss, global_step=global_step)\n\n summary_op = tf.summary.merge_all()\n\n saver = tf.train.Saver()\n\n config = tf.ConfigProto()\n config.gpu_options.allocator_type = 'BFC'\n config.gpu_options.allow_growth = True\n config.allow_soft_placement = True\n\n with tf.Session(config=config) as sess:\n model_path = os.path.join(TRAIN_DIR, \"trained_models\")\n if tf.gfile.Exists(os.path.join(model_path, \"checkpoint\")):\n ckpt = tf.train.get_checkpoint_state(model_path)\n restorer = tf.train.Saver()\n restorer.restore(sess, ckpt.model_checkpoint_path)\n print (\"Load parameters from checkpoint.\")\n else:\n sess.run(tf.global_variables_initializer())\n\n train_summary_writer = tf.summary.FileWriter(model_path, graph=sess.graph)\n\n train_sample_size = dataset_.getTrainSampleSize()\n train_batches = train_sample_size // BATCH_SIZE # The number of batches per epoch\n\n val_sample_size = dataset_.getValSampleSize()\n val_batches = val_sample_size // BATCH_SIZE\n\n for epoch in range(TRAIN_EPOCHS):\n ####################\n # For training\n ####################\n dataset_.shuffleIds()\n for batch_idx in range(train_batches):\n imgs, vols_clr = dataset_.next_batch(batch_idx * BATCH_SIZE, BATCH_SIZE, vol_dim=VOL_DIM)\n vols_occu = np.prod(vols_clr > -0.5, axis=-1, keepdims=True) # (batch, vol_dim, vol_dim, vol_dim, 1)\n vols_occu = vols_occu.astype(np.float32)\n\n feed_dict = {img_pl: imgs, vol_pl: vols_occu, is_train_pl: True}\n\n step = sess.run(global_step)\n _, loss_val = sess.run([train_op, loss], feed_dict=feed_dict)\n\n log_string(\"<TRAIN> Epoch {} - Batch {}: loss: {}.\".format(epoch, batch_idx, loss_val))\n\n \n #####################\n # For validation\n #####################\n loss_sum = 0.0\n for batch_idx in range(val_batches):\n imgs, vols_clr = dataset_.next_batch(batch_idx * BATCH_SIZE, BATCH_SIZE, vol_dim=VOL_DIM, process=\"val\")\n vols_occu = np.prod(vols_clr > -0.5, axis=-1, keepdims=True) # (batch, vol_dim, vol_dim, vol_dim, 1)\n vols_occu = vols_occu.astype(np.float32)\n\n feed_dict = {img_pl: imgs, vol_pl: vols_occu, is_train_pl: False}\n \n loss_val = sess.run(loss, feed_dict=feed_dict)\n loss_sum += loss_val\n log_string(\"<VAL> Epoch {}: loss: {}.\".format(epoch, loss_sum/val_batches))\n\n #####################\n # Save model parameters.\n #####################\n if epoch % FLAGS.epochs_to_save == 0:\n checkpoint_path = os.path.join(model_path, 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step=epoch)\n\n\ndef main():\n train_dataset = dataset.Dataset(base_path=FLAGS.base_dir, \n cat_id=FLAGS.cat_id, \n data_list_path=FLAGS.data_list_path)\n\n train(train_dataset)\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n\n"
]
| [
[
"tensorflow.train.get_checkpoint_state",
"tensorflow.flags._global_parser.parse_args",
"tensorflow.global_variables_initializer",
"tensorflow.Variable",
"tensorflow.train.Saver",
"tensorflow.ConfigProto",
"numpy.prod",
"tensorflow.minimum",
"tensorflow.train.AdamOptimizer",
"tensorflow.summary.scalar",
"tensorflow.maximum",
"tensorflow.Session",
"tensorflow.placeholder",
"tensorflow.summary.merge_all",
"tensorflow.train.exponential_decay",
"tensorflow.app.flags.DEFINE_integer",
"tensorflow.app.flags.DEFINE_string",
"tensorflow.Graph",
"tensorflow.app.flags.DEFINE_float",
"tensorflow.summary.FileWriter"
]
]
|
JPlin/semantic-segmentation-pytorch | [
"c435f02cf1225e0c4a948c4e040d23bbfd5d336a"
]
| [
"dataset.py"
]
| [
"import os\nimport json\nimport torch\nfrom torchvision import transforms\nimport numpy as np\nfrom PIL import Image\nimport random\n\n\ndef imresize(im, size, interp='bilinear'):\n if interp == 'nearest':\n resample = Image.NEAREST\n elif interp == 'bilinear':\n resample = Image.BILINEAR\n elif interp == 'bicubic':\n resample = Image.BICUBIC\n else:\n raise Exception('resample method undefined!')\n\n return im.resize(size, resample)\n\n\nclass BaseDataset(torch.utils.data.Dataset):\n def __init__(self, odgt, opt, **kwargs):\n # parse options\n self.imgSizes = opt.imgSizes\n self.imgMaxSize = opt.imgMaxSize\n # max down sampling rate of network to avoid rounding during conv or pooling\n self.padding_constant = opt.padding_constant\n\n # parse the input list\n self.parse_input_list(odgt, **kwargs)\n\n # mean and std\n self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n def parse_input_list(self, odgt, max_sample=-1, start_idx=-1, end_idx=-1):\n if isinstance(odgt, list):\n self.list_sample = odgt\n elif isinstance(odgt, str):\n self.list_sample = [\n json.loads(x.rstrip()) for x in open(odgt, 'r')\n ]\n\n random.shuffle(self.list_sample)\n if max_sample > 0:\n self.list_sample = self.list_sample[0:max_sample]\n if start_idx >= 0 and end_idx >= 0: # divide file list\n self.list_sample = self.list_sample[start_idx:end_idx]\n\n self.num_sample = len(self.list_sample)\n assert self.num_sample > 0\n print('# samples: {}'.format(self.num_sample))\n\n def img_transform(self, img):\n # 0-255 to 0-1\n img = np.float32(np.array(img)) / 255.\n img = img.transpose((2, 0, 1))\n img = self.normalize(torch.from_numpy(img.copy()))\n return img\n\n def segm_transform(self, segm):\n # to tensor, -1 to 149\n # segm = torch.from_numpy(np.array(segm)).long() - 1\n segm = torch.from_numpy(np.array(segm)).long() + 0\n return segm\n\n # Round x to the nearest multiple of p and x' >= x\n def round2nearest_multiple(self, x, p):\n return ((x - 1) // p + 1) * p\n\n\nclass TrainDataset(BaseDataset):\n def __init__(self, root_dataset, odgt, opt, batch_per_gpu=1, **kwargs):\n super(TrainDataset, self).__init__(odgt, opt, **kwargs)\n self.root_dataset = root_dataset\n # down sampling rate of segm labe\n self.segm_downsampling_rate = opt.segm_downsampling_rate\n self.batch_per_gpu = batch_per_gpu\n\n # classify images into two classes: 1. h > w and 2. h <= w\n self.batch_record_list = [[], []]\n\n # override dataset length when trainig with batch_per_gpu > 1\n self.cur_idx = 0\n self.if_shuffled = False\n\n def _get_sub_batch(self):\n while True:\n # get a sample record\n this_sample = self.list_sample[self.cur_idx]\n if this_sample['height'] > this_sample['width']:\n self.batch_record_list[0].append(\n this_sample) # h > w, go to 1st class\n else:\n self.batch_record_list[1].append(\n this_sample) # h <= w, go to 2nd class\n\n # update current sample pointer\n self.cur_idx += 1\n if self.cur_idx >= self.num_sample:\n self.cur_idx = 0\n np.random.shuffle(self.list_sample)\n\n if len(self.batch_record_list[0]) == self.batch_per_gpu:\n batch_records = self.batch_record_list[0]\n self.batch_record_list[0] = []\n break\n elif len(self.batch_record_list[1]) == self.batch_per_gpu:\n batch_records = self.batch_record_list[1]\n self.batch_record_list[1] = []\n break\n return batch_records\n\n def __getitem__(self, index):\n # NOTE: random shuffle for the first time. shuffle in __init__ is useless\n if not self.if_shuffled:\n np.random.seed(index)\n np.random.shuffle(self.list_sample)\n self.if_shuffled = True\n\n # get sub-batch candidates\n batch_records = self._get_sub_batch()\n\n # resize all images' short edges to the chosen size\n if isinstance(self.imgSizes, list) or isinstance(self.imgSizes, tuple):\n this_short_size = np.random.choice(self.imgSizes)\n else:\n this_short_size = self.imgSizes\n\n # calculate the BATCH's height and width\n # since we concat more than one samples, the batch's h and w shall be larger than EACH sample\n batch_widths = np.zeros(self.batch_per_gpu, np.int32)\n batch_heights = np.zeros(self.batch_per_gpu, np.int32)\n for i in range(self.batch_per_gpu):\n img_height, img_width = batch_records[i]['height'], batch_records[\n i]['width']\n this_scale = min(\n this_short_size / min(img_height, img_width), \\\n self.imgMaxSize / max(img_height, img_width))\n batch_widths[i] = img_width * this_scale\n batch_heights[i] = img_height * this_scale\n\n # Here we must pad both input image and segmentation map to size h' and w' so that p | h' and p | w'\n batch_width = np.max(batch_widths)\n batch_height = np.max(batch_heights)\n batch_width = int(\n self.round2nearest_multiple(batch_width, self.padding_constant))\n batch_height = int(\n self.round2nearest_multiple(batch_height, self.padding_constant))\n\n assert self.padding_constant >= self.segm_downsampling_rate, \\\n 'padding constant must be equal or large than segm downsamping rate'\n batch_images = torch.zeros(self.batch_per_gpu, 3, batch_height,\n batch_width)\n batch_segms = torch.zeros(\n self.batch_per_gpu, batch_height // self.segm_downsampling_rate,\n batch_width // self.segm_downsampling_rate).long()\n\n for i in range(self.batch_per_gpu):\n this_record = batch_records[i]\n\n # load image and label\n image_path = os.path.join(self.root_dataset,\n this_record['fpath_img'])\n segm_path = os.path.join(self.root_dataset,\n this_record['fpath_segm'])\n\n img = Image.open(image_path).convert('RGB')\n segm = Image.open(segm_path)\n assert (segm.mode == \"L\")\n assert (img.size[0] == segm.size[0])\n assert (img.size[1] == segm.size[1])\n\n # random_flip\n if np.random.choice([0, 1]):\n img = img.transpose(Image.FLIP_LEFT_RIGHT)\n segm = segm.transpose(Image.FLIP_LEFT_RIGHT)\n\n # note that each sample within a mini batch has different scale param\n img = imresize(img, (batch_widths[i], batch_heights[i]),\n interp='bilinear')\n segm = imresize(segm, (batch_widths[i], batch_heights[i]),\n interp='nearest')\n\n # further downsample seg label, need to avoid seg label misalignment\n segm_rounded_width = self.round2nearest_multiple(\n segm.size[0], self.segm_downsampling_rate)\n segm_rounded_height = self.round2nearest_multiple(\n segm.size[1], self.segm_downsampling_rate)\n segm_rounded = Image.new('L',\n (segm_rounded_width, segm_rounded_height),\n 0)\n segm_rounded.paste(segm, (0, 0))\n segm = imresize(\n segm_rounded,\n (segm_rounded.size[0] // self.segm_downsampling_rate, \\\n segm_rounded.size[1] // self.segm_downsampling_rate), \\\n interp='nearest')\n\n # image transform, to torch float tensor 3xHxW\n img = self.img_transform(img)\n\n # segm transform, to torch long tensor HxW\n segm = self.segm_transform(segm)\n\n # put into batch arrays\n batch_images[i][:, :img.shape[1], :img.shape[2]] = img\n batch_segms[i][:segm.shape[0], :segm.shape[1]] = segm\n\n output = dict()\n output['img_data'] = batch_images\n output['seg_label'] = batch_segms\n return output\n\n def __len__(self):\n return int(\n 1e10\n ) # It's a fake length due to the trick that every loader maintains its own list\n #return self.num_sampleclass\n\n\nclass ValDataset(BaseDataset):\n def __init__(self, root_dataset, odgt, opt, **kwargs):\n super(ValDataset, self).__init__(odgt, opt, **kwargs)\n self.root_dataset = root_dataset\n\n def __getitem__(self, index):\n this_record = self.list_sample[index]\n # load image and label\n image_path = os.path.join(self.root_dataset, this_record['fpath_img'])\n segm_path = os.path.join(self.root_dataset, this_record['fpath_segm'])\n img = Image.open(image_path).convert('RGB')\n segm = Image.open(segm_path)\n assert (segm.mode == \"L\")\n assert (img.size[0] == segm.size[0])\n assert (img.size[1] == segm.size[1])\n\n ori_width, ori_height = img.size\n\n img_resized_list = []\n for this_short_size in self.imgSizes:\n # calculate target height and width\n scale = min(this_short_size / float(min(ori_height, ori_width)),\n self.imgMaxSize / float(max(ori_height, ori_width)))\n target_height, target_width = int(ori_height * scale), int(\n ori_width * scale)\n\n # to avoid rounding in network\n target_width = self.round2nearest_multiple(target_width,\n self.padding_constant)\n target_height = self.round2nearest_multiple(\n target_height, self.padding_constant)\n\n # resize images\n img_resized = imresize(img, (target_width, target_height),\n interp='bilinear')\n\n # image transform, to torch float tensor 3xHxW\n img_resized = self.img_transform(img_resized)\n img_resized = torch.unsqueeze(img_resized, 0)\n img_resized_list.append(img_resized)\n\n # segm transform, to torch long tensor HxW\n segm = self.segm_transform(segm)\n batch_segms = torch.unsqueeze(segm, 0)\n\n output = dict()\n output['img_ori'] = np.array(img)\n output['img_data'] = [x.contiguous() for x in img_resized_list]\n output['seg_label'] = batch_segms.contiguous()\n output['info'] = this_record['fpath_img']\n return output\n\n def __len__(self):\n return self.num_sample\n\n\nclass TestDataset(BaseDataset):\n def __init__(self, odgt, opt, **kwargs):\n super(TestDataset, self).__init__(odgt, opt, **kwargs)\n\n def __getitem__(self, index):\n this_record = self.list_sample[index]\n # load image\n image_path = this_record['fpath_img']\n img = Image.open(image_path).convert('RGB')\n\n ori_width, ori_height = img.size\n\n img_resized_list = []\n for this_short_size in self.imgSizes:\n # calculate target height and width\n scale = min(this_short_size / float(min(ori_height, ori_width)),\n self.imgMaxSize / float(max(ori_height, ori_width)))\n target_height, target_width = int(ori_height * scale), int(\n ori_width * scale)\n\n # to avoid rounding in network\n target_width = self.round2nearest_multiple(target_width,\n self.padding_constant)\n target_height = self.round2nearest_multiple(\n target_height, self.padding_constant)\n\n # resize images\n img_resized = imresize(img, (target_width, target_height),\n interp='bilinear')\n\n # image transform, to torch float tensor 3xHxW\n img_resized = self.img_transform(img_resized)\n img_resized = torch.unsqueeze(img_resized, 0)\n img_resized_list.append(img_resized)\n\n output = dict()\n output['img_ori'] = np.array(img)\n output['img_data'] = [x.contiguous() for x in img_resized_list]\n output['info'] = this_record['fpath_img']\n return output\n\n def __len__(self):\n return self.num_sample\n\n\nif __name__ == '__main__':\n import os\n import time\n # import math\n import random\n import argparse\n from distutils.version import LooseVersion\n import matplotlib.pyplot as plt\n\n from config import cfg\n from lib.nn import UserScatteredDataParallel, user_scattered_collate, patch_replication_callback\n\n assert LooseVersion(torch.__version__) >= LooseVersion('0.4.0'), \\\n 'PyTorch>=0.4.0 is required'\n\n parser = argparse.ArgumentParser(\n description=\"PyTorch Semantic Segmentation Training\")\n parser.add_argument(\n \"--cfg\",\n default=\"config/face-resnet18dilated-ppm_deepsup.yaml\",\n metavar=\"FILE\",\n help=\"path to config file\",\n type=str,\n )\n parser.add_argument(\"--gpus\",\n default=\"0\",\n help=\"gpus to use, e.g. 0-3 or 0,1,2,3\")\n parser.add_argument(\n \"opts\",\n help=\"Modify config options using the command-line\",\n default=None,\n nargs=argparse.REMAINDER,\n )\n args = parser.parse_args()\n\n cfg.merge_from_file(args.cfg)\n cfg.merge_from_list(args.opts)\n\n cfg.TRAIN.batch_size = 1 * cfg.TRAIN.batch_size_per_gpu\n\n cfg.TRAIN.max_iters = cfg.TRAIN.epoch_iters * cfg.TRAIN.num_epoch\n cfg.TRAIN.running_lr_encoder = cfg.TRAIN.lr_encoder\n cfg.TRAIN.running_lr_decoder = cfg.TRAIN.lr_decoder\n dataset_train = TrainDataset(cfg.DATASET.root_dataset,\n cfg.DATASET.list_train,\n cfg.DATASET,\n batch_per_gpu=cfg.TRAIN.batch_size_per_gpu)\n\n loader_train = torch.utils.data.DataLoader(\n dataset_train,\n batch_size=1, # we have modified data_parallel\n shuffle=False, # we do not use this param\n collate_fn=user_scattered_collate,\n drop_last=True,\n pin_memory=True)\n\n for batch_data in loader_train:\n img = batch_data[0]['img_data']\n label = batch_data[0]['seg_label']\n\n plt.imshow(img[0].permute((1, 2, 0)).numpy())\n plt.show()\n plt.imshow(label[0].numpy())\n plt.show()\n print(np.max(label[0].numpy()), np.min(label[0].numpy()))\n"
]
| [
[
"numpy.max",
"torch.zeros",
"numpy.array",
"numpy.random.choice",
"numpy.zeros",
"numpy.random.seed",
"numpy.random.shuffle",
"torch.unsqueeze",
"torch.utils.data.DataLoader",
"matplotlib.pyplot.show"
]
]
|
killerSwitch/autogluon | [
"11ab6aab35196ef148fb5a8308e92585d9de618a"
]
| [
"core/src/autogluon/core/models/ensemble/fold_fitting_strategy.py"
]
| [
"import copy\nimport logging\nimport os\nimport time\nimport pandas as pd\nimport pickle\nimport psutil\nimport math\nfrom abc import abstractmethod\n\nfrom numpy import ndarray\nfrom pandas import DataFrame, Series\n\nfrom autogluon.common.utils.pandas_utils import get_approximate_df_mem_usage\n\nfrom ...utils.exceptions import TimeLimitExceeded, NotEnoughMemoryError, NotEnoughCudaMemoryError\nfrom ...utils import get_cpu_count, get_gpu_count\nfrom ...utils.try_import import try_import_ray\n\nlogger = logging.getLogger(__name__)\n\nTEXT_MODEL = 'TextPredictorModel'\nIMAGE_MODEL = 'ImagePredictorModel'\nTABULAR_MXNET_MODEL = 'TabularNeuralNetModel'\nTABULAR_FASTAI_MODEL = 'NNFastAiTabularModel'\n\n\nclass AbstractFoldFittingStrategy():\n\n @abstractmethod\n def schedule_fold_model_fit(self, fold_ctx):\n \"\"\"\n Schedule fold model training.\n By design this part is supposed to be 'lazy' evaluator,\n no actual training is performed here.\n Distributed fitters will handle jobs scheduling here.\n \"\"\"\n\n @abstractmethod\n def after_all_folds_scheduled(self):\n \"\"\"\n Method is called when all the folds are scheduled.\n Local fitters will perform training here.\n Distributed fitters will handle job handles and results retrieval here.\n \"\"\"\n\n @abstractmethod\n def _fit(self, model_base, time_start_fold, time_limit_fold, fold_ctx, kwargs):\n \"\"\"\n Method is called when a fold is ready to be fit\n \"\"\"\n\n\nclass LocalFoldFittingStrategy(AbstractFoldFittingStrategy):\n \"\"\"\n Provides some default implementation for AbstractFoldFittingStrategy\n\n Parameters\n ----------\n model_base: AbstractModel\n The template for the folds of model to be trained on.\n model_base_kwargs: dict\n kwargs required to initialize the model base when training the model.\n bagged_ensemble_model : BaggedEnsembleModel\n The ensemble model that holds all the trained folds.\n X : DataFrame\n The training data the model will be trained on.\n y: Series\n The labels of the training data.\n sample_weight:\n The sample weight of the training data.\n time_limit: float\n Approximately how long(in seconds) the fold fitting should be run for. \n If None, no time-constraint will be enforced allowing the folds to fully train. \n time_start: float\n Time starts to fit the BaggedEnsembleModel.\n models: list\n List of models that will be trained.\n oof_pred_proba: ndarray\n Out of folds predict probabilities that are already calculated.\n oof_pred_model_repeats: ndarray,\n Number of repeats the out of folds predict probabilities has been done.\n save_folds: bool, \n Whether to save the folds to disk.\n time_limit_fold_ratio: float, default=0.8\n The ratio of max time limit for each fold.\n If the estimated time required exceeds this ratio, will raise TimeLimitExceed error\n Attributes\n ----------\n X : DataFrame\n The training data the model will be trained on.\n y: Series\n The labels of the training data.\n sample_weight:\n The sample weight of the training data.\n time_limit: float\n Approximately how long(in seconds) the fold fitting should be run for. \n If None, no time-constraint will be enforced allowing the folds to fully train. \n time_start: float\n Time starts to fit the BaggedEnsembleModel.\n models: list\n List of models that will be trained.\n oof_pred_proba: ndarray\n Out of folds predict probabilities that are already calculated.\n oof_pred_model_repeats: ndarray,\n Number of repeats the out of folds predict probabilities has been done.\n jobs: list\n List of jobs that will be scheduled.\n save_folds: bool,\n Whether to save the folds to disk.\n time_limit_fold_ratio: float\n The ratio of max time limit for each fold.\n \"\"\"\n\n def __init__(self, model_base, model_base_kwargs, bagged_ensemble_model,\n X: DataFrame, y: Series, X_pseudo: DataFrame, y_pseudo: Series,\n sample_weight, time_limit: float, time_start: float,\n models: list, oof_pred_proba: ndarray, oof_pred_model_repeats: ndarray,\n save_folds: bool, time_limit_fold_ratio=0.8):\n self.model_base = model_base\n self.model_base_kwargs = model_base_kwargs\n self.X = X\n self.y = y\n self.X_pseudo = X_pseudo\n self.y_pseudo = y_pseudo\n self.sample_weight = sample_weight\n self.time_limit = time_limit\n self.time_start = time_start\n self.models = models\n self.oof_pred_proba = oof_pred_proba\n self.oof_pred_model_repeats = oof_pred_model_repeats\n self.bagged_ensemble_model = bagged_ensemble_model\n self.jobs = []\n self.save_folds = save_folds\n self.time_limit_fold_ratio = time_limit_fold_ratio\n\n def schedule_fold_model_fit(self, fold_ctx):\n raise NotImplementedError\n\n def after_all_folds_scheduled(self):\n raise NotImplementedError\n\n def _get_fold_time_limit(self, fold_ctx):\n _, folds_finished, folds_left, folds_to_fit, _, _ = self._get_fold_properties(fold_ctx)\n time_elapsed = time.time() - self.time_start\n if self.time_limit is not None:\n time_left = self.time_limit - time_elapsed\n required_time_per_fold = time_left / folds_left\n time_limit_fold = required_time_per_fold * self.time_limit_fold_ratio\n if folds_finished > 0:\n expected_time_required = time_elapsed * folds_to_fit / folds_finished\n expected_remaining_time_required = expected_time_required * folds_left / folds_to_fit\n if expected_remaining_time_required > time_left:\n raise TimeLimitExceeded\n if time_left <= 0:\n raise TimeLimitExceeded\n else:\n time_limit_fold = None\n return time_limit_fold\n\n def _update_bagged_ensemble(self, fold_model, pred_proba, fold_ctx):\n _, val_index = fold_ctx['fold']\n model_to_append = fold_model\n if not self.save_folds:\n fold_model.model = None\n if self.bagged_ensemble_model.low_memory:\n self.bagged_ensemble_model.save_child(fold_model, verbose=False)\n model_to_append = fold_model.name\n self.models.append(model_to_append)\n self.oof_pred_proba[val_index] += pred_proba\n self.oof_pred_model_repeats[val_index] += 1\n self.bagged_ensemble_model._add_child_times_to_bag(model=fold_model)\n\n def _predict_oof(self, fold_model, fold_ctx):\n time_train_end_fold = time.time()\n fold, folds_finished, folds_left, \\\n folds_to_fit, is_last_fold, model_name_suffix = self._get_fold_properties(fold_ctx)\n _, val_index = fold\n X_val_fold = self.X.iloc[val_index, :]\n y_val_fold = self.y.iloc[val_index]\n # Check to avoid unnecessarily predicting and saving a model\n # when an Exception is going to be raised later\n if self.time_limit is not None:\n if not is_last_fold:\n time_elapsed = time.time() - self.time_start\n time_left = self.time_limit - time_elapsed\n expected_time_required = time_elapsed * folds_to_fit / (folds_finished + 1)\n expected_remaining_time_required = expected_time_required * (folds_left - 1) / folds_to_fit\n if expected_remaining_time_required > time_left:\n raise TimeLimitExceeded\n pred_proba = fold_model.predict_proba(X_val_fold)\n fold_model.predict_time = time.time() - time_train_end_fold\n fold_model.val_score = fold_model.score_with_y_pred_proba(y=y_val_fold,\n y_pred_proba=pred_proba)\n fold_model.reduce_memory_size(remove_fit=True, remove_info=False, requires_save=True)\n if not self.bagged_ensemble_model.params.get('save_bag_folds', True):\n fold_model.model = None\n return fold_model, pred_proba\n\n @staticmethod\n def _get_fold_properties(fold_ctx):\n fold, folds_finished, folds_left, \\\n folds_to_fit, is_last_fold, model_name_suffix = [\n fold_ctx[f] for f in ['fold', 'folds_finished', 'folds_left', 'folds_to_fit', 'is_last_fold', 'model_name_suffix']]\n return fold, folds_finished, folds_left, folds_to_fit, is_last_fold, model_name_suffix\n\n\nclass SequentialLocalFoldFittingStrategy(LocalFoldFittingStrategy):\n \"\"\"\n This strategy fits the folds locally in a sequence.\n \"\"\"\n def schedule_fold_model_fit(self, fold_ctx):\n self.jobs.append(fold_ctx)\n\n def after_all_folds_scheduled(self):\n for job in self.jobs:\n self._fit_fold_model(job)\n\n def _fit_fold_model(self, fold_ctx):\n time_start_fold = time.time()\n time_limit_fold = self._get_fold_time_limit(fold_ctx)\n fold_model = self._fit(self.model_base, time_start_fold, time_limit_fold, fold_ctx, self.model_base_kwargs)\n fold_model, pred_proba = self._predict_oof(fold_model, fold_ctx)\n self._update_bagged_ensemble(fold_model, pred_proba, fold_ctx)\n\n def _fit(self, model_base, time_start_fold, time_limit_fold, fold_ctx, kwargs):\n fold, folds_finished, folds_left, folds_to_fit, is_last_fold, model_name_suffix = self._get_fold_properties(fold_ctx)\n train_index, val_index = fold\n X_fold, X_val_fold = self.X.iloc[train_index, :], self.X.iloc[val_index, :]\n y_fold, y_val_fold = self.y.iloc[train_index], self.y.iloc[val_index]\n fold_model = copy.deepcopy(model_base)\n fold_model.name = f'{fold_model.name}{model_name_suffix}'\n fold_model.set_contexts(self.bagged_ensemble_model.path + fold_model.name + os.path.sep)\n kwargs_fold = kwargs.copy()\n is_pseudo = self.X_pseudo is not None and self.y_pseudo is not None\n if self.sample_weight is not None:\n kwargs_fold['sample_weight'] = self.sample_weight[train_index]\n kwargs_fold['sample_weight_val'] = self.sample_weight[val_index]\n\n if is_pseudo:\n # TODO: Add support for sample_weight when pseudo is present\n raise Exception('Sample weights given, but not used due to pseudo labelled data being given.')\n else:\n kwargs_fold['sample_weight'] = self.sample_weight[train_index]\n kwargs_fold['sample_weight_val'] = self.sample_weight[val_index]\n\n if is_pseudo:\n logger.log(15, f'{len(self.X_pseudo)} extra rows of pseudolabeled data added to training set for {fold_model.name}')\n X_fold = pd.concat([X_fold, self.X_pseudo], axis=0, ignore_index=True)\n y_fold = pd.concat([y_fold, self.y_pseudo], axis=0, ignore_index=True)\n\n fold_model.fit(X=X_fold, y=y_fold, X_val=X_val_fold, y_val=y_val_fold, time_limit=time_limit_fold, **kwargs_fold)\n fold_model.fit_time = time.time() - time_start_fold\n return fold_model\n\n\ndef _ray_fit(model_base, bagged_ensemble_model_path,\n X, y, X_pseudo, y_pseudo,\n fold_ctx, time_limit_fold, num_cpus,\n save_bag_folds, kwargs_fold):\n logger.log(10, 'ray worker training')\n time_start_fold = time.time()\n fold, folds_finished, folds_left, \\\n folds_to_fit, is_last_fold, \\\n model_name_suffix = LocalFoldFittingStrategy._get_fold_properties(fold_ctx)\n train_index, val_index = fold\n fold_model = copy.deepcopy(model_base)\n fold_model.name = f'{fold_model.name}{model_name_suffix}'\n fold_model.set_contexts(bagged_ensemble_model_path + fold_model.name + os.path.sep)\n if type(X) == str and type(y) == str:\n with open(X, 'rb') as X_f, open(y, 'rb') as y_f:\n X = pickle.load(X_f)\n y = pickle.load(y_f)\n is_pseudo = False\n if X_pseudo is not None and y_pseudo is not None:\n if type(X_pseudo) == str and type(y_pseudo) == str:\n with open(X_pseudo, 'rb') as X_pseudo_f, open(y_pseudo, 'rb') as y_pseudo_f:\n X_pseudo = pickle.load(X_pseudo_f)\n y_pseudo = pickle.load(y_pseudo_f)\n is_pseudo = True\n\n X_fold, X_val_fold = X.iloc[train_index, :], X.iloc[val_index, :]\n y_fold, y_val_fold = y.iloc[train_index], y.iloc[val_index]\n if is_pseudo:\n logger.log(15, f'{len(X_pseudo)} extra rows of pseudolabeled data added to training set for {fold_model.name}')\n X_fold = pd.concat([X_fold, X_pseudo], axis=0, ignore_index=True)\n y_fold = pd.concat([y_fold, y_pseudo], axis=0, ignore_index=True)\n fold_model.fit(X=X_fold, y=y_fold, X_val=X_val_fold, y_val=y_val_fold,\n time_limit=time_limit_fold, num_cpus=num_cpus, **kwargs_fold)\n time_train_end_fold = time.time()\n fold_model.fit_time = time_train_end_fold - time_start_fold\n fold_model, pred_proba = _ray_predict_oof(fold_model, X_val_fold, y_val_fold,\n time_train_end_fold, num_cpus, save_bag_folds)\n fold_model.save()\n return fold_model.name, pred_proba, time_start_fold, \\\n time_train_end_fold, fold_model.predict_time\n\n\ndef _ray_predict_oof(fold_model, X_val_fold, y_val_fold, time_train_end_fold,\n num_cpus=-1, save_bag_folds=True):\n pred_proba = fold_model.predict_proba(X_val_fold, num_cpus=num_cpus)\n time_pred_end_fold = time.time()\n fold_model.predict_time = time_pred_end_fold - time_train_end_fold\n fold_model.val_score = fold_model.score_with_y_pred_proba(y=y_val_fold,\n y_pred_proba=pred_proba)\n fold_model.reduce_memory_size(remove_fit=True, remove_info=False, requires_save=True)\n if not save_bag_folds:\n fold_model.model = None\n return fold_model, pred_proba\n\n\nclass ParallelLocalFoldFittingStrategy(LocalFoldFittingStrategy):\n \"\"\"\n An implementation of LocalFoldFittingStrategy to train multiple folds in parallel.\n Folds are spread to cpu/gpu cores by ray tasks. \n Large data are stored in ray object store, which minimizes memory usage and unessary serializations.\n Trained models are saved to disk within each ray task.\n\n Parameters\n ----------\n num_folds_parallel: int\n Number of folds to train in parallel at once.\n Consider lower this parameter if encounter out of memory issue.\n max_memory_usage_ratio: float, default=0.8\n The ratio of max memory usage for parallel folding.\n If the estimated usage exceeds this ratio, will fall back to sequential folding.\n Attributes\n ----------\n num_cpus: int\n Number of cpu cores available.\n num_gpus: int\n Number of gpus available.\n num_parallel_jobs: int\n Number of parallel jobs to be executed once.\n max_memory_usage_ratio: float\n The ratio of max memory usage for parallel folding.\n time_start_fit: float\n The time of the first model starts training.\n time_end_fit: float\n The time of the last model finishes training.\n fit_time: float\n The amount of time used to fit all folds.\n predict_time: float\n The amount of time used to do out of folds predictions for all folds.\n \"\"\"\n def __init__(self, num_folds_parallel: int, max_memory_usage_ratio=0.8, **kwargs):\n super().__init__(**kwargs)\n self.ray = try_import_ray()\n self.num_cpus = get_cpu_count()\n self.num_gpus = None\n self.num_parallel_jobs = num_folds_parallel\n self.max_memory_usage_ratio = min(max_memory_usage_ratio, 1.0)\n self.time_start_fit = None\n self.time_end_fit = None\n self.fit_time = 0\n self.predict_time = 0\n # max_calls to guarantee release of gpu resource\n self._ray_fit = self.ray.remote(max_calls=1)(_ray_fit)\n # initialize the model base to get necessary info for estimating memory usage\n self._initialized_model_base = copy.deepcopy(self.model_base)\n self._initialized_model_base.initialize(X=self.X, y=self.y, **self.model_base_kwargs)\n\n def is_mem_sufficient(self, num_jobs):\n '''Check if the memory is sufficient to do parallel training'''\n model_mem_est = self._initialized_model_base.estimate_memory_usage(X=self.X)\n _, _, num_parallel_jobs = self._get_resource_suggestions(num_jobs)\n total_model_mem_est = num_parallel_jobs * model_mem_est\n data_mem_est = self._estimate_data_memory_usage()\n total_data_mem_est = num_parallel_jobs * data_mem_est\n mem_available = psutil.virtual_memory().available\n return (mem_available * self.max_memory_usage_ratio) > (total_model_mem_est + total_data_mem_est)\n\n def _estimate_data_memory_usage(self):\n X_mem = get_approximate_df_mem_usage(self.X).sum()\n y_mem = get_approximate_df_mem_usage(self.y.to_frame()).sum()\n return X_mem + y_mem\n\n def _get_gpu_count(self):\n if not self.num_gpus:\n _user_gpu_count = self.model_base.get_params().get('hyperparameters', {}). \\\n get('ag_args_fit', {}).get('num_gpus', 0)\n model_base_class_name = self.model_base.__class__.__name__\n # If user didn't specify num gpus and we are training text or image models,\n # use all gpus.\n if model_base_class_name in [TEXT_MODEL, IMAGE_MODEL] and _user_gpu_count == 0:\n _user_gpu_count = get_gpu_count()\n self.num_gpus = min(_user_gpu_count, get_gpu_count())\n\n def schedule_fold_model_fit(self, fold_ctx):\n self._get_gpu_count()\n if not self.ray.is_initialized():\n if self.num_gpus > 0:\n self.ray.init(log_to_driver=False, num_gpus=self.num_gpus)\n else:\n self.ray.init(log_to_driver=False)\n self.jobs.append(fold_ctx)\n\n def after_all_folds_scheduled(self):\n num_jobs = len(self.jobs)\n resources, _, _ = self._get_resource_suggestions(num_jobs)\n job_refs = []\n job_fold_map = {}\n # prepare shared data\n X, y, X_pseudo, y_pseudo = self._prepare_data()\n model_base_ref = self.ray.put(self.model_base)\n time_limit_fold = self._get_fold_time_limit(num_jobs)\n # spread the task\n for job in self.jobs:\n fold_ctx = job\n ref = self._fit(model_base_ref, X, y, X_pseudo, y_pseudo, time_limit_fold, fold_ctx, resources, self.model_base_kwargs)\n job_fold_map[ref] = fold_ctx\n job_refs.append(ref)\n\n # update ensemble whenver a model return\n unfinished = job_refs\n while unfinished:\n finished, unfinished = self.ray.wait(unfinished, num_returns=1)\n finished = finished[0]\n try:\n fold_model, pred_proba, time_start_fit, \\\n time_end_fit, predict_time = self.ray.get(finished)\n fold_ctx = job_fold_map.get(finished, None)\n assert fold_ctx is not None\n self._update_bagged_ensemble(fold_model, pred_proba, time_start_fit,\n time_end_fit, predict_time, fold_ctx)\n except TimeLimitExceeded:\n # Terminate all ray tasks because a fold failed\n self.ray.shutdown()\n raise TimeLimitExceeded\n # NotEnoughMemoryError is an autogluon custom error,\n # it predict memory usage before hand\n # MemoryError is the actual python memory error if the process failed\n except (NotEnoughMemoryError, MemoryError):\n error_msg = 'Consider decrease folds trained in parallel \\\n by passing num_fold_parallel to ag_args_ensemble \\\n when calling tabular.fit.\\n\\\n If none working, use sequential folding by passing \\\n SequentialLocalFoldFittingStrategy to ag_args_ensemble \\\n when calling tabular.fit and try again.'\n logger.warning(error_msg)\n # Terminate all ray tasks because a fold failed\n self.ray.shutdown()\n raise NotEnoughMemoryError\n except Exception as e:\n processed_exception = self._parse_ray_error(e)\n # Terminate all ray tasks because a fold failed\n self.ray.shutdown()\n raise processed_exception\n self.fit_time = 0\n if self.time_start_fit and self.time_end_fit:\n self.fit_time = self.time_end_fit - self.time_start_fit\n self.bagged_ensemble_model._add_parallel_child_times(self.fit_time, self.predict_time)\n\n def _fit(self, model_base_ref, X_ref, y_ref, X_pseudo_ref, y_pseudo_ref, time_limit_fold, fold_ctx, resources, kwargs):\n fold, folds_finished, folds_left, \\\n folds_to_fit, is_last_fold, \\\n model_name_suffix = self._get_fold_properties(fold_ctx)\n train_index, val_index = fold\n fold_ctx_ref = self.ray.put(fold_ctx)\n save_bag_folds = self.bagged_ensemble_model.params.get('save_bag_folds', True)\n kwargs_fold = kwargs.copy()\n is_pseudo = X_pseudo_ref is not None and y_pseudo_ref is not None\n if self.sample_weight is not None:\n if is_pseudo:\n # TODO: Add support for sample_weight when pseudo is present\n raise Exception('Sample weights given, but not used due to pseudo labelled data being given.')\n else:\n kwargs_fold['sample_weight'] = self.sample_weight[train_index]\n kwargs_fold['sample_weight_val'] = self.sample_weight[val_index]\n num_cpus = resources.get('num_cpus', 0)\n return self._ray_fit.options(**resources) \\\n .remote(model_base_ref, self.bagged_ensemble_model.path,\n X_ref, y_ref, X_pseudo_ref, y_pseudo_ref, fold_ctx_ref, time_limit_fold, num_cpus,\n save_bag_folds, kwargs_fold)\n\n def _update_bagged_ensemble(self, fold_model, pred_proba, time_start_fit,\n time_end_fit, predict_time, fold_ctx):\n _, val_index = fold_ctx['fold']\n self.models.append(fold_model)\n self.oof_pred_proba[val_index] += pred_proba\n self.oof_pred_model_repeats[val_index] += 1\n if self.time_start_fit:\n self.time_start_fit = min(time_start_fit, self.time_start_fit)\n else:\n self.time_start_fit = time_start_fit\n if self.time_end_fit:\n self.time_end_fit = max(time_end_fit, self.time_end_fit)\n else:\n self.time_end_fit = time_end_fit\n self.predict_time += predict_time\n\n def _get_fold_time_limit(self, num_jobs):\n _, batches, _ = self._get_resource_suggestions(num_jobs)\n time_elapsed = time.time() - self.time_start\n if self.time_limit is not None:\n time_left = self.time_limit - time_elapsed\n required_time_per_fold = time_left / batches\n time_limit_fold = required_time_per_fold * self.time_limit_fold_ratio\n if time_left <= 0:\n raise TimeLimitExceeded\n else:\n time_limit_fold = None\n return time_limit_fold\n\n def _get_resource_suggestions(self, num_jobs):\n # TODO: We need to handle user provide custom num_cpus\n cpu_per_job = max(1, int(self.num_cpus // self.num_parallel_jobs))\n gpu_per_job = 0\n resources = dict(num_cpus=cpu_per_job)\n num_parallel_jobs = min(self.num_parallel_jobs, self.num_cpus // cpu_per_job)\n self.num_parallel_jobs = num_parallel_jobs\n batches = math.ceil(num_jobs / num_parallel_jobs)\n if self.num_gpus and self.num_gpus > 0:\n gpu_per_job = self.num_gpus / self.num_parallel_jobs\n # For Image and Text model,\n # we always guarantee a task has at least one full gpu to use\n # FIXME: Avoid hardcoding model names.\n if self.model_base.__class__.__name__ in [TEXT_MODEL, IMAGE_MODEL]:\n gpu_per_job = max(1, math.ceil(gpu_per_job))\n resources = dict(num_cpus=cpu_per_job, num_gpus=gpu_per_job)\n return resources, batches, num_parallel_jobs\n\n def _prepare_data(self, in_mem=True):\n X_pseudo = None\n y_pseudo = None\n if in_mem:\n X = self.ray.put(self.X)\n y = self.ray.put(self.y)\n if self.X_pseudo is not None and self.y_pseudo is not None:\n X_pseudo = self.ray.put(self.X_pseudo)\n y_pseudo = self.ray.put(self.y_pseudo)\n else:\n X = 'X.pkl'\n y = 'y.pkl'\n utils = 'utils'\n X = os.path.join(self.bagged_ensemble_model.path, utils, X)\n y = os.path.join(self.bagged_ensemble_model.path, utils, y)\n with open(X, 'wb') as X_f, open(y, 'wb') as y_f:\n pickle.dump(self.X, X_f)\n pickle.dump(self.y, y_f)\n if self.X_pseudo is not None and self.y_pseudo is not None:\n X_pseudo = 'X_pseudo.pkl'\n y_pseudo = 'y_pseudo.pkl'\n X_pseudo = os.path.join(self.bagged_ensemble_model.path, utils, X_pseudo)\n y_pseudo = os.path.join(self.bagged_ensemble_model.path, utils, y_pseudo)\n return X, y, X_pseudo, y_pseudo\n\n def _parse_ray_error(self, e):\n error = str(e).lower()\n if 'cuda' in error and ('out of memory' in error or 'alloc' in error):\n default_error_msg = 'If none working, use sequential folding by passing \\\n SequentialLocalFoldFittingStrategy to ag_args_ensemble \\\n when calling tabular.fit and try again.'\n # FIXME: Avoid hardcoding model names.\n if self.model_base.__class__.__name__ in [TEXT_MODEL, IMAGE_MODEL]:\n error_msg = f'Out of CUDA memory while training \\\n {self.model_base.__class__.__name__}. \\\n Consider decrease batch size in hyperparameter and try again.\\n\\\n Or decrease folds trained in parallel by passing num_fold_parallel \\\n to ag_args_ensemble when calling tabular.fit if you have multiple \\\n gpus and try again'\n logger.warning(error_msg)\n # FIXME: Avoid hardcoding model names.\n elif self.model_base.__class__.__name__ in [TABULAR_MXNET_MODEL, TABULAR_FASTAI_MODEL]:\n error_msg = f'Out of CUDA memory while training \\\n {self.model_base.__class__.__name__}. \\\n Consider decrease batch size in hyperparameter and try again.\\n\\\n Or decrease folds trained in parallel by passing num_fold_parallel \\\n to ag_args_ensemble when calling tabular.fit and try again'\n logger.warning(error_msg)\n else:\n error_msg = f'Out of CUDA memory while training \\\n {self.model_base.__class__.__name__}. \\\n Consider decrease folds trained in parallel by passing \\\n num_fold_parallel to ag_args_ensemble when calling tabular.fit \\\n and try again'\n logger.warning(error_msg)\n logger.warning(default_error_msg)\n e = NotEnoughCudaMemoryError\n return e\n"
]
| [
[
"pandas.concat"
]
]
|
TontonTremblay/nerf_pl | [
"686e09b7c642778e226cdf83b70f47a6abeda73a"
]
| [
"eval.py"
]
| [
"import torch\nimport os\nimport numpy as np\nfrom collections import defaultdict\nfrom tqdm import tqdm\nimport imageio\nfrom argparse import ArgumentParser\n\nfrom models.rendering import render_rays\nfrom models.nerf import *\n\nfrom utils import load_ckpt\nimport metrics\n\nfrom datasets import dataset_dict\nfrom datasets.depth_utils import *\n\ntorch.backends.cudnn.benchmark = True\n\ndef get_opts():\n parser = ArgumentParser()\n parser.add_argument('--root_dir', type=str,\n default='/home/ubuntu/data/nerf_example_data/nerf_synthetic/lego',\n help='root directory of dataset')\n parser.add_argument('--dataset_name', type=str, default='blender',\n choices=['blender', 'llff', 'nvisii'],\n help='which dataset to validate')\n parser.add_argument('--scene_name', type=str, default='test',\n help='scene name, used as output folder name')\n parser.add_argument('--split', type=str, default='test',\n help='test or test_train')\n parser.add_argument('--img_wh', nargs=\"+\", type=int, default=[800, 800],\n help='resolution (img_w, img_h) of the image')\n parser.add_argument('--spheric_poses', default=False, action=\"store_true\",\n help='whether images are taken in spheric poses (for llff)')\n\n parser.add_argument('--N_samples', type=int, default=64,\n help='number of coarse samples')\n parser.add_argument('--N_importance', type=int, default=128,\n help='number of additional fine samples')\n parser.add_argument('--use_disp', default=False, action=\"store_true\",\n help='use disparity depth sampling')\n parser.add_argument('--chunk', type=int, default=32*1024*4,\n help='chunk size to split the input to avoid OOM')\n\n parser.add_argument('--ckpt_path', type=str, required=True,\n help='pretrained checkpoint path to load')\n\n parser.add_argument('--save_depth', default=False, action=\"store_true\",\n help='whether to save depth prediction')\n parser.add_argument('--depth_format', type=str, default='pfm',\n choices=['pfm', 'bytes'],\n help='which format to save')\n\n return parser.parse_args()\n\n\[email protected]_grad()\ndef batched_inference(models, embeddings,\n rays, N_samples, N_importance, use_disp,\n chunk,\n white_back):\n \"\"\"Do batched inference on rays using chunk.\"\"\"\n B = rays.shape[0]\n chunk = 1024*32\n results = defaultdict(list)\n for i in range(0, B, chunk):\n rendered_ray_chunks = \\\n render_rays(models,\n embeddings,\n rays[i:i+chunk],\n N_samples,\n use_disp,\n 0,\n 0,\n N_importance,\n chunk,\n white_back,\n test_time=True)\n\n for k, v in rendered_ray_chunks.items():\n results[k] += [v]\n\n for k, v in results.items():\n results[k] = torch.cat(v, 0)\n return results\n\n\nif __name__ == \"__main__\":\n args = get_opts()\n w, h = args.img_wh\n\n kwargs = {'root_dir': args.root_dir,\n 'split': args.split,\n 'img_wh': tuple(args.img_wh)}\n if args.dataset_name == 'llff':\n kwargs['spheric_poses'] = args.spheric_poses\n dataset = dataset_dict[args.dataset_name](**kwargs)\n\n embedding_xyz = Embedding(3, 10)\n embedding_dir = Embedding(3, 4)\n nerf_coarse = NeRF()\n nerf_fine = NeRF()\n load_ckpt(nerf_coarse, args.ckpt_path, model_name='nerf_coarse')\n load_ckpt(nerf_fine, args.ckpt_path, model_name='nerf_fine')\n nerf_coarse.cuda().eval()\n nerf_fine.cuda().eval()\n\n models = [nerf_coarse, nerf_fine]\n embeddings = [embedding_xyz, embedding_dir]\n\n imgs = []\n psnrs = []\n dir_name = f'results/{args.dataset_name}/{args.scene_name}'\n os.makedirs(dir_name, exist_ok=True)\n\n for i in tqdm(range(len(dataset))):\n sample = dataset[i]\n rays = sample['rays'].cuda()\n results = batched_inference(models, embeddings, rays,\n args.N_samples, args.N_importance, args.use_disp,\n args.chunk,\n dataset.white_back)\n\n img_pred = results['rgb_fine'].view(h, w, 3).cpu().numpy()\n \n if args.save_depth:\n depth_pred = results['depth_fine'].view(h, w).cpu().numpy()\n depth_pred = np.nan_to_num(depth_pred)\n if args.depth_format == 'pfm':\n save_pfm(os.path.join(dir_name, f'depth_{i:03d}.pfm'), depth_pred)\n else:\n with open(f'depth_{i:03d}', 'wb') as f:\n f.write(depth_pred.tobytes())\n\n img_pred_ = (img_pred*255).astype(np.uint8)\n imgs += [img_pred_]\n #imageio.imwrite(os.path.join(dir_name, f'{i:03d}.png'), img_pred_)\n\n if 'rgbs' in sample:\n rgbs = sample['rgbs']\n img_gt = rgbs.view(h, w, 3)\n import pdb; pdb.set_trace()\n psnrs += [metrics.psnr(img_gt, img_pred).item()]\n \n #imageio.mimsave(os.path.join(dir_name, f'{args.scene_name}.gif'), imgs, fps=30)\n \n if psnrs:\n mean_psnr = np.mean(psnrs)\n print(f'Mean PSNR : {mean_psnr:.2f}')\n"
]
| [
[
"torch.no_grad",
"torch.cat",
"numpy.nan_to_num",
"numpy.mean"
]
]
|
woithook/LIO | [
"8ec884ab7134a1ab7d8dd8922d4935e74f607446"
]
| [
"social_dilemmas/envs/cleanup.py"
]
| [
"import numpy as np\nimport random\n\nfrom social_dilemmas.constants import CLEANUP_MAP\nfrom social_dilemmas.envs.map_env import MapEnv, ACTIONS\nfrom social_dilemmas.envs.agent import CleanupAgent # CLEANUP_VIEW_SIZE\n\n# Add custom actions to the agent\nACTIONS['FIRE'] = 5 # length of firing beam\nACTIONS['CLEAN'] = 5 # length of cleanup beam\n\n# Custom colour dictionary\nCLEANUP_COLORS = {'C': [100, 255, 255], # Cyan cleaning beam\n 'S': [99, 156, 194], # Light grey-blue stream cell\n 'H': [113, 75, 24], # brown waste cells\n 'R': [99, 156, 194]} # Light grey-blue river cell\n\nSPAWN_PROB = [0, 0.005, 0.02, 0.05]\n\ncleanup_params_default = {'thresholdDepletion': 0.4,\n 'thresholdRestoration': 0.0,\n 'wasteSpawnProbability': 0.5,\n 'appleRespawnProbability': 0.05}\n\nclass CleanupEnv(MapEnv):\n\n def __init__(self, ascii_map=CLEANUP_MAP, num_agents=1, render=False,\n shuffle_spawn=True, global_ref_point=None,\n view_size=7, random_orientation=True,\n cleanup_params=cleanup_params_default,\n beam_width=3):\n self.global_ref_point = global_ref_point\n self.view_size = view_size\n super().__init__(ascii_map, num_agents, render,\n shuffle_spawn=shuffle_spawn,\n random_orientation=random_orientation,\n beam_width=beam_width)\n\n self.thresholdDepletion = cleanup_params['thresholdDepletion']\n self.thresholdRestoration = cleanup_params['thresholdRestoration']\n self.wasteSpawnProbability = cleanup_params['wasteSpawnProbability']\n self.appleRespawnProbability = cleanup_params['appleRespawnProbability']\n\n # compute potential waste area\n unique, counts = np.unique(self.base_map, return_counts=True)\n counts_dict = dict(zip(unique, counts))\n self.potential_waste_area = counts_dict.get('H', 0) + counts_dict.get('R', 0)\n self.current_apple_spawn_prob = self.appleRespawnProbability\n self.current_waste_spawn_prob = self.wasteSpawnProbability\n self.compute_probabilities()\n\n # make a list of the potential apple and waste spawn points\n self.apple_points = []\n self.waste_start_points = []\n self.waste_points = []\n self.river_points = []\n self.stream_points = []\n for row in range(self.base_map.shape[0]):\n for col in range(self.base_map.shape[1]):\n if self.base_map[row, col] == 'P':\n self.spawn_points.append([row, col])\n elif self.base_map[row, col] == 'B':\n self.apple_points.append([row, col])\n elif self.base_map[row, col] == 'S':\n self.stream_points.append([row, col])\n if self.base_map[row, col] == 'H':\n self.waste_start_points.append([row, col])\n if self.base_map[row, col] == 'H' or self.base_map[row, col] == 'R':\n self.waste_points.append([row, col])\n if self.base_map[row, col] == 'R':\n self.river_points.append([row, col])\n\n self.color_map.update(CLEANUP_COLORS)\n\n @property\n def action_space(self):\n agents = list(self.agents.values())\n return agents[0].action_space\n\n @property\n def observation_space(self):\n # FIXME(ev) this is an information leak\n agents = list(self.agents.values())\n return agents[0].observation_space\n\n def custom_reset(self):\n \"\"\"Initialize the walls and the waste\"\"\"\n for waste_start_point in self.waste_start_points:\n self.world_map[waste_start_point[0], waste_start_point[1]] = 'H'\n for river_point in self.river_points:\n self.world_map[river_point[0], river_point[1]] = 'R'\n for stream_point in self.stream_points:\n self.world_map[stream_point[0], stream_point[1]] = 'S'\n self.compute_probabilities()\n\n def custom_action(self, agent, action):\n \"\"\"Allows agents to take actions that are not move or turn\"\"\"\n updates = []\n if action == 'FIRE':\n agent.fire_beam('F')\n updates = self.update_map_fire(agent.get_pos().tolist(),\n agent.get_orientation(), ACTIONS['FIRE'],\n fire_char='F')\n elif action == 'CLEAN':\n agent.fire_beam('C')\n updates = self.update_map_fire(agent.get_pos().tolist(),\n agent.get_orientation(),\n ACTIONS['FIRE'],\n fire_char='C',\n cell_types=['H'],\n update_char=['R'],\n blocking_cells=['H'])\n return updates\n\n def custom_map_update(self):\n \"\"\"\"Update the probabilities and then spawn\"\"\"\n self.compute_probabilities()\n self.update_map(self.spawn_apples_and_waste())\n\n def setup_agents(self):\n \"\"\"Constructs all the agents in self.agent\"\"\"\n map_with_agents = self.get_map_with_agents()\n\n for i in range(self.num_agents):\n agent_id = 'agent-' + str(i)\n spawn_point = self.spawn_point()\n rotation = self.spawn_rotation()\n # grid = util.return_view(map_with_agents, spawn_point,\n # CLEANUP_VIEW_SIZE, CLEANUP_VIEW_SIZE)\n # agent = CleanupAgent(agent_id, spawn_point, rotation, grid)\n agent = CleanupAgent(agent_id, spawn_point, rotation, map_with_agents,\n global_ref_point=self.global_ref_point,\n view_len=self.view_size)\n self.agents[agent_id] = agent\n\n def spawn_apples_and_waste(self):\n spawn_points = []\n # spawn apples, multiple can spawn per step\n for i in range(len(self.apple_points)):\n row, col = self.apple_points[i]\n # don't spawn apples where agents already are\n if [row, col] not in self.agent_pos and self.world_map[row, col] != 'A':\n rand_num = np.random.rand(1)[0]\n if rand_num < self.current_apple_spawn_prob:\n spawn_points.append((row, col, 'A'))\n\n # spawn one waste point, only one can spawn per step\n if not np.isclose(self.current_waste_spawn_prob, 0):\n random.shuffle(self.waste_points)\n for i in range(len(self.waste_points)):\n row, col = self.waste_points[i]\n # don't spawn waste where it already is\n if self.world_map[row, col] != 'H':\n rand_num = np.random.rand(1)[0]\n if rand_num < self.current_waste_spawn_prob:\n spawn_points.append((row, col, 'H'))\n break\n return spawn_points\n\n def compute_probabilities(self):\n waste_density = 0\n if self.potential_waste_area > 0:\n waste_density = 1 - self.compute_permitted_area() / self.potential_waste_area\n if waste_density >= self.thresholdDepletion:\n self.current_apple_spawn_prob = 0\n self.current_waste_spawn_prob = 0\n else:\n self.current_waste_spawn_prob = self.wasteSpawnProbability\n if waste_density <= self.thresholdRestoration:\n self.current_apple_spawn_prob = self.appleRespawnProbability\n else:\n spawn_prob = (1 - (waste_density - self.thresholdRestoration)\n / (self.thresholdDepletion - self.thresholdRestoration)) \\\n * self.appleRespawnProbability\n self.current_apple_spawn_prob = spawn_prob\n\n def compute_permitted_area(self):\n \"\"\"How many cells can we spawn waste on?\"\"\"\n unique, counts = np.unique(self.world_map, return_counts=True)\n counts_dict = dict(zip(unique, counts))\n current_area = counts_dict.get('H', 0)\n free_area = self.potential_waste_area - current_area\n return free_area\n"
]
| [
[
"numpy.isclose",
"numpy.random.rand",
"numpy.unique"
]
]
|
willhyper/dnn | [
"244f04fdb91eeb3f27cca1a5132c9a486bbf788a"
]
| [
"randomized_svd.py"
]
| [
"import numpy as np\n\ndef randomized_svd(M, k):\n m, n = M.shape\n transpose = False\n if m < n:\n transpose = True\n M = M.T\n\n rand_matrix = np.random.normal(size=(M.shape[1], k)) # short side by k\n Q, _ = np.linalg.qr(M @ rand_matrix, mode='reduced') # long side by k\n smaller_matrix = Q.T @ M # k by short side\n U_hat, s, V = np.linalg.svd(smaller_matrix, full_matrices=False)\n U = Q @ U_hat\n\n if transpose:\n return V.T, s.T, U.T\n else:\n return U, s, V\n"
]
| [
[
"numpy.linalg.qr",
"numpy.random.normal",
"numpy.linalg.svd"
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.