repo_name
stringlengths
8
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
speglich/devito
[ "f535a44dff12de2837eb6e3217a65ffb2d371cb8" ]
[ "tests/test_dimension.py" ]
[ "from itertools import product\n\nimport numpy as np\nfrom sympy import And\nimport pytest\n\nfrom conftest import skipif\nfrom devito import (ConditionalDimension, Grid, Function, TimeFunction, SparseFunction, # noqa\n Eq, Operator, Constant, Dimension, SubDimension, switchconfig,\n SubDomain, Lt, Le, Gt, Ge, Ne, Buffer)\nfrom devito.ir.iet import Expression, Iteration, FindNodes, retrieve_iteration_tree\nfrom devito.symbolics import indexify, retrieve_functions\nfrom devito.types import Array\n\n\nclass TestBufferedDimension(object):\n\n def test_multi_buffer(self):\n grid = Grid((3, 3))\n f = TimeFunction(name=\"f\", grid=grid)\n g = TimeFunction(name=\"g\", grid=grid, save=Buffer(7))\n\n op = Operator([Eq(f.forward, 1), Eq(g, f.forward)])\n op(time_M=3)\n # f looped all time_order buffer and is 1 everywhere\n assert np.allclose(f.data, 1)\n # g looped indices 0 to 3, rest is still 0\n assert np.allclose(g.data[0:4], 1)\n assert np.allclose(g.data[4:], 0)\n\n def test_multi_buffer_long_time(self):\n grid = Grid((3, 3))\n time = grid.time_dim\n f = TimeFunction(name=\"f\", grid=grid)\n g = TimeFunction(name=\"g\", grid=grid, save=Buffer(7))\n\n op = Operator([Eq(f.forward, time), Eq(g, time+1)])\n op(time_M=20)\n # f[0] is time=19, f[1] is time=20\n assert np.allclose(f.data[0], 19)\n assert np.allclose(f.data[1], 20)\n # g is time 15 to 21 (loop twice the 7 buffer then 15->21)\n for i in range(7):\n assert np.allclose(g.data[i], 14+i+1)\n\n\nclass TestSubDimension(object):\n\n def test_interior(self):\n \"\"\"\n Tests application of an Operator consisting of a single equation\n over the ``interior`` subdomain.\n \"\"\"\n grid = Grid(shape=(4, 4, 4))\n x, y, z = grid.dimensions\n\n interior = grid.interior\n\n u = TimeFunction(name='u', grid=grid)\n\n eqn = [Eq(u.forward, u + 2, subdomain=interior)]\n\n op = Operator(eqn)\n op.apply(time_M=2)\n assert np.all(u.data[1, 1:-1, 1:-1, 1:-1] == 6.)\n assert np.all(u.data[1, :, 0] == 0.)\n assert np.all(u.data[1, :, -1] == 0.)\n assert np.all(u.data[1, :, :, 0] == 0.)\n assert np.all(u.data[1, :, :, -1] == 0.)\n\n def test_domain_vs_interior(self):\n \"\"\"\n Tests application of an Operator consisting of two equations, one\n over the whole domain (default), and one over the ``interior`` subdomain.\n \"\"\"\n grid = Grid(shape=(4, 4, 4))\n x, y, z = grid.dimensions\n t = grid.stepping_dim # noqa\n\n interior = grid.interior\n\n u = TimeFunction(name='u', grid=grid) # noqa\n eqs = [Eq(u.forward, u + 1),\n Eq(u.forward, u.forward + 2, subdomain=interior)]\n\n op = Operator(eqs, opt='noop')\n trees = retrieve_iteration_tree(op)\n assert len(trees) == 2\n\n op.apply(time_M=1)\n assert np.all(u.data[1, 0, :, :] == 1)\n assert np.all(u.data[1, -1, :, :] == 1)\n assert np.all(u.data[1, :, 0, :] == 1)\n assert np.all(u.data[1, :, -1, :] == 1)\n assert np.all(u.data[1, :, :, 0] == 1)\n assert np.all(u.data[1, :, :, -1] == 1)\n assert np.all(u.data[1, 1:3, 1:3, 1:3] == 3)\n\n def test_subdim_middle(self):\n \"\"\"\n Tests that instantiating SubDimensions using the classmethod\n constructors works correctly.\n \"\"\"\n grid = Grid(shape=(4, 4, 4))\n x, y, z = grid.dimensions\n t = grid.stepping_dim # noqa\n\n u = TimeFunction(name='u', grid=grid) # noqa\n xi = SubDimension.middle(name='xi', parent=x,\n thickness_left=1,\n thickness_right=1)\n eqs = [Eq(u.forward, u + 1)]\n eqs = [e.subs(x, xi) for e in eqs]\n\n op = Operator(eqs)\n\n u.data[:] = 1.0\n op.apply(time_M=1)\n assert np.all(u.data[1, 0, :, :] == 1)\n assert np.all(u.data[1, -1, :, :] == 1)\n assert np.all(u.data[1, 1:3, :, :] == 2)\n\n def test_symbolic_size(self):\n \"\"\"Check the symbolic size of all possible SubDimensions is as expected.\"\"\"\n grid = Grid(shape=(4,))\n x, = grid.dimensions\n thickness = 4\n\n xleft = SubDimension.left(name='xleft', parent=x, thickness=thickness)\n assert xleft.symbolic_size == xleft.thickness.left[0]\n\n xi = SubDimension.middle(name='xi', parent=x,\n thickness_left=thickness, thickness_right=thickness)\n assert xi.symbolic_size == (x.symbolic_max - x.symbolic_min -\n xi.thickness.left[0] - xi.thickness.right[0] + 1)\n\n xright = SubDimension.right(name='xright', parent=x, thickness=thickness)\n assert xright.symbolic_size == xright.thickness.right[0]\n\n def test_bcs(self):\n \"\"\"\n Tests application of an Operator consisting of multiple equations\n defined over different sub-regions, explicitly created through the\n use of SubDimensions.\n \"\"\"\n grid = Grid(shape=(20, 20))\n x, y = grid.dimensions\n t = grid.stepping_dim\n thickness = 4\n\n u = TimeFunction(name='u', save=None, grid=grid, space_order=0, time_order=1)\n\n xleft = SubDimension.left(name='xleft', parent=x, thickness=thickness)\n xi = SubDimension.middle(name='xi', parent=x,\n thickness_left=thickness, thickness_right=thickness)\n xright = SubDimension.right(name='xright', parent=x, thickness=thickness)\n\n yi = SubDimension.middle(name='yi', parent=y,\n thickness_left=thickness, thickness_right=thickness)\n\n t_in_centre = Eq(u[t+1, xi, yi], 1)\n leftbc = Eq(u[t+1, xleft, yi], u[t+1, xleft+1, yi] + 1)\n rightbc = Eq(u[t+1, xright, yi], u[t+1, xright-1, yi] + 1)\n\n op = Operator([t_in_centre, leftbc, rightbc])\n\n op.apply(time_m=1, time_M=1)\n\n assert np.all(u.data[0, :, 0:thickness] == 0.)\n assert np.all(u.data[0, :, -thickness:] == 0.)\n assert all(np.all(u.data[0, i, thickness:-thickness] == (thickness+1-i))\n for i in range(thickness))\n assert all(np.all(u.data[0, -i, thickness:-thickness] == (thickness+2-i))\n for i in range(1, thickness + 1))\n assert np.all(u.data[0, thickness:-thickness, thickness:-thickness] == 1.)\n\n def test_flow_detection_interior(self):\n \"\"\"\n Test detection of flow directions when SubDimensions are used\n (in this test they are induced by the ``interior`` subdomain).\n\n Stencil uses values at new timestep as well as those at previous ones\n This forces an evaluation order onto x.\n Weights are:\n\n x=0 x=1 x=2 x=3\n t=N 2 ---3\n v /\n t=N+1 o--+----4\n\n Flow dependency should traverse x in the negative direction\n\n x=2 x=3 x=4 x=5 x=6\n t=0 0 --- 0 -- 1 -- 0\n v / v / v /\n t=1 44 -+--- 11 -+--- 2--+ -- 0\n \"\"\"\n grid = Grid(shape=(10, 10))\n x, y = grid.dimensions\n\n interior = grid.interior\n\n u = TimeFunction(name='u', grid=grid, save=10, time_order=1, space_order=0)\n\n step = Eq(u.forward, 2*u\n + 3*u.subs(x, x+x.spacing)\n + 4*u.forward.subs(x, x+x.spacing),\n subdomain=interior)\n op = Operator(step)\n\n u.data[0, 5, 5] = 1.0\n op.apply(time_M=0)\n assert u.data[1, 5, 5] == 2\n assert u.data[1, 4, 5] == 11\n assert u.data[1, 3, 5] == 44\n assert u.data[1, 2, 5] == 4*44\n assert u.data[1, 1, 5] == 4*4*44\n\n # This point isn't updated because of the `interior` selection\n assert u.data[1, 0, 5] == 0\n\n assert np.all(u.data[1, 6:, :] == 0)\n assert np.all(u.data[1, :, 0:5] == 0)\n assert np.all(u.data[1, :, 6:] == 0)\n\n @pytest.mark.parametrize('exprs,expected,', [\n # Carried dependence in both /t/ and /x/\n (['Eq(u[t+1, x, y], u[t+1, x-1, y] + u[t, x, y])'], 'y'),\n (['Eq(u[t+1, x, y], u[t+1, x-1, y] + u[t, x, y], subdomain=interior)'], 'i0y'),\n # Carried dependence in both /t/ and /y/\n (['Eq(u[t+1, x, y], u[t+1, x, y-1] + u[t, x, y])'], 'x'),\n (['Eq(u[t+1, x, y], u[t+1, x, y-1] + u[t, x, y], subdomain=interior)'], 'i0x'),\n # Carried dependence in /y/, leading to separate /y/ loops, one\n # going forward, the other backward\n (['Eq(u[t+1, x, y], u[t+1, x, y-1] + u[t, x, y], subdomain=interior)',\n 'Eq(u[t+1, x, y], u[t+1, x, y+1] + u[t, x, y], subdomain=interior)'], 'i0x'),\n ])\n def test_iteration_property_parallel(self, exprs, expected):\n \"\"\"Tests detection of sequental and parallel Iterations when applying\n equations over different subdomains.\"\"\"\n grid = Grid(shape=(20, 20))\n x, y = grid.dimensions # noqa\n t = grid.time_dim # noqa\n\n interior = grid.interior # noqa\n\n u = TimeFunction(name='u', grid=grid, save=10, time_order=1) # noqa\n\n # List comprehension would need explicit locals/globals mappings to eval\n for i, e in enumerate(list(exprs)):\n exprs[i] = eval(e)\n\n op = Operator(exprs, opt='noop')\n iterations = FindNodes(Iteration).visit(op)\n assert all(i.is_Sequential for i in iterations if i.dim.name != expected)\n assert all(i.is_Parallel for i in iterations if i.dim.name == expected)\n\n @skipif(['device'])\n @pytest.mark.parametrize('exprs,expected,', [\n # All parallel, the innermost Iteration gets vectorized\n (['Eq(u[time, x, yleft], u[time, x, yleft] + 1.)'], ['yleft']),\n # All outers are parallel, carried dependence in `yleft`, so the middle\n # Iteration over `x` gets vectorized\n (['Eq(u[time, x, yleft], u[time, x, yleft+1] + 1.)'], ['x']),\n # Only the middle Iteration is parallel, so no vectorization (the Iteration\n # is left non-vectorised for OpenMP parallelism)\n (['Eq(u[time+1, x, yleft], u[time, x, yleft+1] + u[time+1, x, yleft+1])'], [])\n ])\n def test_iteration_property_vector(self, exprs, expected):\n \"\"\"Tests detection of vector Iterations when using subdimensions.\"\"\"\n grid = Grid(shape=(20, 20))\n x, y = grid.dimensions # noqa\n time = grid.time_dim # noqa\n\n # The leftmost 10 elements\n yleft = SubDimension.left(name='yleft', parent=y, thickness=10) # noqa\n\n u = TimeFunction(name='u', grid=grid, save=10, time_order=0, space_order=1) # noqa\n\n # List comprehension would need explicit locals/globals mappings to eval\n for i, e in enumerate(list(exprs)):\n exprs[i] = eval(e)\n\n op = Operator(exprs, opt='simd')\n iterations = FindNodes(Iteration).visit(op)\n vectorized = [i.dim.name for i in iterations if i.is_Vectorized]\n assert set(vectorized) == set(expected)\n\n def test_subdimmiddle_parallel(self):\n \"\"\"\n Tests application of an Operator consisting of a subdimension\n defined over different sub-regions, explicitly created through the\n use of SubDimensions.\n \"\"\"\n grid = Grid(shape=(20, 20))\n x, y = grid.dimensions\n t = grid.stepping_dim\n thickness = 4\n\n u = TimeFunction(name='u', save=None, grid=grid, space_order=0, time_order=1)\n\n xi = SubDimension.middle(name='xi', parent=x,\n thickness_left=thickness, thickness_right=thickness)\n\n yi = SubDimension.middle(name='yi', parent=y,\n thickness_left=thickness, thickness_right=thickness)\n\n # a 5 point stencil that can be computed in parallel\n centre = Eq(u[t+1, xi, yi], u[t, xi, yi] + u[t, xi-1, yi]\n + u[t, xi+1, yi] + u[t, xi, yi-1] + u[t, xi, yi+1])\n\n u.data[0, 10, 10] = 1.0\n\n op = Operator([centre])\n\n iterations = FindNodes(Iteration).visit(op)\n assert all(i.is_Affine and i.is_Parallel for i in iterations if i.dim in [xi, yi])\n\n op.apply(time_m=0, time_M=0)\n\n assert np.all(u.data[1, 9:12, 10] == 1.0)\n assert np.all(u.data[1, 10, 9:12] == 1.0)\n\n # Other than those, it should all be 0\n u.data[1, 9:12, 10] = 0.0\n u.data[1, 10, 9:12] = 0.0\n assert np.all(u.data[1, :] == 0)\n\n def test_subdimleft_parallel(self):\n \"\"\"\n Tests application of an Operator consisting of a subdimension\n defined over different sub-regions, explicitly created through the\n use of SubDimensions.\n\n This tests that flow direction is not being automatically inferred\n from whether the subdimension is on the left or right boundary.\n \"\"\"\n grid = Grid(shape=(20, 20))\n x, y = grid.dimensions\n t = grid.stepping_dim\n thickness = 4\n\n u = TimeFunction(name='u', save=None, grid=grid, space_order=0, time_order=1)\n\n xl = SubDimension.left(name='xl', parent=x, thickness=thickness)\n\n yi = SubDimension.middle(name='yi', parent=y,\n thickness_left=thickness, thickness_right=thickness)\n\n # Can be done in parallel\n eq = Eq(u[t+1, xl, yi], u[t, xl, yi] + 1)\n\n op = Operator([eq])\n\n iterations = FindNodes(Iteration).visit(op)\n assert all(i.is_Affine and i.is_Parallel for i in iterations if i.dim in [xl, yi])\n\n op.apply(time_m=0, time_M=0)\n\n assert np.all(u.data[1, 0:thickness, 0:thickness] == 0)\n assert np.all(u.data[1, 0:thickness, -thickness:] == 0)\n assert np.all(u.data[1, 0:thickness, thickness:-thickness] == 1)\n assert np.all(u.data[1, thickness+1:, :] == 0)\n\n def test_subdimmiddle_notparallel(self):\n \"\"\"\n Tests application of an Operator consisting of a subdimension\n defined over different sub-regions, explicitly created through the\n use of SubDimensions.\n\n Different from ``test_subdimmiddle_parallel`` because an interior\n dimension cannot be evaluated in parallel.\n \"\"\"\n grid = Grid(shape=(20, 20))\n x, y = grid.dimensions\n t = grid.stepping_dim\n thickness = 4\n\n u = TimeFunction(name='u', save=None, grid=grid, space_order=0, time_order=1)\n\n xi = SubDimension.middle(name='xi', parent=x,\n thickness_left=thickness, thickness_right=thickness)\n\n yi = SubDimension.middle(name='yi', parent=y,\n thickness_left=thickness, thickness_right=thickness)\n\n # flow dependencies in x and y which should force serial execution\n # in reverse direction\n centre = Eq(u[t+1, xi, yi], u[t, xi, yi] + u[t+1, xi+1, yi+1])\n u.data[0, 10, 10] = 1.0\n\n op = Operator([centre])\n\n iterations = FindNodes(Iteration).visit(op)\n assert all(i.is_Affine and i.is_Sequential for i in iterations if i.dim == xi)\n assert all(i.is_Affine and i.is_Parallel for i in iterations if i.dim == yi)\n\n op.apply(time_m=0, time_M=0)\n\n for i in range(4, 11):\n assert u.data[1, i, i] == 1.0\n u.data[1, i, i] = 0.0\n\n assert np.all(u.data[1, :] == 0)\n\n def test_subdimleft_notparallel(self):\n \"\"\"\n Tests application of an Operator consisting of a subdimension\n defined over different sub-regions, explicitly created through the\n use of SubDimensions.\n\n This tests that flow direction is not being automatically inferred\n from whether the subdimension is on the left or right boundary.\n \"\"\"\n grid = Grid(shape=(20, 20))\n x, y = grid.dimensions\n t = grid.stepping_dim\n thickness = 4\n\n u = TimeFunction(name='u', save=None, grid=grid, space_order=1, time_order=0)\n\n xl = SubDimension.left(name='xl', parent=x, thickness=thickness)\n\n yi = SubDimension.middle(name='yi', parent=y,\n thickness_left=thickness, thickness_right=thickness)\n\n # Flows inward (i.e. forward) rather than outward\n eq = Eq(u[t+1, xl, yi], u[t+1, xl-1, yi] + 1)\n\n op = Operator([eq])\n\n iterations = FindNodes(Iteration).visit(op)\n assert all(i.is_Affine and i.is_Sequential for i in iterations if i.dim == xl)\n assert all(i.is_Affine and i.is_Parallel for i in iterations if i.dim == yi)\n\n op.apply(time_m=1, time_M=1)\n\n assert all(np.all(u.data[0, :thickness, thickness+i] == [1, 2, 3, 4])\n for i in range(12))\n assert np.all(u.data[0, thickness:] == 0)\n assert np.all(u.data[0, :, thickness+12:] == 0)\n\n def test_subdim_fd(self):\n \"\"\"\n Test that the FD shortcuts are handled correctly with SubDimensions\n \"\"\"\n grid = Grid(shape=(20, 20))\n x, y = grid.dimensions\n\n u = TimeFunction(name='u', save=None, grid=grid, space_order=1, time_order=1)\n u.data[:] = 2.\n\n # Flows inward (i.e. forward) rather than outward\n eq = [Eq(u.forward, u.dx + u.dy, subdomain=grid.interior)]\n\n op = Operator(eq)\n\n op.apply(time_M=0)\n\n assert np.all(u.data[1, -1, :] == 2.)\n assert np.all(u.data[1, :, 0] == 2.)\n assert np.all(u.data[1, :, -1] == 2.)\n assert np.all(u.data[1, 0, :] == 2.)\n assert np.all(u.data[1, 1:18, 1:18] == 0.)\n\n def test_arrays_defined_over_subdims(self):\n \"\"\"\n Check code generation when an Array uses a SubDimension.\n \"\"\"\n grid = Grid(shape=(3,))\n x, = grid.dimensions\n xi, = grid.interior.dimensions\n\n f = Function(name='f', grid=grid)\n a = Array(name='a', dimensions=(xi,), dtype=grid.dtype)\n op = Operator([Eq(a[xi], 1), Eq(f, f + a[xi + 1], subdomain=grid.interior)],\n openmp=False)\n assert len(op.parameters) == 6\n # neither `x_size` nor `xi_size` are expected here\n assert not any(i.name in ('x_size', 'xi_size') for i in op.parameters)\n # Try running it -- regardless of what it will produce, this should run\n # ie, this checks this error isn't raised:\n # \"ValueError: No value found for parameter xi_size\"\n op()\n\n\nclass TestConditionalDimension(object):\n\n \"\"\"\n A collection of tests to check the correct functioning of ConditionalDimensions.\n \"\"\"\n\n def test_basic(self):\n nt = 19\n grid = Grid(shape=(11, 11))\n time = grid.time_dim\n\n u = TimeFunction(name='u', grid=grid)\n assert(grid.stepping_dim in u.indices)\n\n u2 = TimeFunction(name='u2', grid=grid, save=nt)\n assert(time in u2.indices)\n\n factor = 4\n time_subsampled = ConditionalDimension('t_sub', parent=time, factor=factor)\n usave = TimeFunction(name='usave', grid=grid, save=(nt+factor-1)//factor,\n time_dim=time_subsampled)\n assert(time_subsampled in usave.indices)\n\n eqns = [Eq(u.forward, u + 1.), Eq(u2.forward, u2 + 1.), Eq(usave, u)]\n op = Operator(eqns)\n op.apply(t_M=nt-2)\n assert np.all(np.allclose(u.data[(nt-1) % 3], nt-1))\n assert np.all([np.allclose(u2.data[i], i) for i in range(nt)])\n assert np.all([np.allclose(usave.data[i], i*factor)\n for i in range((nt+factor-1)//factor)])\n\n def test_basic_shuffles(self):\n \"\"\"\n Like ``test_basic``, but with different equation orderings. Nevertheless,\n we assert against the same exact values as in ``test_basic``, since we\n save `u`, not `u.forward`.\n \"\"\"\n nt = 19\n grid = Grid(shape=(11, 11))\n time = grid.time_dim\n\n u = TimeFunction(name='u', grid=grid)\n\n u2 = TimeFunction(name='u2', grid=grid, save=nt)\n\n factor = 4\n time_subsampled = ConditionalDimension('t_sub', parent=time, factor=factor)\n usave = TimeFunction(name='usave', grid=grid, save=(nt+factor-1)//factor,\n time_dim=time_subsampled)\n\n # Shuffle 1\n eqns = [Eq(usave, u), Eq(u.forward, u + 1.), Eq(u2.forward, u2 + 1.)]\n op = Operator(eqns)\n op.apply(t_M=nt-2)\n assert np.all(np.allclose(u.data[(nt-1) % 3], nt-1))\n assert np.all([np.allclose(u2.data[i], i) for i in range(nt)])\n assert np.all([np.allclose(usave.data[i], i*factor)\n for i in range((nt+factor-1)//factor)])\n\n # Shuffle 2\n usave.data[:] = 0.\n u.data[:] = 0.\n u2.data[:] = 0.\n eqns = [Eq(u.forward, u + 1.), Eq(usave, u), Eq(u2.forward, u2 + 1.)]\n op = Operator(eqns)\n op.apply(t_M=nt-2)\n assert np.all(np.allclose(u.data[(nt-1) % 3], nt-1))\n assert np.all([np.allclose(u2.data[i], i) for i in range(nt)])\n assert np.all([np.allclose(usave.data[i], i*factor)\n for i in range((nt+factor-1)//factor)])\n\n def test_spacial_subsampling(self):\n \"\"\"\n Test conditional dimension for the spatial ones.\n This test saves u every two grid points :\n u2[x, y] = u[2*x, 2*y]\n \"\"\"\n nt = 19\n grid = Grid(shape=(12, 12))\n time = grid.time_dim\n\n u = TimeFunction(name='u', grid=grid, save=nt)\n assert(grid.time_dim in u.indices)\n\n # Creates subsampled spatial dimensions and accordine grid\n dims = tuple([ConditionalDimension(d.name+'sub', parent=d, factor=2)\n for d in u.grid.dimensions])\n grid2 = Grid((6, 6), dimensions=dims, time_dimension=time)\n u2 = TimeFunction(name='u2', grid=grid2, save=nt)\n assert(time in u2.indices)\n\n eqns = [Eq(u.forward, u + 1.), Eq(u2, u)]\n op = Operator(eqns)\n op.apply(time_M=nt-2)\n # Verify that u2[x,y]= u[2*x, 2*y]\n assert np.allclose(u.data[:-1, 0:-1:2, 0:-1:2], u2.data[:-1, :, :])\n\n def test_time_subsampling_fd(self):\n nt = 19\n grid = Grid(shape=(11, 11))\n x, y = grid.dimensions\n time = grid.time_dim\n\n factor = 4\n time_subsampled = ConditionalDimension('t_sub', parent=time, factor=factor)\n usave = TimeFunction(name='usave', grid=grid, save=(nt+factor-1)//factor,\n time_dim=time_subsampled, time_order=2)\n\n dx2 = [indexify(i) for i in retrieve_functions(usave.dt2.evaluate)]\n assert dx2 == [usave[time_subsampled - 1, x, y],\n usave[time_subsampled + 1, x, y],\n usave[time_subsampled, x, y]]\n\n def test_subsampled_fd(self):\n \"\"\"\n Test that the FD shortcuts are handled correctly with ConditionalDimensions\n \"\"\"\n grid = Grid(shape=(21, 21))\n time = grid.time_dim\n # Creates subsampled spatial dimensions and accordine grid\n dims = tuple([ConditionalDimension(d.name+'sub', parent=d, factor=2)\n for d in grid.dimensions])\n grid2 = Grid((6, 6), dimensions=dims, time_dimension=time)\n u2 = TimeFunction(name='u2', grid=grid2, space_order=2, time_order=1)\n u2.data.fill(2.)\n eqns = [Eq(u2.forward, u2.dx + u2.dy)]\n op = Operator(eqns)\n op.apply(time_M=0, x_M=11, y_M=11)\n # Verify that u2 contains subsampled fd values\n assert np.all(u2.data[0, :, :] == 2.)\n assert np.all(u2.data[1, 0, 0] == 0.)\n assert np.all(u2.data[1, -1, -1] == -40.)\n assert np.all(u2.data[1, 0, -1] == -20.)\n assert np.all(u2.data[1, -1, 0] == -20.)\n assert np.all(u2.data[1, 1:-1, 0] == 0.)\n assert np.all(u2.data[1, 0, 1:-1] == 0.)\n assert np.all(u2.data[1, 1:-1, -1] == -20.)\n assert np.all(u2.data[1, -1, 1:-1] == -20.)\n assert np.all(u2.data[1, 1:4, 1:4] == 0.)\n\n # This test generates an openmp loop form which makes older gccs upset\n @switchconfig(openmp=False)\n def test_nothing_in_negative(self):\n \"\"\"Test the case where when the condition is false, there is nothing to do.\"\"\"\n nt = 4\n grid = Grid(shape=(11, 11))\n time = grid.time_dim\n\n u = TimeFunction(name='u', save=nt, grid=grid)\n assert(grid.time_dim in u.indices)\n\n factor = 4\n time_subsampled = ConditionalDimension('t_sub', parent=time, factor=factor)\n usave = TimeFunction(name='usave', grid=grid, save=(nt+factor-1)//factor,\n time_dim=time_subsampled)\n assert(time_subsampled in usave.indices)\n\n eqns = [Eq(usave, u)]\n op = Operator(eqns)\n\n u.data[:] = 1.0\n usave.data[:] = 0.0\n op.apply(time_m=1, time_M=1)\n assert np.allclose(usave.data, 0.0)\n\n op.apply(time_m=0, time_M=0)\n assert np.allclose(usave.data, 1.0)\n\n def test_laplace(self):\n grid = Grid(shape=(20, 20, 20))\n x, y, z = grid.dimensions\n time = grid.time_dim\n t = grid.stepping_dim\n tsave = ConditionalDimension(name='tsave', parent=time, factor=2)\n\n u = TimeFunction(name='u', grid=grid, save=None, time_order=2)\n usave = TimeFunction(name='usave', grid=grid, time_dim=tsave,\n time_order=0, space_order=0)\n\n steps = []\n # save of snapshot\n steps.append(Eq(usave, u))\n # standard laplace-like thing\n steps.append(Eq(u[t+1, x, y, z],\n u[t, x, y, z] - u[t-1, x, y, z]\n + u[t, x-1, y, z] + u[t, x+1, y, z]\n + u[t, x, y-1, z] + u[t, x, y+1, z]\n + u[t, x, y, z-1] + u[t, x, y, z+1]))\n\n op = Operator(steps)\n\n u.data[:] = 0.0\n u.data[0, 10, 10, 10] = 1.0\n op.apply(time_m=0, time_M=0)\n assert np.sum(u.data[0, :, :, :]) == 1.0\n assert np.sum(u.data[1, :, :, :]) == 7.0\n assert np.all(usave.data[0, :, :, :] == u.data[0, :, :, :])\n\n def test_as_expr(self):\n nt = 19\n grid = Grid(shape=(11, 11))\n time = grid.time_dim\n\n u = TimeFunction(name='u', grid=grid)\n assert(grid.stepping_dim in u.indices)\n\n u2 = TimeFunction(name='u2', grid=grid, save=nt)\n assert(time in u2.indices)\n\n factor = 4\n time_subsampled = ConditionalDimension('t_sub', parent=time, factor=factor)\n usave = TimeFunction(name='usave', grid=grid, save=(nt+factor-1)//factor,\n time_dim=time_subsampled)\n assert(time_subsampled in usave.indices)\n\n eqns = [Eq(u.forward, u + 1.), Eq(u2.forward, u2 + 1.),\n Eq(usave, time_subsampled * u)]\n op = Operator(eqns)\n op.apply(t=nt-2)\n assert np.all(np.allclose(u.data[(nt-1) % 3], nt-1))\n assert np.all([np.allclose(u2.data[i], i) for i in range(nt)])\n assert np.all([np.allclose(usave.data[i], i*factor*i)\n for i in range((nt+factor-1)//factor)])\n\n def test_shifted(self):\n nt = 19\n grid = Grid(shape=(11, 11))\n time = grid.time_dim\n\n u = TimeFunction(name='u', grid=grid)\n assert(grid.stepping_dim in u.indices)\n\n u2 = TimeFunction(name='u2', grid=grid, save=nt)\n assert(time in u2.indices)\n\n factor = 4\n time_subsampled = ConditionalDimension('t_sub', parent=time, factor=factor)\n usave = TimeFunction(name='usave', grid=grid, save=2, time_dim=time_subsampled)\n assert(time_subsampled in usave.indices)\n\n t_sub_shift = Constant(name='t_sub_shift', dtype=np.int32)\n\n eqns = [Eq(u.forward, u + 1.), Eq(u2.forward, u2 + 1.),\n Eq(usave.subs(time_subsampled, time_subsampled - t_sub_shift), u)]\n op = Operator(eqns)\n\n # Starting at time_m=10, so time_subsampled - t_sub_shift is in range\n op.apply(time_m=10, time_M=nt-2, t_sub_shift=3)\n assert np.all(np.allclose(u.data[0], 8))\n assert np.all([np.allclose(u2.data[i], i - 10) for i in range(10, nt)])\n assert np.all([np.allclose(usave.data[i], 2+i*factor) for i in range(2)])\n\n def test_no_index(self):\n \"\"\"Test behaviour when the ConditionalDimension is used as a symbol in\n an expression.\"\"\"\n nt = 19\n grid = Grid(shape=(11, 11))\n time = grid.time_dim\n\n u = TimeFunction(name='u', grid=grid)\n assert(grid.stepping_dim in u.indices)\n\n v = Function(name='v', grid=grid)\n\n factor = 4\n time_subsampled = ConditionalDimension('t_sub', parent=time, factor=factor)\n\n eqns = [Eq(u.forward, u + 1), Eq(v, v + u*u*time_subsampled)]\n op = Operator(eqns)\n op.apply(t_M=nt-2)\n assert np.all(np.allclose(u.data[(nt-1) % 3], nt-1))\n # expected result is 1024\n # v = u[0]**2 * 0 + u[4]**2 * 1 + u[8]**2 * 2 + u[12]**2 * 3 + u[16]**2 * 4\n # with u[t] = t\n # v = 16 * 1 + 64 * 2 + 144 * 3 + 256 * 4 = 1600\n assert np.all(np.allclose(v.data, 1600))\n\n def test_no_index_sparse(self):\n \"\"\"Test behaviour when the ConditionalDimension is used as a symbol in\n an expression over sparse data objects.\"\"\"\n grid = Grid(shape=(4, 4), extent=(3.0, 3.0))\n time = grid.time_dim\n\n f = TimeFunction(name='f', grid=grid, save=1)\n f.data[:] = 0.\n\n coordinates = [(0.5, 0.5), (0.5, 2.5), (2.5, 0.5), (2.5, 2.5)]\n sf = SparseFunction(name='sf', grid=grid, npoint=4, coordinates=coordinates)\n sf.data[:] = 1.\n sd = sf.dimensions[sf._sparse_position]\n\n # We want to write to `f` through `sf` so that we obtain the\n # following 4x4 grid (the '*' show the position of the sparse points)\n # We do that by emulating an injection\n #\n # 0 --- 0 --- 0 --- 0\n # | * | | * |\n # 0 --- 1 --- 1 --- 0\n # | | | |\n # 0 --- 1 --- 1 --- 0\n # | * | | * |\n # 0 --- 0 --- 0 --- 0\n\n radius = 1\n indices = [(i, i+radius) for i in sf._coordinate_indices]\n bounds = [i.symbolic_size - radius for i in grid.dimensions]\n\n eqs = []\n for e, i in enumerate(product(*indices)):\n args = [j > 0 for j in i]\n args.extend([j < k for j, k in zip(i, bounds)])\n condition = And(*args, evaluate=False)\n cd = ConditionalDimension('sfc%d' % e, parent=sd, condition=condition)\n index = [time] + list(i)\n eqs.append(Eq(f[index], f[index] + sf[cd]))\n\n op = Operator(eqs)\n op.apply(time=0)\n\n assert np.all(f.data[0, 1:-1, 1:-1] == 1.)\n assert np.all(f.data[0, 0] == 0.)\n assert np.all(f.data[0, -1] == 0.)\n assert np.all(f.data[0, :, 0] == 0.)\n assert np.all(f.data[0, :, -1] == 0.)\n\n def test_symbolic_factor(self):\n \"\"\"\n Test ConditionalDimension with symbolic factor (provided as a Constant).\n \"\"\"\n g = Grid(shape=(4, 4, 4))\n\n u = TimeFunction(name='u', grid=g, time_order=0)\n\n fact = Constant(name='fact', dtype=np.int32, value=4)\n tsub = ConditionalDimension(name='tsub', parent=g.time_dim, factor=fact)\n usave = TimeFunction(name='usave', grid=g, time_dim=tsub, save=4)\n\n op = Operator([Eq(u, u + 1), Eq(usave, u)])\n\n op.apply(time=7) # Use `fact`'s default value, 4\n assert np.all(usave.data[0] == 1)\n assert np.all(usave.data[1] == 5)\n\n u.data[:] = 0.\n op.apply(time=7, fact=2)\n assert np.all(usave.data[0] == 1)\n assert np.all(usave.data[1] == 3)\n assert np.all(usave.data[2] == 5)\n assert np.all(usave.data[3] == 7)\n\n def test_implicit_dims(self):\n \"\"\"\n Test ConditionalDimension as an implicit dimension for an equation.\n \"\"\"\n\n # This test makes an Operator that should create a vector of increasing\n # integers, but stop incrementing when a certain stop value is reached\n\n shape = (50,)\n stop_value = 20\n\n time = Dimension(name='time')\n f = TimeFunction(name='f', shape=shape, dimensions=[time])\n\n # The condition to stop incrementing\n cond = ConditionalDimension(name='cond',\n parent=time, condition=f[time] < stop_value)\n\n eqs = [Eq(f.forward, f), Eq(f.forward, f.forward + 1, implicit_dims=[cond])]\n op = Operator(eqs)\n op.apply(time_M=shape[0] - 2)\n\n # Make the same calculation in python to assert the result\n F = np.zeros(shape[0])\n for i in range(shape[0]):\n F[i] = i if i < stop_value else stop_value\n\n assert np.all(f.data == F)\n\n def test_stepping_dim_in_condition_lowering(self):\n \"\"\"\n Check that the compiler performs lowering on conditions\n with TimeDimensions and generates the expected code::\n\n if (g[t][x + 1][y + 1] <= 10){ if (g[t0][x + 1][y + 1] <= 10){\n ... --> ...\n } }\n\n This test increments a function by one at every timestep until it is\n less-or-equal to 10 (g<=10) while although operator runs for 13 timesteps.\n \"\"\"\n grid = Grid(shape=(4, 4))\n _, y = grid.dimensions\n\n ths = 10\n g = TimeFunction(name='g', grid=grid)\n\n ci = ConditionalDimension(name='ci', parent=y, condition=Le(g, ths))\n\n op = Operator(Eq(g.forward, g + 1, implicit_dims=ci))\n\n op.apply(time_M=ths+3)\n assert np.all(g.data[0, :, :] == ths)\n assert np.all(g.data[1, :, :] == ths + 1)\n assert 'if (g[t0][x + 1][y + 1] <= 10)\\n'\n '{\\n g[t1][x + 1][y + 1] = g[t0][x + 1][y + 1] + 1' in str(op.ccode)\n\n def test_expr_like_lowering(self):\n \"\"\"\n Test the lowering of an expr-like ConditionalDimension's condition.\n This test makes an Operator that should indexify and lower the condition\n passed in the Conditional Dimension\n \"\"\"\n\n grid = Grid(shape=(3, 3))\n g1 = Function(name='g1', grid=grid)\n g2 = Function(name='g2', grid=grid)\n\n g1.data[:] = 0.49\n g2.data[:] = 0.49\n x, y = grid.dimensions\n ci = ConditionalDimension(name='ci', parent=y, condition=Le((g1 + g2),\n 1.01*(g1 + g2)))\n\n f = Function(name='f', shape=grid.shape, dimensions=(x, ci))\n Operator(Eq(f, g1+g2)).apply()\n\n assert np.all(f.data[:] == g1.data[:] + g2.data[:])\n\n @pytest.mark.parametrize('setup_rel, rhs, c1, c2, c3, c4', [\n # Relation, RHS, c1 to c4 used as indexes in assert\n (Lt, 3, 2, 4, 4, -1), (Le, 2, 2, 4, 4, -1), (Ge, 3, 4, 6, 1, 4),\n (Gt, 2, 4, 6, 1, 4), (Ne, 5, 2, 6, 1, 2)\n ])\n def test_relational_classes(self, setup_rel, rhs, c1, c2, c3, c4):\n \"\"\"\n Test ConditionalDimension using conditions based on Relations over SubDomains.\n \"\"\"\n\n class InnerDomain(SubDomain):\n name = 'inner'\n\n def define(self, dimensions):\n return {d: ('middle', 2, 2) for d in dimensions}\n\n inner_domain = InnerDomain()\n grid = Grid(shape=(8, 8), subdomains=(inner_domain,))\n g = Function(name='g', grid=grid)\n g2 = Function(name='g2', grid=grid)\n\n for i in [g, g2]:\n i.data[:4, :4] = 1\n i.data[4:, :4] = 2\n i.data[4:, 4:] = 3\n i.data[:4, 4:] = 4\n\n xi, yi = grid.subdomains['inner'].dimensions\n\n cond = setup_rel(0.25*g + 0.75*g2, rhs, subdomain=grid.subdomains['inner'])\n ci = ConditionalDimension(name='ci', parent=yi, condition=cond)\n f = Function(name='f', shape=grid.shape, dimensions=(xi, ci))\n\n eq1 = Eq(f, 0.4*g + 0.6*g2)\n eq2 = Eq(f, 5)\n\n Operator([eq1, eq2]).apply()\n assert np.all(f.data[2:6, c1:c2] == 5.)\n assert np.all(f.data[:, c3:c4] < 5.)\n\n def test_from_cond_to_param(self):\n \"\"\"\n Test that Functions appearing in the condition of a ConditionalDimension\n but not explicitly in an Eq are actually part of the Operator input\n (stems from issue #1298).\n \"\"\"\n grid = Grid(shape=(8, 8))\n x, y = grid.dimensions\n\n g = Function(name='g', grid=grid)\n h = Function(name='h', grid=grid)\n ci = ConditionalDimension(name='ci', parent=y, condition=Lt(g, 2 + h))\n f = Function(name='f', shape=grid.shape, dimensions=(x, ci))\n\n for _ in range(5):\n # issue #1298 was non deterministic\n Operator(Eq(f, 5)).apply()\n\n @skipif('device')\n def test_no_fusion_simple(self):\n \"\"\"\n If ConditionalDimensions are present, then Clusters must not be fused so\n that ultimately Eqs get scheduled to different loop nests.\n \"\"\"\n grid = Grid(shape=(4, 4, 4))\n time = grid.time_dim\n\n f = TimeFunction(name='f', grid=grid)\n g = Function(name='g', grid=grid)\n h = Function(name='h', grid=grid)\n\n # No ConditionalDimensions yet. Will be fused and optimized\n eqns = [Eq(f.forward, f + 1),\n Eq(h, f + 1),\n Eq(g, f + 1)]\n\n op = Operator(eqns)\n\n exprs = FindNodes(Expression).visit(op._func_table['bf0'].root)\n assert len(exprs) == 4\n assert exprs[1].expr.rhs is exprs[0].output\n assert exprs[2].expr.rhs is exprs[0].output\n assert exprs[3].expr.rhs is exprs[0].output\n\n # Now with a ConditionalDimension. No fusion, no optimization\n ctime = ConditionalDimension(name='ctime', parent=time, condition=time > 4)\n\n eqns = [Eq(f.forward, f + 1),\n Eq(h, f + 1),\n Eq(g, f + 1, implicit_dims=[ctime])]\n\n op = Operator(eqns)\n exprs = FindNodes(Expression).visit(op._func_table['bf0'].root)\n assert len(exprs) == 3\n assert exprs[1].expr.rhs is exprs[0].output\n assert exprs[2].expr.rhs is exprs[0].output\n exprs = FindNodes(Expression).visit(op._func_table['bf1'].root)\n assert len(exprs) == 1\n\n @skipif('device')\n def test_no_fusion_convoluted(self):\n \"\"\"\n Conceptually like `test_no_fusion_simple`, but with more expressions\n and non-trivial data flow.\n \"\"\"\n grid = Grid(shape=(4, 4, 4))\n time = grid.time_dim\n\n f = TimeFunction(name='f', grid=grid)\n g = Function(name='g', grid=grid)\n h = Function(name='h', grid=grid)\n\n ctime = ConditionalDimension(name='ctime', parent=time, condition=time > 4)\n\n eqns = [Eq(f.forward, f + 1),\n Eq(h, f + 1),\n Eq(g, f + 1, implicit_dims=[ctime]),\n Eq(f.forward, f + 1, implicit_dims=[ctime]),\n Eq(f.forward, f + 1),\n Eq(g, f + 1)]\n\n op = Operator(eqns)\n\n exprs = FindNodes(Expression).visit(op._func_table['bf0'].root)\n assert len(exprs) == 3\n assert exprs[1].expr.rhs is exprs[0].output\n assert exprs[2].expr.rhs is exprs[0].output\n\n exprs = FindNodes(Expression).visit(op._func_table['bf1'].root)\n assert len(exprs) == 3\n\n exprs = FindNodes(Expression).visit(op._func_table['bf2'].root)\n assert len(exprs) == 3\n assert exprs[1].expr.rhs is exprs[0].output\n assert exprs[2].expr.rhs is exprs[0].output\n\n\nclass TestMashup(object):\n\n \"\"\"\n Check the correct functioning of the compiler in presence of many Dimension types.\n \"\"\"\n\n def test_topofusion_w_subdims_conddims(self):\n \"\"\"\n Check that topological fusion works across guarded Clusters over different\n iteration spaces and in presence of anti-dependences.\n\n This test uses both SubDimensions (via SubDomains) and ConditionalDimensions.\n \"\"\"\n grid = Grid(shape=(4, 4, 4))\n time = grid.time_dim\n\n f = TimeFunction(name='f', grid=grid, time_order=2)\n g = TimeFunction(name='g', grid=grid, time_order=2)\n h = TimeFunction(name='h', grid=grid, time_order=2)\n fsave = TimeFunction(name='fsave', grid=grid, time_order=2, save=5)\n gsave = TimeFunction(name='gsave', grid=grid, time_order=2, save=5)\n\n ctime = ConditionalDimension(name='ctime', parent=time, condition=time > 4)\n\n eqns = [Eq(f.forward, f + 1),\n Eq(g.forward, g + 1),\n Eq(fsave, f.dt2, implicit_dims=[ctime]),\n Eq(h, f + g, subdomain=grid.interior),\n Eq(gsave, g.dt2, implicit_dims=[ctime])]\n\n op = Operator(eqns)\n\n # Check generated code -- expect the gsave equation to be scheduled together\n # in the same loop nest with the fsave equation\n assert len(op._func_table) == 3\n\n exprs = FindNodes(Expression).visit(op._func_table['bf0'].root)\n assert len(exprs) == 2\n assert exprs[0].write is f\n assert exprs[1].write is g\n\n exprs = FindNodes(Expression).visit(op._func_table['bf1'].root)\n assert len(exprs) == 3\n assert exprs[1].write is fsave\n assert exprs[2].write is gsave\n\n exprs = FindNodes(Expression).visit(op._func_table['bf2'].root)\n assert len(exprs) == 1\n assert exprs[0].write is h\n\n def test_topofusion_w_subdims_conddims_v2(self):\n \"\"\"\n Like `test_topofusion_w_subdims_conddims` but with more SubDomains,\n so we expect fewer loop nests.\n \"\"\"\n grid = Grid(shape=(4, 4, 4))\n time = grid.time_dim\n\n f = TimeFunction(name='f', grid=grid, time_order=2)\n g = TimeFunction(name='g', grid=grid, time_order=2)\n h = TimeFunction(name='h', grid=grid, time_order=2)\n fsave = TimeFunction(name='fsave', grid=grid, time_order=2, save=5)\n gsave = TimeFunction(name='gsave', grid=grid, time_order=2, save=5)\n\n ctime = ConditionalDimension(name='ctime', parent=time, condition=time > 4)\n\n eqns = [Eq(f.forward, f + 1, subdomain=grid.interior),\n Eq(g.forward, g + 1, subdomain=grid.interior),\n Eq(fsave, f.dt2, implicit_dims=[ctime]),\n Eq(h, f + g, subdomain=grid.interior),\n Eq(gsave, g.dt2, implicit_dims=[ctime])]\n\n op = Operator(eqns)\n\n # Check generated code -- expect the gsave equation to be scheduled together\n # in the same loop nest with the fsave equation\n assert len(op._func_table) == 2\n assert len(FindNodes(Expression).visit(op._func_table['bf0'].root)) == 3\n assert len(FindNodes(Expression).visit(op._func_table['bf1'].root)) == 2 + 1 # r0\n\n def test_topofusion_w_subdims_conddims_v3(self):\n \"\"\"\n Like `test_topofusion_w_subdims_conddims_v2` but with an extra anti-dependence,\n which causes scheduling over more loop nests.\n \"\"\"\n grid = Grid(shape=(4, 4, 4))\n time = grid.time_dim\n\n f = TimeFunction(name='f', grid=grid, time_order=2)\n g = TimeFunction(name='g', grid=grid, time_order=2)\n h = TimeFunction(name='h', grid=grid, time_order=2)\n fsave = TimeFunction(name='fsave', grid=grid, time_order=2, save=5)\n gsave = TimeFunction(name='gsave', grid=grid, time_order=2, save=5)\n\n ctime = ConditionalDimension(name='ctime', parent=time, condition=time > 4)\n\n eqns = [Eq(f.forward, f + 1, subdomain=grid.interior),\n Eq(g.forward, g + 1, subdomain=grid.interior),\n Eq(fsave, f.dt2, implicit_dims=[ctime]),\n Eq(h, f.dt2.dx + g, subdomain=grid.interior),\n Eq(gsave, g.dt2, implicit_dims=[ctime])]\n\n op = Operator(eqns)\n\n # Check generated code -- expect the gsave equation to be scheduled together\n # in the same loop nest with the fsave equation\n assert len(op._func_table) == 3\n\n exprs = FindNodes(Expression).visit(op._func_table['bf0'].root)\n assert len(exprs) == 2\n assert exprs[0].write is f\n assert exprs[1].write is g\n\n exprs = FindNodes(Expression).visit(op._func_table['bf1'].root)\n assert len(exprs) == 3\n assert exprs[1].write is fsave\n assert exprs[2].write is gsave\n\n exprs = FindNodes(Expression).visit(op._func_table['bf2'].root)\n assert len(exprs) == 2\n assert exprs[1].write is h\n" ]
[ [ "numpy.allclose", "numpy.sum", "numpy.all", "numpy.zeros" ] ]
Bartdoekemeijer/FLORIS
[ "be3c9fbb559354b5bf848792d84caff90606ed05" ]
[ "tests/reg_tests/cumulative_curl_regression_test.py" ]
[ "# Copyright 2021 NREL\n\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# the License at 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n\n# See https://floris.readthedocs.io for documentation\n\nimport numpy as np\n\nfrom floris.simulation import Floris\nfrom floris.simulation import Ct, power, axial_induction, average_velocity\nfrom tests.conftest import N_TURBINES, N_WIND_DIRECTIONS, N_WIND_SPEEDS, print_test_values, assert_results_arrays\n\nDEBUG = True\nVELOCITY_MODEL = \"cc\"\nDEFLECTION_MODEL = \"gauss\"\n\nbaseline = np.array(\n [\n # 8 m/s\n [\n [7.9803783, 0.7634300, 1695368.7987130, 0.2568077],\n [5.3585771, 0.8698045, 492577.1572448, 0.3195870],\n [4.9669368, 0.8944963, 379718.4177412, 0.3375933],\n ],\n # 9 m/s\n [\n [8.9779256, 0.7625731, 2413658.0981405, 0.2563676],\n [6.0299374, 0.8340431, 719536.2896199, 0.2963110],\n [5.5776779, 0.8570341, 560907.3153174, 0.3109458],\n ],\n # 10 m/s\n [\n [9.9754729, 0.7527803, 3306006.2306084, 0.2513940],\n [6.7205268, 0.8035032, 1012640.0064192, 0.2783602],\n [6.2110904, 0.8256933, 792936.0055473, 0.2912497],\n ],\n # 11 m/s\n [\n [10.9730201, 0.7304328, 4373596.1594956, 0.2404007],\n [7.4516751, 0.7774337, 1381908.5141696, 0.2641154],\n [6.8606000, 0.7978670, 1077836.5443900, 0.2752040],\n ]\n ]\n)\n\nyawed_baseline = np.array(\n [\n # 8 m/s\n [\n [7.9803783, 0.7605249, 1683956.5765064, 0.2548147],\n [5.4029703, 0.8670436, 505567.9316776, 0.3176841],\n [4.9742156, 0.8939700, 381463.8369041, 0.3371887],\n ],\n # 9 m/s\n [\n [8.9779256, 0.7596713, 2397236.5542849, 0.2543815],\n [6.0798421, 0.8317429, 739756.7356164, 0.2949042],\n [5.5879702, 0.8565074, 564477.6027506, 0.3105979],\n ],\n # 10 m/s\n [\n [9.9754729, 0.7499157, 3283591.8023665, 0.2494847],\n [6.7754450, 0.8012935, 1038201.4571916, 0.2771174],\n [6.2236744, 0.8251133, 798034.8027193, 0.2909027],\n ],\n # 11 m/s\n [\n [10.9730201, 0.7276532, 4344222.0129382, 0.2386508],\n [7.5103951, 0.7755790, 1413728.7289467, 0.2631345],\n [6.8746872, 0.7973002, 1084393.3749950, 0.2748890],\n ]\n ]\n)\n\nyaw_added_recovery_baseline = np.array(\n [\n # 8 m/s\n [\n [7.9803783, 0.7605249, 1683956.5765064, 0.2548147],\n [5.4219904, 0.8658607, 511133.7736997, 0.3168748],\n [4.9902533, 0.8928102, 385309.6126320, 0.3363008],\n ],\n # 9 m/s\n [\n [8.9779256, 0.7596713, 2397236.5542849, 0.2543815],\n [6.1011855, 0.8307591, 748404.6404163, 0.2943055],\n [5.6072171, 0.8555225, 571154.1495386, 0.3099490],\n ],\n # 10 m/s\n [\n [9.9754729, 0.7499157, 3283591.8023665, 0.2494847],\n [6.7984638, 0.8003672, 1048915.4794254, 0.2765986],\n [6.2452220, 0.8241201, 806765.4479110, 0.2903098],\n ],\n # 11 m/s\n [\n [10.9730201, 0.7276532, 4344222.0129382, 0.2386508],\n [7.5339320, 0.7749706, 1427833.3888763, 0.2628137],\n [6.8971848, 0.7963949, 1094864.8116422, 0.2743869],\n ],\n ]\n)\n\nsecondary_steering_baseline = np.array(\n [\n # 8 m/s\n [\n [7.9803783, 0.7605249, 1683956.5765064, 0.2548147],\n [5.4029709, 0.8670436, 505568.1176628, 0.3176840],\n [4.9791408, 0.8936138, 382644.8719082, 0.3369155],\n ],\n # 9 m/s\n [\n [8.9779256, 0.7596713, 2397236.5542849, 0.2543815],\n [6.0798429, 0.8317428, 739757.0246720, 0.2949042],\n [5.5938124, 0.8562085, 566504.2126629, 0.3104007],\n ],\n # 10 m/s\n [\n [9.9754729, 0.7499157, 3283591.8023665, 0.2494847],\n [6.7754458, 0.8012934, 1038201.8164555, 0.2771174],\n [6.2302537, 0.8248100, 800700.5867580, 0.2907215],\n ],\n # 11 m/s\n [\n [10.9730201, 0.7276532, 4344222.0129382, 0.2386508],\n [7.5103959, 0.7755790, 1413729.2052485, 0.2631345],\n [6.8817912, 0.7970143, 1087699.9040360, 0.2747304],\n ],\n ]\n)\n\n\n# Note: compare the yawed vs non-yawed results. The upstream turbine\n# power should be lower in the yawed case. The following turbine\n# powers should higher in the yawed case.\n\n\ndef test_regression_tandem(sample_inputs_fixture):\n \"\"\"\n Tandem turbines\n \"\"\"\n sample_inputs_fixture.floris[\"wake\"][\"model_strings\"][\"velocity_model\"] = VELOCITY_MODEL\n sample_inputs_fixture.floris[\"wake\"][\"model_strings\"][\"deflection_model\"] = DEFLECTION_MODEL\n\n floris = Floris.from_dict(sample_inputs_fixture.floris)\n floris.initialize_domain()\n floris.steady_state_atmospheric_condition()\n\n n_turbines = floris.farm.n_turbines\n n_wind_speeds = floris.flow_field.n_wind_speeds\n n_wind_directions = floris.flow_field.n_wind_directions\n\n velocities = floris.flow_field.u\n yaw_angles = floris.farm.yaw_angles\n test_results = np.zeros((n_wind_directions, n_wind_speeds, n_turbines, 4))\n\n farm_avg_velocities = average_velocity(\n velocities,\n )\n farm_cts = Ct(\n velocities,\n yaw_angles,\n floris.farm.turbine_fCts,\n floris.farm.turbine_type_map,\n )\n farm_powers = power(\n floris.flow_field.air_density,\n velocities,\n yaw_angles,\n floris.farm.pPs,\n floris.farm.turbine_power_interps,\n floris.farm.turbine_type_map,\n )\n farm_axial_inductions = axial_induction(\n velocities,\n yaw_angles,\n floris.farm.turbine_fCts,\n floris.farm.turbine_type_map,\n )\n for i in range(n_wind_directions):\n for j in range(n_wind_speeds):\n for k in range(n_turbines):\n test_results[i, j, k, 0] = farm_avg_velocities[i, j, k]\n test_results[i, j, k, 1] = farm_cts[i, j, k]\n test_results[i, j, k, 2] = farm_powers[i, j, k]\n test_results[i, j, k, 3] = farm_axial_inductions[i, j, k]\n\n if DEBUG:\n print_test_values(\n farm_avg_velocities,\n farm_cts,\n farm_powers,\n farm_axial_inductions,\n )\n\n assert_results_arrays(test_results[0], baseline)\n\n\ndef test_regression_rotation(sample_inputs_fixture):\n \"\"\"\n Turbines in tandem and rotated.\n The result from 270 degrees should match the results from 360 degrees.\n\n Wind from the West (Left)\n\n ^\n |\n y\n\n 1|1 3\n |\n |\n |\n 0|0 2\n |----------|\n 0 1 x->\n\n\n Wind from the North (Top), rotated\n\n ^\n |\n y\n\n 1|3 2\n |\n |\n |\n 0|1 0\n |----------|\n 0 1 x->\n\n In 270, turbines 2 and 3 are waked. In 360, turbines 0 and 2 are waked.\n The test compares turbines 2 and 3 with 0 and 2 from 270 and 360.\n \"\"\"\n TURBINE_DIAMETER = 126.0\n\n sample_inputs_fixture.floris[\"wake\"][\"model_strings\"][\"velocity_model\"] = VELOCITY_MODEL\n sample_inputs_fixture.floris[\"wake\"][\"model_strings\"][\"deflection_model\"] = DEFLECTION_MODEL\n sample_inputs_fixture.floris[\"farm\"][\"layout_x\"] = [\n 0.0,\n 0.0,\n 5 * TURBINE_DIAMETER,\n 5 * TURBINE_DIAMETER,\n ]\n sample_inputs_fixture.floris[\"farm\"][\"layout_y\"] = [\n 0.0,\n 5 * TURBINE_DIAMETER,\n 0.0,\n 5 * TURBINE_DIAMETER\n ]\n sample_inputs_fixture.floris[\"flow_field\"][\"wind_directions\"] = [270.0, 360.0]\n sample_inputs_fixture.floris[\"flow_field\"][\"wind_speeds\"] = [8.0]\n\n floris = Floris.from_dict(sample_inputs_fixture.floris)\n floris.initialize_domain()\n floris.steady_state_atmospheric_condition()\n\n farm_avg_velocities = average_velocity(floris.flow_field.u)\n\n t0_270 = farm_avg_velocities[0, 0, 0] # upstream\n t1_270 = farm_avg_velocities[0, 0, 1] # upstream\n t2_270 = farm_avg_velocities[0, 0, 2] # waked\n t3_270 = farm_avg_velocities[0, 0, 3] # waked\n\n t0_360 = farm_avg_velocities[1, 0, 0] # waked\n t1_360 = farm_avg_velocities[1, 0, 1] # upstream\n t2_360 = farm_avg_velocities[1, 0, 2] # waked\n t3_360 = farm_avg_velocities[1, 0, 3] # upstream\n\n assert np.allclose(t0_270, t1_360)\n assert np.allclose(t1_270, t3_360)\n assert np.allclose(t2_270, t0_360)\n assert np.allclose(t3_270, t2_360)\n\n\ndef test_regression_yaw(sample_inputs_fixture):\n \"\"\"\n Tandem turbines with the upstream turbine yawed\n \"\"\"\n sample_inputs_fixture.floris[\"wake\"][\"model_strings\"][\"velocity_model\"] = VELOCITY_MODEL\n sample_inputs_fixture.floris[\"wake\"][\"model_strings\"][\"deflection_model\"] = DEFLECTION_MODEL\n\n floris = Floris.from_dict(sample_inputs_fixture.floris)\n\n yaw_angles = np.zeros((N_WIND_DIRECTIONS, N_WIND_SPEEDS, N_TURBINES))\n yaw_angles[:,:,0] = 5.0\n floris.farm.yaw_angles = yaw_angles\n\n floris.initialize_domain()\n floris.steady_state_atmospheric_condition()\n\n n_turbines = floris.farm.n_turbines\n n_wind_speeds = floris.flow_field.n_wind_speeds\n n_wind_directions = floris.flow_field.n_wind_directions\n\n velocities = floris.flow_field.u\n yaw_angles = floris.farm.yaw_angles\n test_results = np.zeros((n_wind_directions, n_wind_speeds, n_turbines, 4))\n\n farm_avg_velocities = average_velocity(\n velocities,\n )\n farm_cts = Ct(\n velocities,\n yaw_angles,\n floris.farm.turbine_fCts,\n floris.farm.turbine_type_map,\n )\n farm_powers = power(\n floris.flow_field.air_density,\n velocities,\n yaw_angles,\n floris.farm.pPs,\n floris.farm.turbine_power_interps,\n floris.farm.turbine_type_map,\n )\n farm_axial_inductions = axial_induction(\n velocities,\n yaw_angles,\n floris.farm.turbine_fCts,\n floris.farm.turbine_type_map,\n )\n for i in range(n_wind_directions):\n for j in range(n_wind_speeds):\n for k in range(n_turbines):\n test_results[i, j, k, 0] = farm_avg_velocities[i, j, k]\n test_results[i, j, k, 1] = farm_cts[i, j, k]\n test_results[i, j, k, 2] = farm_powers[i, j, k]\n test_results[i, j, k, 3] = farm_axial_inductions[i, j, k]\n\n if DEBUG:\n print_test_values(\n farm_avg_velocities,\n farm_cts,\n farm_powers,\n farm_axial_inductions,\n )\n\n assert_results_arrays(test_results[0], yawed_baseline)\n\n\ndef test_regression_yaw_added_recovery(sample_inputs_fixture):\n \"\"\"\n Tandem turbines with the upstream turbine yawed and yaw added recovery\n correction enabled\n \"\"\"\n\n sample_inputs_fixture.floris[\"wake\"][\"model_strings\"][\"velocity_model\"] = VELOCITY_MODEL\n sample_inputs_fixture.floris[\"wake\"][\"model_strings\"][\"deflection_model\"] = DEFLECTION_MODEL\n\n sample_inputs_fixture.floris[\"wake\"][\"enable_transverse_velocities\"] = True\n sample_inputs_fixture.floris[\"wake\"][\"enable_secondary_steering\"] = False\n sample_inputs_fixture.floris[\"wake\"][\"enable_yaw_added_recovery\"] = True\n\n floris = Floris.from_dict(sample_inputs_fixture.floris)\n\n yaw_angles = np.zeros((N_WIND_DIRECTIONS, N_WIND_SPEEDS, N_TURBINES))\n yaw_angles[:,:,0] = 5.0\n floris.farm.yaw_angles = yaw_angles\n \n floris.initialize_domain()\n floris.steady_state_atmospheric_condition()\n\n n_turbines = floris.farm.n_turbines\n n_wind_speeds = floris.flow_field.n_wind_speeds\n n_wind_directions = floris.flow_field.n_wind_directions\n\n velocities = floris.flow_field.u\n yaw_angles = floris.farm.yaw_angles\n test_results = np.zeros((n_wind_directions, n_wind_speeds, n_turbines, 4))\n\n farm_avg_velocities = average_velocity(\n velocities,\n )\n farm_cts = Ct(\n velocities,\n yaw_angles,\n floris.farm.turbine_fCts,\n floris.farm.turbine_type_map,\n )\n farm_powers = power(\n floris.flow_field.air_density,\n velocities,\n yaw_angles,\n floris.farm.pPs,\n floris.farm.turbine_power_interps,\n floris.farm.turbine_type_map,\n )\n farm_axial_inductions = axial_induction(\n velocities,\n yaw_angles,\n floris.farm.turbine_fCts,\n floris.farm.turbine_type_map,\n )\n for i in range(n_wind_directions):\n for j in range(n_wind_speeds):\n for k in range(n_turbines):\n test_results[i, j, k, 0] = farm_avg_velocities[i, j, k]\n test_results[i, j, k, 1] = farm_cts[i, j, k]\n test_results[i, j, k, 2] = farm_powers[i, j, k]\n test_results[i, j, k, 3] = farm_axial_inductions[i, j, k]\n\n if DEBUG:\n print_test_values(\n farm_avg_velocities,\n farm_cts,\n farm_powers,\n farm_axial_inductions,\n )\n\n assert_results_arrays(test_results[0], yaw_added_recovery_baseline)\n\n\ndef test_regression_secondary_steering(sample_inputs_fixture):\n \"\"\"\n Tandem turbines with the upstream turbine yawed and secondary steering enabled\n \"\"\"\n\n sample_inputs_fixture.floris[\"wake\"][\"model_strings\"][\"velocity_model\"] = VELOCITY_MODEL\n sample_inputs_fixture.floris[\"wake\"][\"model_strings\"][\"deflection_model\"] = DEFLECTION_MODEL\n\n sample_inputs_fixture.floris[\"wake\"][\"enable_transverse_velocities\"] = True\n sample_inputs_fixture.floris[\"wake\"][\"enable_secondary_steering\"] = True\n sample_inputs_fixture.floris[\"wake\"][\"enable_yaw_added_recovery\"] = False\n\n floris = Floris.from_dict(sample_inputs_fixture.floris)\n\n yaw_angles = np.zeros((N_WIND_DIRECTIONS, N_WIND_SPEEDS, N_TURBINES))\n yaw_angles[:,:,0] = 5.0\n floris.farm.yaw_angles = yaw_angles\n \n floris.initialize_domain()\n floris.steady_state_atmospheric_condition()\n\n n_turbines = floris.farm.n_turbines\n n_wind_speeds = floris.flow_field.n_wind_speeds\n n_wind_directions = floris.flow_field.n_wind_directions\n\n velocities = floris.flow_field.u\n yaw_angles = floris.farm.yaw_angles\n test_results = np.zeros((n_wind_directions, n_wind_speeds, n_turbines, 4))\n\n farm_avg_velocities = average_velocity(\n velocities,\n )\n farm_cts = Ct(\n velocities,\n yaw_angles,\n floris.farm.turbine_fCts,\n floris.farm.turbine_type_map,\n )\n farm_powers = power(\n floris.flow_field.air_density,\n velocities,\n yaw_angles,\n floris.farm.pPs,\n floris.farm.turbine_power_interps,\n floris.farm.turbine_type_map,\n )\n farm_axial_inductions = axial_induction(\n velocities,\n yaw_angles,\n floris.farm.turbine_fCts,\n floris.farm.turbine_type_map,\n )\n for i in range(n_wind_directions):\n for j in range(n_wind_speeds):\n for k in range(n_turbines):\n test_results[i, j, k, 0] = farm_avg_velocities[i, j, k]\n test_results[i, j, k, 1] = farm_cts[i, j, k]\n test_results[i, j, k, 2] = farm_powers[i, j, k]\n test_results[i, j, k, 3] = farm_axial_inductions[i, j, k]\n\n if DEBUG:\n print_test_values(\n farm_avg_velocities,\n farm_cts,\n farm_powers,\n farm_axial_inductions,\n )\n\n assert_results_arrays(test_results[0], secondary_steering_baseline)\n\n\ndef test_regression_small_grid_rotation(sample_inputs_fixture):\n \"\"\"\n Where wake models are masked based on the x-location of a turbine, numerical precision\n can cause masking to fail unexpectedly. For example, in the configuration here one of\n the turbines has these delta x values;\n\n [[4.54747351e-13 4.54747351e-13 4.54747351e-13 4.54747351e-13 4.54747351e-13]\n [4.54747351e-13 4.54747351e-13 4.54747351e-13 4.54747351e-13 4.54747351e-13]\n [4.54747351e-13 4.54747351e-13 4.54747351e-13 4.54747351e-13 4.54747351e-13]\n [4.54747351e-13 4.54747351e-13 4.54747351e-13 4.54747351e-13 4.54747351e-13]\n [4.54747351e-13 4.54747351e-13 4.54747351e-13 4.54747351e-13 4.54747351e-13]]\n\n and therefore the masking statement is False when it should be True. This causes the current\n turbine to be affected by its own wake. This test requires that at least in this particular\n configuration the masking correctly filters grid points.\n \"\"\"\n sample_inputs_fixture.floris[\"wake\"][\"model_strings\"][\"velocity_model\"] = VELOCITY_MODEL\n sample_inputs_fixture.floris[\"wake\"][\"model_strings\"][\"deflection_model\"] = DEFLECTION_MODEL\n X, Y = np.meshgrid(\n 6.0 * 126.0 * np.arange(0, 5, 1),\n 6.0 * 126.0 * np.arange(0, 5, 1)\n )\n X = X.flatten()\n Y = Y.flatten()\n\n sample_inputs_fixture.floris[\"farm\"][\"layout_x\"] = X\n sample_inputs_fixture.floris[\"farm\"][\"layout_y\"] = Y\n\n floris = Floris.from_dict(sample_inputs_fixture.floris)\n floris.initialize_domain()\n floris.steady_state_atmospheric_condition()\n\n # farm_avg_velocities = average_velocity(floris.flow_field.u)\n velocities = floris.flow_field.u\n yaw_angles = floris.farm.yaw_angles\n\n farm_powers = power(\n floris.flow_field.air_density,\n velocities,\n yaw_angles,\n floris.farm.pPs,\n floris.farm.turbine_power_interps,\n floris.farm.turbine_type_map,\n )\n\n # A \"column\" is oriented parallel to the wind direction\n # Columns 1 - 4 should have the same power profile\n # Column 5 leading turbine is completely unwaked\n # and the rest of the turbines have a partial wake from their immediate upstream turbine\n assert np.allclose(farm_powers[2,0,0:5], farm_powers[2,0,5:10])\n assert np.allclose(farm_powers[2,0,0:5], farm_powers[2,0,10:15])\n assert np.allclose(farm_powers[2,0,0:5], farm_powers[2,0,15:20])\n assert np.allclose(farm_powers[2,0,20], farm_powers[2,0,0])\n assert np.allclose(farm_powers[2,0,21], farm_powers[2,0,21:25])\n" ]
[ [ "numpy.array", "numpy.allclose", "numpy.arange", "numpy.zeros" ] ]
MarcusJones/kaggle_petfinder_adoption
[ "2d745b48405f4d4211b523eae272b9169fcf9fa2" ]
[ "reference_kernels/kernel.py" ]
[ "import gc\r\nimport glob\r\nimport json\r\nimport matplotlib.pyplot as plt\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport scipy as sp\r\nimport lightgbm as lgb\r\n\r\nfrom collections import Counter\r\nfrom functools import partial\r\nfrom math import sqrt\r\nfrom joblib import Parallel, delayed\r\nfrom tqdm import tqdm\r\nfrom PIL import Image\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn.model_selection import StratifiedKFold\r\nfrom sklearn.metrics import cohen_kappa_score, mean_squared_error\r\nfrom sklearn.metrics import confusion_matrix as sk_cmatrix\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.decomposition import SparsePCA, TruncatedSVD, LatentDirichletAllocation, NMF\r\n\r\n# basic datasets\r\ntrain = pd.read_csv('../input/petfinder-adoption-prediction/train/train.csv')\r\ntest = pd.read_csv('../input/petfinder-adoption-prediction/test/test.csv')\r\nsample_submission = pd.read_csv('../input/petfinder-adoption-prediction/test/sample_submission.csv')\r\nlabels_breed = pd.read_csv('../input/petfinder-adoption-prediction/breed_labels.csv')\r\nlabels_state = pd.read_csv('../input/petfinder-adoption-prediction/color_labels.csv')\r\nlabels_color = pd.read_csv('../input/petfinder-adoption-prediction/state_labels.csv')\r\n\r\ntrain_image_files = sorted(glob.glob('../input/petfinder-adoption-prediction/train_images/*.jpg'))\r\ntrain_metadata_files = sorted(glob.glob('../input/petfinder-adoption-prediction/train_metadata/*.json'))\r\ntrain_sentiment_files = sorted(glob.glob('../input/petfinder-adoption-prediction/train_sentiment/*.json'))\r\ntest_image_files = sorted(glob.glob('../input/petfinder-adoption-prediction/test_images/*.jpg'))\r\ntest_metadata_files = sorted(glob.glob('../input/petfinder-adoption-prediction/test_metadata/*.json'))\r\ntest_sentiment_files = sorted(glob.glob('../input/petfinder-adoption-prediction/test_sentiment/*.json'))\r\n\r\n# extract datasets\r\n# https://www.kaggle.com/christofhenkel/extract-image-features-from-pretrained-nn\r\ntrain_img_features = pd.read_csv('../input/extract-image-features-from-pretrained-nn/train_img_features.csv')\r\ntest_img_features = pd.read_csv('../input/extract-image-features-from-pretrained-nn/test_img_features.csv')\r\n\r\n# img_features columns set names\r\ncol_names =[\"PetID\"] + [\"{}_img_feature\".format(_) for _ in range(256)]\r\ntrain_img_features.columns = col_names\r\ntest_img_features.columns = col_names\r\n\r\n# ref: https://www.kaggle.com/wrosinski/baselinemodeling\r\nclass PetFinderParser(object):\r\n \r\n def __init__(self, debug=False):\r\n \r\n self.debug = debug\r\n self.sentence_sep = ' '\r\n \r\n # Does not have to be extracted because main DF already contains description\r\n self.extract_sentiment_text = False\r\n \r\n \r\n def open_metadata_file(self, filename):\r\n \"\"\"\r\n Load metadata file.\r\n \"\"\"\r\n with open(filename, 'r') as f:\r\n metadata_file = json.load(f)\r\n return metadata_file\r\n \r\n def open_sentiment_file(self, filename):\r\n \"\"\"\r\n Load sentiment file.\r\n \"\"\"\r\n with open(filename, 'r') as f:\r\n sentiment_file = json.load(f)\r\n return sentiment_file\r\n \r\n def open_image_file(self, filename):\r\n \"\"\"\r\n Load image file.\r\n \"\"\"\r\n image = np.asarray(Image.open(filename))\r\n return image\r\n \r\n def parse_sentiment_file(self, file):\r\n \"\"\"\r\n Parse sentiment file. Output DF with sentiment features.\r\n \"\"\"\r\n \r\n file_sentiment = file['documentSentiment']\r\n file_entities = [x['name'] for x in file['entities']]\r\n file_entities = self.sentence_sep.join(file_entities)\r\n\r\n if self.extract_sentiment_text:\r\n file_sentences_text = [x['text']['content'] for x in file['sentences']]\r\n file_sentences_text = self.sentence_sep.join(file_sentences_text)\r\n file_sentences_sentiment = [x['sentiment'] for x in file['sentences']]\r\n \r\n file_sentences_sentiment = pd.DataFrame.from_dict(\r\n file_sentences_sentiment, orient='columns').sum()\r\n file_sentences_sentiment = file_sentences_sentiment.add_prefix('document_').to_dict()\r\n \r\n file_sentiment.update(file_sentences_sentiment)\r\n \r\n df_sentiment = pd.DataFrame.from_dict(file_sentiment, orient='index').T\r\n if self.extract_sentiment_text:\r\n df_sentiment['text'] = file_sentences_text\r\n \r\n df_sentiment['entities'] = file_entities\r\n df_sentiment = df_sentiment.add_prefix('sentiment_')\r\n \r\n return df_sentiment\r\n \r\n def parse_metadata_file(self, file):\r\n \"\"\"\r\n Parse metadata file. Output DF with metadata features.\r\n \"\"\"\r\n \r\n file_keys = list(file.keys())\r\n \r\n if 'labelAnnotations' in file_keys:\r\n file_annots = file['labelAnnotations'][:int(len(file['labelAnnotations']) * 0.3)]\r\n file_top_score = np.asarray([x['score'] for x in file_annots]).mean()\r\n file_top_desc = [x['description'] for x in file_annots]\r\n else:\r\n file_top_score = np.nan\r\n file_top_desc = ['']\r\n \r\n file_colors = file['imagePropertiesAnnotation']['dominantColors']['colors']\r\n file_crops = file['cropHintsAnnotation']['cropHints']\r\n\r\n file_color_score = np.asarray([x['score'] for x in file_colors]).mean()\r\n file_color_pixelfrac = np.asarray([x['pixelFraction'] for x in file_colors]).mean()\r\n\r\n file_crop_conf = np.asarray([x['confidence'] for x in file_crops]).mean()\r\n \r\n if 'importanceFraction' in file_crops[0].keys():\r\n file_crop_importance = np.asarray([x['importanceFraction'] for x in file_crops]).mean()\r\n else:\r\n file_crop_importance = np.nan\r\n\r\n df_metadata = {\r\n 'annots_score': file_top_score,\r\n 'color_score': file_color_score,\r\n 'color_pixelfrac': file_color_pixelfrac,\r\n 'crop_conf': file_crop_conf,\r\n 'crop_importance': file_crop_importance,\r\n 'annots_top_desc': self.sentence_sep.join(file_top_desc)\r\n }\r\n \r\n df_metadata = pd.DataFrame.from_dict(df_metadata, orient='index').T\r\n df_metadata = df_metadata.add_prefix('metadata_')\r\n \r\n return df_metadata\r\n \r\n\r\n# Helper function for parallel data processing:\r\ndef extract_additional_features(pet_id, mode='train'):\r\n \r\n sentiment_filename = '../input/petfinder-adoption-prediction/{}_sentiment/{}.json'.format(mode, pet_id)\r\n try:\r\n sentiment_file = pet_parser.open_sentiment_file(sentiment_filename)\r\n df_sentiment = pet_parser.parse_sentiment_file(sentiment_file)\r\n df_sentiment['PetID'] = pet_id\r\n except FileNotFoundError:\r\n df_sentiment = []\r\n\r\n dfs_metadata = []\r\n metadata_filenames = sorted(glob.glob('../input/petfinder-adoption-prediction/{}_metadata/{}*.json'.format(mode, pet_id)))\r\n if len(metadata_filenames) > 0:\r\n for f in metadata_filenames:\r\n metadata_file = pet_parser.open_metadata_file(f)\r\n df_metadata = pet_parser.parse_metadata_file(metadata_file)\r\n df_metadata['PetID'] = pet_id\r\n dfs_metadata.append(df_metadata)\r\n dfs_metadata = pd.concat(dfs_metadata, ignore_index=True, sort=False)\r\n dfs = [df_sentiment, dfs_metadata]\r\n \r\n return dfs\r\n\r\ndef agg_features(df_metadata, df_sentiment):\r\n # Extend aggregates and improve column naming\r\n aggregates = ['mean', \"median\", 'sum', \"var\", \"std\", \"min\", \"max\", \"nunique\"]\r\n \r\n metadata_desc = df_metadata.groupby(['PetID'])['metadata_annots_top_desc'].unique()\r\n metadata_desc = metadata_desc.reset_index()\r\n metadata_desc['metadata_annots_top_desc'] = metadata_desc['metadata_annots_top_desc'].apply(lambda x: ' '.join(x))\r\n \r\n prefix = 'metadata'\r\n metadata_gr = df_metadata.drop(['metadata_annots_top_desc'], axis=1)\r\n for i in metadata_gr.columns:\r\n if 'PetID' not in i:\r\n metadata_gr[i] = metadata_gr[i].astype(float)\r\n metadata_gr = metadata_gr.groupby(['PetID']).agg(aggregates)\r\n metadata_gr.columns = pd.Index(['{}_{}_{}'.format(prefix, c[0], c[1].upper()) for c in metadata_gr.columns.tolist()])\r\n metadata_gr = metadata_gr.reset_index()\r\n \r\n sentiment_desc = df_sentiment.groupby(['PetID'])['sentiment_entities'].unique()\r\n sentiment_desc = sentiment_desc.reset_index()\r\n sentiment_desc['sentiment_entities'] = sentiment_desc['sentiment_entities'].apply(lambda x: ' '.join(x))\r\n \r\n prefix = 'sentiment'\r\n sentiment_gr = df_sentiment.drop(['sentiment_entities'], axis=1)\r\n for i in sentiment_gr.columns:\r\n if 'PetID' not in i:\r\n sentiment_gr[i] = sentiment_gr[i].astype(float)\r\n sentiment_gr = sentiment_gr.groupby(['PetID']).agg(aggregates)\r\n sentiment_gr.columns = pd.Index(['{}_{}_{}'.format(\r\n prefix, c[0], c[1].upper()) for c in sentiment_gr.columns.tolist()])\r\n sentiment_gr = sentiment_gr.reset_index()\r\n \r\n return sentiment_gr, metadata_gr, metadata_desc, sentiment_desc\r\n\r\n\r\ndef breed_features(df, _labels_breed):\r\n breed_main = df[['Breed1']].merge(_labels_breed, how='left', left_on='Breed1', right_on='BreedID', suffixes=('', '_main_breed'))\r\n breed_main = breed_main.iloc[:, 2:]\r\n breed_main = breed_main.add_prefix('main_breed_')\r\n \r\n breed_second = df[['Breed2']].merge(_labels_breed, how='left', left_on='Breed2', right_on='BreedID', suffixes=('', '_second_breed'))\r\n breed_second = breed_second.iloc[:, 2:]\r\n breed_second = breed_second.add_prefix('second_breed_')\r\n \r\n return breed_main, breed_second\r\n\r\n\r\ndef impact_coding(data, feature, target='y'):\r\n '''\r\n In this implementation we get the values and the dictionary as two different steps.\r\n This is just because initially we were ignoring the dictionary as a result variable.\r\n \r\n In this implementation the KFolds use shuffling. If you want reproducibility the cv \r\n could be moved to a parameter.\r\n '''\r\n n_folds = 20\r\n n_inner_folds = 10\r\n impact_coded = pd.Series()\r\n \r\n oof_default_mean = data[target].mean() # Gobal mean to use by default (you could further tune this)\r\n kf = KFold(n_splits=n_folds, shuffle=True)\r\n oof_mean_cv = pd.DataFrame()\r\n split = 0\r\n for infold, oof in kf.split(data[feature]):\r\n impact_coded_cv = pd.Series()\r\n kf_inner = KFold(n_splits=n_inner_folds, shuffle=True)\r\n inner_split = 0\r\n inner_oof_mean_cv = pd.DataFrame()\r\n oof_default_inner_mean = data.iloc[infold][target].mean()\r\n for infold_inner, oof_inner in kf_inner.split(data.iloc[infold]):\r\n # The mean to apply to the inner oof split (a 1/n_folds % based on the rest)\r\n oof_mean = data.iloc[infold_inner].groupby(by=feature)[target].mean()\r\n impact_coded_cv = impact_coded_cv.append(data.iloc[infold].apply(\r\n lambda x: oof_mean[x[feature]]\r\n if x[feature] in oof_mean.index\r\n else oof_default_inner_mean\r\n , axis=1))\r\n\r\n # Also populate mapping (this has all group -> mean for all inner CV folds)\r\n inner_oof_mean_cv = inner_oof_mean_cv.join(pd.DataFrame(oof_mean), rsuffix=inner_split, how='outer')\r\n inner_oof_mean_cv.fillna(value=oof_default_inner_mean, inplace=True)\r\n inner_split += 1\r\n\r\n # Also populate mapping\r\n oof_mean_cv = oof_mean_cv.join(pd.DataFrame(inner_oof_mean_cv), rsuffix=split, how='outer')\r\n oof_mean_cv.fillna(value=oof_default_mean, inplace=True)\r\n split += 1\r\n \r\n impact_coded = impact_coded.append(data.iloc[oof].apply(\r\n lambda x: inner_oof_mean_cv.loc[x[feature]].mean()\r\n if x[feature] in inner_oof_mean_cv.index\r\n else oof_default_mean\r\n , axis=1))\r\n\r\n return impact_coded, oof_mean_cv.mean(axis=1), oof_default_mean \r\n \r\n \r\ndef frequency_encoding(df, col_name):\r\n new_name = \"{}_counts\".format(col_name)\r\n new_col_name = \"{}_freq\".format(col_name)\r\n grouped = df.groupby(col_name).size().reset_index(name=new_name)\r\n df = df.merge(grouped, how = \"left\", on = col_name)\r\n df[new_col_name] = df[new_name]/df[new_name].count()\r\n del df[new_name]\r\n return df\r\n \r\n\r\n# FROM: https://www.kaggle.com/myltykritik/simple-lgbm-image-features\r\n\r\n# The following 3 functions have been taken from Ben Hamner's github repository\r\n# https://github.com/benhamner/Metrics\r\ndef confusion_matrix(rater_a, rater_b, min_rating=None, max_rating=None):\r\n \"\"\"\r\n Returns the confusion matrix between rater's ratings\r\n \"\"\"\r\n assert(len(rater_a) == len(rater_b))\r\n if min_rating is None:\r\n min_rating = min(rater_a + rater_b)\r\n if max_rating is None:\r\n max_rating = max(rater_a + rater_b)\r\n num_ratings = int(max_rating - min_rating + 1)\r\n conf_mat = [[0 for i in range(num_ratings)]\r\n for j in range(num_ratings)]\r\n for a, b in zip(rater_a, rater_b):\r\n conf_mat[a - min_rating][b - min_rating] += 1\r\n return conf_mat\r\n\r\n\r\ndef histogram(ratings, min_rating=None, max_rating=None):\r\n \"\"\"\r\n Returns the counts of each type of rating that a rater made\r\n \"\"\"\r\n if min_rating is None:\r\n min_rating = min(ratings)\r\n if max_rating is None:\r\n max_rating = max(ratings)\r\n num_ratings = int(max_rating - min_rating + 1)\r\n hist_ratings = [0 for x in range(num_ratings)]\r\n for r in ratings:\r\n hist_ratings[r - min_rating] += 1\r\n return hist_ratings\r\n\r\n\r\ndef quadratic_weighted_kappa(y, y_pred):\r\n \"\"\"\r\n Calculates the quadratic weighted kappa\r\n axquadratic_weighted_kappa calculates the quadratic weighted kappa\r\n value, which is a measure of inter-rater agreement between two raters\r\n that provide discrete numeric ratings. Potential values range from -1\r\n (representing complete disagreement) to 1 (representing complete\r\n agreement). A kappa value of 0 is expected if all agreement is due to\r\n chance.\r\n quadratic_weighted_kappa(rater_a, rater_b), where rater_a and rater_b\r\n each correspond to a list of integer ratings. These lists must have the\r\n same length.\r\n The ratings should be integers, and it is assumed that they contain\r\n the complete range of possible ratings.\r\n quadratic_weighted_kappa(X, min_rating, max_rating), where min_rating\r\n is the minimum possible rating, and max_rating is the maximum possible\r\n rating\r\n \"\"\"\r\n rater_a = y\r\n rater_b = y_pred\r\n min_rating=None\r\n max_rating=None\r\n rater_a = np.array(rater_a, dtype=int)\r\n rater_b = np.array(rater_b, dtype=int)\r\n assert(len(rater_a) == len(rater_b))\r\n if min_rating is None:\r\n min_rating = min(min(rater_a), min(rater_b))\r\n if max_rating is None:\r\n max_rating = max(max(rater_a), max(rater_b))\r\n conf_mat = confusion_matrix(rater_a, rater_b,\r\n min_rating, max_rating)\r\n num_ratings = len(conf_mat)\r\n num_scored_items = float(len(rater_a))\r\n\r\n hist_rater_a = histogram(rater_a, min_rating, max_rating)\r\n hist_rater_b = histogram(rater_b, min_rating, max_rating)\r\n\r\n numerator = 0.0\r\n denominator = 0.0\r\n\r\n for i in range(num_ratings):\r\n for j in range(num_ratings):\r\n expected_count = (hist_rater_a[i] * hist_rater_b[j]\r\n / num_scored_items)\r\n d = pow(i - j, 2.0) / pow(num_ratings - 1, 2.0)\r\n numerator += d * conf_mat[i][j] / num_scored_items\r\n denominator += d * expected_count / num_scored_items\r\n\r\n return (1.0 - numerator / denominator)\r\n\r\nclass OptimizedRounder(object):\r\n def __init__(self):\r\n self.coef_ = 0\r\n\r\n def _kappa_loss(self, coef, X, y):\r\n X_p = np.copy(X)\r\n for i, pred in enumerate(X_p):\r\n if pred < coef[0]:\r\n X_p[i] = 0\r\n elif pred >= coef[0] and pred < coef[1]:\r\n X_p[i] = 1\r\n elif pred >= coef[1] and pred < coef[2]:\r\n X_p[i] = 2\r\n elif pred >= coef[2] and pred < coef[3]:\r\n X_p[i] = 3\r\n else:\r\n X_p[i] = 4\r\n\r\n ll = quadratic_weighted_kappa(y, X_p)\r\n return -ll\r\n\r\n def fit(self, X, y):\r\n loss_partial = partial(self._kappa_loss, X=X, y=y)\r\n initial_coef = [0.5, 1.5, 2.5, 3.5]\r\n self.coef_ = sp.optimize.minimize(loss_partial, initial_coef, method='nelder-mead')\r\n\r\n def predict(self, X, coef):\r\n X_p = np.copy(X)\r\n for i, pred in enumerate(X_p):\r\n if pred < coef[0]:\r\n X_p[i] = 0\r\n elif pred >= coef[0] and pred < coef[1]:\r\n X_p[i] = 1\r\n elif pred >= coef[1] and pred < coef[2]:\r\n X_p[i] = 2\r\n elif pred >= coef[2] and pred < coef[3]:\r\n X_p[i] = 3\r\n else:\r\n X_p[i] = 4\r\n return X_p\r\n\r\n def coefficients(self):\r\n return self.coef_['x']\r\n \r\n \r\ndef rmse(actual, predicted):\r\n return sqrt(mean_squared_error(actual, predicted))\r\n \r\n\r\ndef train_lightgbm(X_train, X_test, params, n_splits, num_rounds, verbose_eval, early_stop):\r\n kfold = StratifiedKFold(n_splits=n_splits, random_state=1337)\r\n oof_train = np.zeros((X_train.shape[0]))\r\n oof_test = np.zeros((X_test.shape[0], n_splits))\r\n \r\n i = 0\r\n for train_index, valid_index in kfold.split(X_train, X_train['AdoptionSpeed'].values):\r\n \r\n X_tr = X_train.iloc[train_index, :]\r\n X_val = X_train.iloc[valid_index, :]\r\n \r\n y_tr = X_tr['AdoptionSpeed'].values\r\n X_tr = X_tr.drop(['AdoptionSpeed'], axis=1)\r\n \r\n y_val = X_val['AdoptionSpeed'].values\r\n X_val = X_val.drop(['AdoptionSpeed'], axis=1)\r\n \r\n print('\\ny_tr distribution: {}'.format(Counter(y_tr)))\r\n \r\n d_train = lgb.Dataset(X_tr, label=y_tr)\r\n d_valid = lgb.Dataset(X_val, label=y_val)\r\n watchlist = [d_train, d_valid]\r\n \r\n print('training LGB:')\r\n model = lgb.train(params,\r\n train_set=d_train,\r\n num_boost_round=num_rounds,\r\n valid_sets=watchlist,\r\n verbose_eval=verbose_eval,\r\n early_stopping_rounds=early_stop)\r\n \r\n val_pred = model.predict(X_val, num_iteration=model.best_iteration)\r\n test_pred = model.predict(X_test, num_iteration=model.best_iteration)\r\n \r\n oof_train[valid_index] = val_pred\r\n oof_test[:, i] = test_pred\r\n \r\n i += 1\r\n \r\n return oof_train, oof_test\r\n \r\n\r\npet_parser = PetFinderParser() \r\n \r\ndef main():\r\n \r\n train_pet_ids = train.PetID.unique()\r\n test_pet_ids = test.PetID.unique()\r\n \r\n dfs_train = Parallel(n_jobs=6, verbose=1)(\r\n delayed(extract_additional_features)(i, mode='train') for i in train_pet_ids)\r\n \r\n train_dfs_sentiment = [x[0] for x in dfs_train if isinstance(x[0], pd.DataFrame)]\r\n train_dfs_metadata = [x[1] for x in dfs_train if isinstance(x[1], pd.DataFrame)]\r\n \r\n train_dfs_sentiment = pd.concat(train_dfs_sentiment, ignore_index=True, sort=False)\r\n train_dfs_metadata = pd.concat(train_dfs_metadata, ignore_index=True, sort=False)\r\n \r\n dfs_test = Parallel(n_jobs=6, verbose=1)(\r\n delayed(extract_additional_features)(i, mode='test') for i in test_pet_ids)\r\n \r\n test_dfs_sentiment = [x[0] for x in dfs_test if isinstance(x[0], pd.DataFrame)]\r\n test_dfs_metadata = [x[1] for x in dfs_test if isinstance(x[1], pd.DataFrame)]\r\n \r\n test_dfs_sentiment = pd.concat(test_dfs_sentiment, ignore_index=True, sort=False)\r\n test_dfs_metadata = pd.concat(test_dfs_metadata, ignore_index=True, sort=False)\r\n \r\n train_sentiment_gr, train_metadata_gr, train_metadata_desc, train_sentiment_desc = agg_features(train_dfs_metadata, train_dfs_sentiment) \r\n test_sentiment_gr, test_metadata_gr, test_metadata_desc, test_sentiment_desc = agg_features(test_dfs_metadata, test_dfs_sentiment) \r\n \r\n train_proc = train.copy()\r\n for tr in [train_sentiment_gr, train_metadata_gr, train_metadata_desc, train_sentiment_desc]:\r\n train_proc = train_proc.merge(tr, how='left', on='PetID')\r\n \r\n test_proc = test.copy()\r\n for ts in [test_sentiment_gr, test_metadata_gr, test_metadata_desc, test_sentiment_desc]:\r\n test_proc = test_proc.merge(\r\n ts, how='left', on='PetID')\r\n\r\n train_proc = pd.merge(train_proc, train_img_features, on=\"PetID\")\r\n test_proc = pd.merge(test_proc, test_img_features, on=\"PetID\")\r\n \r\n train_breed_main, train_breed_second = breed_features(train_proc, labels_breed)\r\n train_proc = pd.concat([train_proc, train_breed_main, train_breed_second], axis=1)\r\n \r\n test_breed_main, test_breed_second = breed_features(test_proc, labels_breed)\r\n test_proc = pd.concat([test_proc, test_breed_main, test_breed_second], axis=1)\r\n \r\n X = pd.concat([train_proc, test_proc], ignore_index=True, sort=False)\r\n column_types = X.dtypes\r\n\r\n int_cols = column_types[column_types == 'int']\r\n float_cols = column_types[column_types == 'float']\r\n cat_cols = column_types[column_types == 'object']\r\n \r\n X_temp = X.copy()\r\n\r\n text_columns = ['Description', 'metadata_annots_top_desc', 'sentiment_entities']\r\n categorical_columns = ['main_breed_BreedName', 'second_breed_BreedName']\r\n\r\n to_drop_columns = ['PetID', 'Name', 'RescuerID']\r\n \r\n rescuer_count = X.groupby(['RescuerID'])['PetID'].count().reset_index()\r\n rescuer_count.columns = ['RescuerID', 'RescuerID_COUNT']\r\n \r\n X_temp = X_temp.merge(rescuer_count, how='left', on='RescuerID')\r\n \r\n for i in categorical_columns:\r\n X_temp.loc[:, i] = pd.factorize(X_temp.loc[:, i])[0]\r\n \r\n X_text = X_temp[text_columns]\r\n\r\n for i in X_text.columns:\r\n X_text.loc[:, i] = X_text.loc[:, i].fillna('<MISSING>')\r\n \r\n n_components = 5\r\n text_features = []\r\n\r\n\r\n # Generate text features:\r\n for i in X_text.columns:\r\n \r\n # Initialize decomposition methods:\r\n print('generating features from: {}'.format(i))\r\n svd_ = TruncatedSVD(\r\n n_components=n_components, random_state=1337)\r\n nmf_ = NMF(\r\n n_components=n_components, random_state=1337)\r\n \r\n tfidf_col = TfidfVectorizer().fit_transform(X_text.loc[:, i].values)\r\n svd_col = svd_.fit_transform(tfidf_col)\r\n svd_col = pd.DataFrame(svd_col)\r\n svd_col = svd_col.add_prefix('SVD_{}_'.format(i))\r\n \r\n nmf_col = nmf_.fit_transform(tfidf_col)\r\n nmf_col = pd.DataFrame(nmf_col)\r\n nmf_col = nmf_col.add_prefix('NMF_{}_'.format(i))\r\n \r\n text_features.append(svd_col)\r\n text_features.append(nmf_col)\r\n \r\n \r\n # Combine all extracted features:\r\n text_features = pd.concat(text_features, axis=1)\r\n \r\n # Concatenate with main DF:\r\n X_temp = pd.concat([X_temp, text_features], axis=1)\r\n \r\n # Remove raw text columns:\r\n for i in X_text.columns:\r\n X_temp = X_temp.drop(i, axis=1)\r\n \r\n X_temp[\"name_length\"] = X_temp.Name[X_temp.Name.isnull()].map(lambda x: len(str(x)))\r\n X_temp[\"name_length\"] = X_temp.Name.map(lambda x: len(str(x)))\r\n X_temp = X_temp.drop(to_drop_columns, axis=1)\r\n \r\n # Split into train and test again:\r\n X_train = X_temp.loc[np.isfinite(X_temp.AdoptionSpeed), :]\r\n X_test = X_temp.loc[~np.isfinite(X_temp.AdoptionSpeed), :]\r\n \r\n # Remove missing target column from test:\r\n X_test = X_test.drop(['AdoptionSpeed'], axis=1)\r\n \r\n \r\n print('X_train shape: {}'.format(X_train.shape))\r\n print('X_test shape: {}'.format(X_test.shape))\r\n \r\n assert X_train.shape[0] == train.shape[0]\r\n assert X_test.shape[0] == test.shape[0]\r\n \r\n \r\n # Check if columns between the two DFs are the same:\r\n train_cols = X_train.columns.tolist()\r\n train_cols.remove('AdoptionSpeed')\r\n \r\n test_cols = X_test.columns.tolist()\r\n \r\n np.random.seed(13)\r\n \r\n categorical_features = [\"Type\", \"Breed1\", \"Breed2\", \"Color1\" ,\"Color2\", \"Color3\", \"State\"]\r\n \r\n impact_coding_map = {}\r\n for f in categorical_features:\r\n print(\"Impact coding for {}\".format(f))\r\n X_train[\"impact_encoded_{}\".format(f)], impact_coding_mapping, default_coding = impact_coding(X_train, f, target=\"AdoptionSpeed\")\r\n impact_coding_map[f] = (impact_coding_mapping, default_coding)\r\n mapping, default_mean = impact_coding_map[f]\r\n X_test[\"impact_encoded_{}\".format(f)] = X_test.apply(lambda x: mapping[x[f]] if x[f] in mapping\r\n else default_mean, axis=1)\r\n\r\n for cat in categorical_features:\r\n X_train = frequency_encoding(X_train, cat)\r\n X_test = frequency_encoding(X_test, cat)\r\n\r\n params = {'application': 'regression',\r\n 'boosting': 'gbdt',\r\n 'metric': 'rmse',\r\n 'num_leaves': 70,\r\n 'max_depth': 9,\r\n 'learning_rate': 0.01,\r\n 'bagging_fraction': 0.85,\r\n 'feature_fraction': 0.8,\r\n 'min_split_gain': 0.02,\r\n 'min_child_samples': 150,\r\n 'min_child_weight': 0.02,\r\n 'lambda_l2': 0.0475,\r\n 'verbosity': -1,\r\n 'data_random_seed': 17}\r\n\r\n # Additional parameters:\r\n early_stop = 500\r\n verbose_eval = 100\r\n num_rounds = 10000\r\n n_splits = 5\r\n \r\n oof_train, oof_test = train_lightgbm(X_train, X_test, params, n_splits, num_rounds, verbose_eval, early_stop)\r\n optR = OptimizedRounder()\r\n optR.fit(oof_train, X_train['AdoptionSpeed'].values)\r\n coefficients = optR.coefficients()\r\n pred_test_y_k = optR.predict(oof_train, coefficients)\r\n print(\"\\nValid Counts = \", Counter(X_train['AdoptionSpeed'].values))\r\n print(\"Predicted Counts = \", Counter(pred_test_y_k))\r\n print(\"Coefficients = \", coefficients)\r\n qwk = quadratic_weighted_kappa(X_train['AdoptionSpeed'].values, pred_test_y_k)\r\n print(\"QWK = \", qwk)\r\n \r\n # Manually adjusted coefficients:\r\n coefficients_ = coefficients.copy()\r\n \r\n coefficients_[0] = 1.645\r\n coefficients_[1] = 2.115\r\n coefficients_[3] = 2.84\r\n \r\n train_predictions = optR.predict(oof_train, coefficients_).astype(int)\r\n print('train pred distribution: {}'.format(Counter(train_predictions)))\r\n \r\n test_predictions = optR.predict(oof_test.mean(axis=1), coefficients_)\r\n print('test pred distribution: {}'.format(Counter(test_predictions)))\r\n \r\n # Generate submission:\r\n submission = pd.DataFrame({'PetID': test['PetID'].values, 'AdoptionSpeed': test_predictions.astype(np.int32)})\r\n submission.head()\r\n submission.to_csv('submission.csv', index=False)\r\n \r\n\r\nif __name__ == '__main__':\r\n main()" ]
[ [ "pandas.Series", "numpy.random.seed", "numpy.asarray", "numpy.copy", "sklearn.decomposition.NMF", "pandas.DataFrame.from_dict", "numpy.isfinite", "sklearn.feature_extraction.text.TfidfVectorizer", "sklearn.decomposition.TruncatedSVD", "sklearn.model_selection.KFold", "numpy.zeros", "pandas.read_csv", "scipy.optimize.minimize", "pandas.merge", "pandas.concat", "pandas.factorize", "sklearn.metrics.mean_squared_error", "sklearn.model_selection.StratifiedKFold", "pandas.DataFrame", "numpy.array" ] ]
bstellato/cvxpy
[ "c954bcfd14f9b131bd55d5c1028e667297a53f76" ]
[ "cvxpy/cvxcore/tests/python/364A_scripts/act_management.py" ]
[ "from cvxpy import Maximize, Problem, Variable, hstack, vstack\nimport numpy as np\nimport time\n\n\n# Create two scalar optimization variables.\n\nANSWERS = []\nTIME = 0\n\nA = np.array([ [1, 2, 0, 1], \\\n[0, 0, 3, 1], \\\n[0, 3, 1, 1], \\\n[2, 1, 2, 5], \\\n[1, 0, 3, 2] ])\n\nA_star = hstack(A,A)\n\nc_max = np.array([100] * 5)\n\np = np.array([3, 2, 7, 6])\np_disc = np.array([2, 1, 4, 2])\n\np_star = vstack(p, p_disc)\n\nq = np.array([4, 10, 5, 10])\n\nx_star = Variable( 8 )\nconstraints = [ A_star * x_star <= c_max, x_star >= 0 ]\nfor i in range(4):\n\tconstraints.append( x_star[i] >= q[i] )\n\nobjective = Maximize(p_star.T * x_star)\n\nprob = Problem(objective, constraints)\ntic = time.time()\nANSWERS.append( prob.solve() ) \ntoc = time.time()\nTIME += toc - tic \n\n\nx = np.array( [0] * 4)\nfor i in range(4):\n\tx[i] = x_star.value[i] + x_star.value[4 + i]\n\n\npass #print \"Optimal revenue:\", result \npass #print \"Optimal activity levels:\", x\n\naverage_rate = np.array([0] * 4)\n\nfor i in range(4):\n\taverage_rate[i] = (x_star.value[i] * p_star.value[i] + x_star.value[i + 4] * p_star.value[i + 4]) / x[i]\n\npass #print \"Average rate:\", average_rate" ]
[ [ "numpy.array" ] ]
titania7777/3D-ResNets-PyTorch
[ "45921588bcf70f1b4ace424e754c48c0b5501ad6" ]
[ "main.py" ]
[ "from pathlib import Path\nimport json\nimport random\nimport os\n\nimport numpy as np\nimport torch\nfrom torch.nn import CrossEntropyLoss\nfrom torch.optim import SGD, lr_scheduler\nimport torch.multiprocessing as mp\nimport torch.distributed as dist\nfrom torch.backends import cudnn\nimport torchvision\n\nfrom opts import parse_opts\nfrom model import (generate_model, load_pretrained_model, make_data_parallel,\n get_fine_tuning_parameters)\nfrom mean import get_mean_std\nfrom spatial_transforms import (Compose, Normalize, Resize, CenterCrop,\n CornerCrop, MultiScaleCornerCrop,\n RandomResizedCrop, RandomHorizontalFlip,\n ToTensor, ScaleValue, ColorJitter,\n PickFirstChannels)\nfrom temporal_transforms import (LoopPadding, TemporalRandomCrop,\n TemporalCenterCrop, TemporalEvenCrop,\n SlidingWindow, TemporalSubsampling)\nfrom temporal_transforms import Compose as TemporalCompose\nfrom dataset import get_training_data, get_validation_data, get_inference_data\nfrom utils import Logger, worker_init_fn, get_lr\nfrom training import train_epoch\nfrom validation import val_epoch\nimport inference\n\n\ndef json_serial(obj):\n if isinstance(obj, Path):\n return str(obj)\n\n\ndef get_opt():\n opt = parse_opts()\n\n if opt.root_path is not None:\n opt.video_path = opt.root_path / opt.video_path\n opt.annotation_path = opt.root_path / opt.annotation_path\n opt.result_path = opt.root_path / opt.result_path\n if opt.resume_path is not None:\n opt.resume_path = opt.root_path / opt.resume_path\n if opt.pretrain_path is not None:\n opt.pretrain_path = opt.root_path / opt.pretrain_path\n\n if opt.pretrain_path is not None:\n opt.n_finetune_classes = opt.n_classes\n opt.n_classes = opt.n_pretrain_classes\n\n if opt.output_topk <= 0:\n opt.output_topk = opt.n_classes\n\n if opt.inference_batch_size == 0:\n opt.inference_batch_size = opt.batch_size\n\n opt.arch = '{}-{}'.format(opt.model, opt.model_depth)\n opt.begin_epoch = 1\n opt.mean, opt.std = get_mean_std(opt.value_scale, dataset=opt.mean_dataset)\n opt.n_input_channels = 3\n if opt.input_type == 'flow':\n opt.n_input_channels = 2\n opt.mean = opt.mean[:2]\n opt.std = opt.std[:2]\n\n if opt.distributed:\n opt.dist_rank = int(os.environ[\"OMPI_COMM_WORLD_RANK\"])\n\n if opt.dist_rank == 0:\n print(opt)\n with (opt.result_path / 'opts.json').open('w') as opt_file:\n json.dump(vars(opt), opt_file, default=json_serial)\n else:\n print(opt)\n with (opt.result_path / 'opts.json').open('w') as opt_file:\n json.dump(vars(opt), opt_file, default=json_serial)\n\n return opt\n\n\ndef resume_model(resume_path, arch, model):\n print('loading checkpoint {} model'.format(resume_path))\n checkpoint = torch.load(resume_path, map_location='cpu')\n assert arch == checkpoint['arch']\n\n if hasattr(model, 'module'):\n model.module.load_state_dict(checkpoint['state_dict'])\n else:\n model.load_state_dict(checkpoint['state_dict'])\n\n return model\n\n\ndef resume_train_utils(resume_path, begin_epoch, optimizer, scheduler):\n print('loading checkpoint {} train utils'.format(resume_path))\n checkpoint = torch.load(resume_path, map_location='cpu')\n\n begin_epoch = checkpoint['epoch'] + 1\n if optimizer is not None and 'optimizer' in checkpoint:\n optimizer.load_state_dict(checkpoint['optimizer'])\n if scheduler is not None and 'scheduler' in checkpoint:\n scheduler.load_state_dict(checkpoint['scheduler'])\n\n return begin_epoch, optimizer, scheduler\n\n\ndef get_normalize_method(mean, std, no_mean_norm, no_std_norm):\n if no_mean_norm:\n if no_std_norm:\n return Normalize([0, 0, 0], [1, 1, 1])\n else:\n return Normalize([0, 0, 0], std)\n else:\n if no_std_norm:\n return Normalize(mean, [1, 1, 1])\n else:\n return Normalize(mean, std)\n\n\ndef get_train_utils(opt, model_parameters):\n assert opt.train_crop in ['random', 'corner', 'center']\n spatial_transform = []\n if opt.train_crop == 'random':\n spatial_transform.append(\n RandomResizedCrop(\n opt.sample_size, (opt.train_crop_min_scale, 1.0),\n (opt.train_crop_min_ratio, 1.0 / opt.train_crop_min_ratio)))\n elif opt.train_crop == 'corner':\n scales = [1.0]\n scale_step = 1 / (2**(1 / 4))\n for _ in range(1, 5):\n scales.append(scales[-1] * scale_step)\n spatial_transform.append(MultiScaleCornerCrop(opt.sample_size, scales))\n elif opt.train_crop == 'center':\n spatial_transform.append(Resize(opt.sample_size))\n spatial_transform.append(CenterCrop(opt.sample_size))\n normalize = get_normalize_method(opt.mean, opt.std, opt.no_mean_norm,\n opt.no_std_norm)\n if not opt.no_hflip:\n spatial_transform.append(RandomHorizontalFlip())\n if opt.colorjitter:\n spatial_transform.append(ColorJitter())\n spatial_transform.append(ToTensor())\n if opt.input_type == 'flow':\n spatial_transform.append(PickFirstChannels(n=2))\n spatial_transform.append(ScaleValue(opt.value_scale))\n spatial_transform.append(normalize)\n spatial_transform = Compose(spatial_transform)\n\n assert opt.train_t_crop in ['random', 'center']\n temporal_transform = []\n if opt.sample_t_stride > 1:\n temporal_transform.append(TemporalSubsampling(opt.sample_t_stride))\n if opt.train_t_crop == 'random':\n temporal_transform.append(TemporalRandomCrop(opt.sample_duration))\n elif opt.train_t_crop == 'center':\n temporal_transform.append(TemporalCenterCrop(opt.sample_duration))\n temporal_transform = TemporalCompose(temporal_transform)\n\n train_data = get_training_data(opt.video_path, opt.annotation_path,\n opt.dataset, opt.input_type, opt.file_type,\n spatial_transform, temporal_transform)\n if opt.distributed:\n train_sampler = torch.utils.data.distributed.DistributedSampler(\n train_data)\n else:\n train_sampler = None\n train_loader = torch.utils.data.DataLoader(train_data,\n batch_size=opt.batch_size,\n shuffle=(train_sampler is None),\n num_workers=opt.n_threads,\n pin_memory=True,\n sampler=train_sampler,\n worker_init_fn=worker_init_fn)\n\n if opt.is_master_node:\n train_logger = Logger(opt.result_path / 'train.log',\n ['epoch', 'loss', 'acc', 'lr'])\n train_batch_logger = Logger(\n opt.result_path / 'train_batch.log',\n ['epoch', 'batch', 'iter', 'loss', 'acc', 'lr'])\n else:\n train_logger = None\n train_batch_logger = None\n\n if opt.nesterov:\n dampening = 0\n else:\n dampening = opt.dampening\n optimizer = SGD(model_parameters,\n lr=opt.learning_rate,\n momentum=opt.momentum,\n dampening=dampening,\n weight_decay=opt.weight_decay,\n nesterov=opt.nesterov)\n\n assert opt.lr_scheduler in ['plateau', 'multistep']\n assert not (opt.lr_scheduler == 'plateau' and opt.no_val)\n if opt.lr_scheduler == 'plateau':\n scheduler = lr_scheduler.ReduceLROnPlateau(\n optimizer, 'min', patience=opt.plateau_patience)\n else:\n scheduler = lr_scheduler.MultiStepLR(optimizer,\n opt.multistep_milestones)\n\n return (train_loader, train_sampler, train_logger, train_batch_logger,\n optimizer, scheduler)\n\n\ndef get_val_utils(opt):\n normalize = get_normalize_method(opt.mean, opt.std, opt.no_mean_norm,\n opt.no_std_norm)\n spatial_transform = [\n Resize(opt.sample_size),\n CenterCrop(opt.sample_size),\n ToTensor()\n ]\n if opt.input_type == 'flow':\n spatial_transform.append(PickFirstChannels(n=2))\n spatial_transform.extend([ScaleValue(opt.value_scale), normalize])\n spatial_transform = Compose(spatial_transform)\n\n temporal_transform = []\n if opt.sample_t_stride > 1:\n temporal_transform.append(TemporalSubsampling(opt.sample_t_stride))\n temporal_transform.append(\n TemporalEvenCrop(opt.sample_duration, opt.n_val_samples))\n temporal_transform = TemporalCompose(temporal_transform)\n\n val_data, collate_fn = get_validation_data(opt.video_path,\n opt.annotation_path, opt.dataset,\n opt.input_type, opt.file_type,\n spatial_transform,\n temporal_transform)\n if opt.distributed:\n val_sampler = torch.utils.data.distributed.DistributedSampler(\n val_data, shuffle=False)\n else:\n val_sampler = None\n val_loader = torch.utils.data.DataLoader(val_data,\n batch_size=(opt.batch_size //\n opt.n_val_samples),\n shuffle=False,\n num_workers=opt.n_threads,\n pin_memory=True,\n sampler=val_sampler,\n worker_init_fn=worker_init_fn,\n collate_fn=collate_fn)\n\n if opt.is_master_node:\n val_logger = Logger(opt.result_path / 'val.log',\n ['epoch', 'loss', 'acc'])\n else:\n val_logger = None\n\n return val_loader, val_logger\n\n\ndef get_inference_utils(opt):\n assert opt.inference_crop in ['center', 'nocrop']\n\n normalize = get_normalize_method(opt.mean, opt.std, opt.no_mean_norm,\n opt.no_std_norm)\n\n spatial_transform = [Resize(opt.sample_size)]\n if opt.inference_crop == 'center':\n spatial_transform.append(CenterCrop(opt.sample_size))\n spatial_transform.append(ToTensor())\n if opt.input_type == 'flow':\n spatial_transform.append(PickFirstChannels(n=2))\n spatial_transform.extend([ScaleValue(opt.value_scale), normalize])\n spatial_transform = Compose(spatial_transform)\n\n temporal_transform = []\n if opt.sample_t_stride > 1:\n temporal_transform.append(TemporalSubsampling(opt.sample_t_stride))\n temporal_transform.append(\n SlidingWindow(opt.sample_duration, opt.inference_stride))\n temporal_transform = TemporalCompose(temporal_transform)\n\n inference_data, collate_fn = get_inference_data(\n opt.video_path, opt.annotation_path, opt.dataset, opt.input_type,\n opt.file_type, opt.inference_subset, spatial_transform,\n temporal_transform)\n\n inference_loader = torch.utils.data.DataLoader(\n inference_data,\n batch_size=opt.inference_batch_size,\n shuffle=False,\n num_workers=opt.n_threads,\n pin_memory=True,\n worker_init_fn=worker_init_fn,\n collate_fn=collate_fn)\n\n return inference_loader, inference_data.class_names\n\n\ndef save_checkpoint(save_file_path, epoch, arch, model, optimizer, scheduler):\n if hasattr(model, 'module'):\n model_state_dict = model.module.state_dict()\n else:\n model_state_dict = model.state_dict()\n save_states = {\n 'epoch': epoch,\n 'arch': arch,\n 'state_dict': model_state_dict,\n 'optimizer': optimizer.state_dict(),\n 'scheduler': scheduler.state_dict()\n }\n torch.save(save_states, save_file_path)\n\n\ndef main_worker(index, opt):\n random.seed(opt.manual_seed)\n np.random.seed(opt.manual_seed)\n torch.manual_seed(opt.manual_seed)\n\n if index >= 0 and opt.device.type == 'cuda':\n opt.device = torch.device(f'cuda:{index}')\n\n if opt.distributed:\n opt.dist_rank = opt.dist_rank * opt.ngpus_per_node + index\n dist.init_process_group(backend='nccl',\n init_method=opt.dist_url,\n world_size=opt.world_size,\n rank=opt.dist_rank)\n opt.batch_size = int(opt.batch_size / opt.ngpus_per_node)\n opt.n_threads = int(\n (opt.n_threads + opt.ngpus_per_node - 1) / opt.ngpus_per_node)\n opt.is_master_node = not opt.distributed or opt.dist_rank == 0\n\n model = generate_model(opt)\n if opt.batchnorm_sync:\n assert opt.distributed, 'SyncBatchNorm only supports DistributedDataParallel.'\n model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)\n if opt.pretrain_path:\n model = load_pretrained_model(model, opt.pretrain_path, opt.model,\n opt.n_finetune_classes)\n if opt.resume_path is not None:\n model = resume_model(opt.resume_path, opt.arch, model)\n model = make_data_parallel(model, opt.distributed, opt.device)\n\n if opt.pretrain_path:\n parameters = get_fine_tuning_parameters(model, opt.ft_begin_module)\n else:\n parameters = model.parameters()\n\n if opt.is_master_node:\n print(model)\n\n criterion = CrossEntropyLoss().to(opt.device)\n\n if not opt.no_train:\n (train_loader, train_sampler, train_logger, train_batch_logger,\n optimizer, scheduler) = get_train_utils(opt, parameters)\n if opt.resume_path is not None:\n opt.begin_epoch, optimizer, scheduler = resume_train_utils(\n opt.resume_path, opt.begin_epoch, optimizer, scheduler)\n if opt.overwrite_milestones:\n scheduler.milestones = opt.multistep_milestones\n if not opt.no_val:\n val_loader, val_logger = get_val_utils(opt)\n\n if opt.tensorboard and opt.is_master_node:\n from torch.utils.tensorboard import SummaryWriter\n if opt.begin_epoch == 1:\n tb_writer = SummaryWriter(log_dir=opt.result_path)\n else:\n tb_writer = SummaryWriter(log_dir=opt.result_path,\n purge_step=opt.begin_epoch)\n else:\n tb_writer = None\n\n prev_val_loss = None\n for i in range(opt.begin_epoch, opt.n_epochs + 1):\n if not opt.no_train:\n if opt.distributed:\n train_sampler.set_epoch(i)\n current_lr = get_lr(optimizer)\n train_epoch(i, train_loader, model, criterion, optimizer,\n opt.device, current_lr, train_logger,\n train_batch_logger, tb_writer, opt.distributed)\n\n if i % opt.checkpoint == 0 and opt.is_master_node:\n save_file_path = opt.result_path / 'save_{}.pth'.format(i)\n save_checkpoint(save_file_path, i, opt.arch, model, optimizer,\n scheduler)\n\n if not opt.no_val:\n prev_val_loss = val_epoch(i, val_loader, model, criterion,\n opt.device, val_logger, tb_writer,\n opt.distributed)\n\n if not opt.no_train and opt.lr_scheduler == 'multistep':\n scheduler.step()\n elif not opt.no_train and opt.lr_scheduler == 'plateau':\n scheduler.step(prev_val_loss)\n\n if opt.inference:\n inference_loader, inference_class_names = get_inference_utils(opt)\n inference_result_path = opt.result_path / '{}.json'.format(\n opt.inference_subset)\n\n inference.inference(inference_loader, model, inference_result_path,\n inference_class_names, opt.inference_no_average,\n opt.output_topk)\n\n\nif __name__ == '__main__':\n opt = get_opt()\n\n opt.device = torch.device('cpu' if opt.no_cuda else 'cuda')\n if not opt.no_cuda:\n cudnn.benchmark = True\n if opt.accimage:\n torchvision.set_image_backend('accimage')\n\n opt.ngpus_per_node = torch.cuda.device_count()\n if opt.distributed:\n opt.world_size = opt.ngpus_per_node * opt.world_size\n mp.spawn(main_worker, nprocs=opt.ngpus_per_node, args=(opt,))\n else:\n main_worker(-1, opt)" ]
[ [ "torch.utils.data.DataLoader", "torch.nn.SyncBatchNorm.convert_sync_batchnorm", "torch.optim.SGD", "torch.load", "torch.utils.data.distributed.DistributedSampler", "torch.multiprocessing.spawn", "torch.manual_seed", "torch.save", "numpy.random.seed", "torch.distributed.init_process_group", "torch.cuda.device_count", "torch.nn.CrossEntropyLoss", "torch.optim.lr_scheduler.MultiStepLR", "torch.utils.tensorboard.SummaryWriter", "torch.optim.lr_scheduler.ReduceLROnPlateau", "torch.device" ] ]
IntoxicatedDING/stdn
[ "1bb9555114c762b09ad65eb16c59b134e1dccb56" ]
[ "data/voc0712.py" ]
[ "\"\"\"VOC Dataset Classes\n\nOriginal author: Francisco Massa\nhttps://github.com/fmassa/vision/blob/voc_dataset/torchvision/datasets/voc.py\n\nUpdated by: Ellis Brown, Max deGroot\n\"\"\"\n'''\nAdapted from https://github.com/amdegroot/ssd.pytorch\n'''\nfrom .config import HOME\nimport os.path as osp\nimport sys\nimport torch\nimport torch.utils.data as data\nimport cv2\nimport numpy as np\nif sys.version_info[0] == 2:\n import xml.etree.cElementTree as ET\nelse:\n import xml.etree.ElementTree as ET\n\nVOC_CLASSES = ( # always index 0\n 'aeroplane', 'bicycle', 'bird', 'boat',\n 'bottle', 'bus', 'car', 'cat', 'chair',\n 'cow', 'diningtable', 'dog', 'horse',\n 'motorbike', 'person', 'pottedplant',\n 'sheep', 'sofa', 'train', 'tvmonitor')\n\n# note: if you used our download scripts, this should be right\nVOC_ROOT = osp.join(HOME, \"dataset/VOC0712/VOCdevkit/\")\n\n\nclass VOCAnnotationTransform(object):\n \"\"\"Transforms a VOC annotation into a Tensor of bbox coords and label index\n Initilized with a dictionary lookup of classnames to indexes\n\n Arguments:\n class_to_ind (dict, optional): dictionary lookup of classnames -> indexes\n (default: alphabetic indexing of VOC's 20 classes)\n keep_difficult (bool, optional): keep difficult instances or not\n (default: False)\n height (int): height\n width (int): width\n \"\"\"\n\n def __init__(self, class_to_ind=None, keep_difficult=False):\n self.class_to_ind = class_to_ind or dict(\n zip(VOC_CLASSES, range(len(VOC_CLASSES))))\n self.keep_difficult = keep_difficult\n\n def __call__(self, target, width, height):\n \"\"\"\n Arguments:\n target (annotation) : the target annotation to be made usable\n will be an ET.Element\n Returns:\n a list containing lists of bounding boxes [bbox coords, class name]\n \"\"\"\n res = []\n for obj in target.iter('object'):\n difficult = int(obj.find('difficult').text) == 1\n if not self.keep_difficult and difficult:\n continue\n name = obj.find('name').text.lower().strip()\n bbox = obj.find('bndbox')\n\n pts = ['xmin', 'ymin', 'xmax', 'ymax']\n bndbox = []\n for i, pt in enumerate(pts):\n cur_pt = int(bbox.find(pt).text) - 1\n # scale height or width\n cur_pt = cur_pt / width if i % 2 == 0 else cur_pt / height\n bndbox.append(cur_pt)\n label_idx = self.class_to_ind[name]\n bndbox.append(label_idx)\n res += [bndbox] # [xmin, ymin, xmax, ymax, label_ind]\n # img_id = target.find('filename').text[:-4]\n\n return res # [[xmin, ymin, xmax, ymax, label_ind], ... ]\n\n\nclass VOCDetection(data.Dataset):\n \"\"\"VOC Detection Dataset Object\n\n input is image, target is annotation\n\n Arguments:\n root (string): filepath to VOCdevkit folder.\n image_set (string): imageset to use (eg. 'train', 'val', 'test')\n transform (callable, optional): transformation to perform on the\n input image\n target_transform (callable, optional): transformation to perform on the\n target `annotation`\n (eg: take in caption string, return tensor of word indices)\n dataset_name (string, optional): which dataset to load\n (default: 'VOC2007')\n \"\"\"\n\n def __init__(self, root,\n # image_sets=[('2007', 'trainval'), ('2012', 'trainval')],\n image_sets=[('2007', 'trainval')],\n transform=None, target_transform=VOCAnnotationTransform(),\n dataset_name='VOC0712'):\n self.root = root\n self.image_set = image_sets\n self.transform = transform\n self.target_transform = target_transform\n self.name = dataset_name\n self._annopath = osp.join('%s', 'Annotations', '%s.xml')\n self._imgpath = osp.join('%s', 'JPEGImages', '%s.jpg')\n self.ids = list()\n for (year, name) in image_sets:\n rootpath = osp.join(self.root, 'VOC' + year)\n for line in open(osp.join(rootpath, 'ImageSets', 'Main', name + '.txt')):\n self.ids.append((rootpath, line.strip()))\n\n def __getitem__(self, index):\n im, gt, h, w = self.pull_item(index)\n\n return im, gt\n\n def __len__(self):\n return len(self.ids)\n\n def pull_item(self, index):\n img_id = self.ids[index]\n\n target = ET.parse(self._annopath % img_id).getroot()\n img = cv2.imread(self._imgpath % img_id)\n height, width, channels = img.shape\n\n if self.target_transform is not None:\n target = self.target_transform(target, width, height)\n\n if self.transform is not None:\n target = np.array(target)\n img, boxes, labels = self.transform(img, target[:, :4], target[:, 4])\n # to rgb\n img = img[:, :, (2, 1, 0)]\n # img = img.transpose(2, 0, 1)\n target = np.hstack((boxes, np.expand_dims(labels, axis=1)))\n return torch.from_numpy(img).permute(2, 0, 1), target, height, width\n # return torch.from_numpy(img), target, height, width\n\n def pull_image(self, index):\n '''Returns the original image object at index in PIL form\n\n Note: not using self.__getitem__(), as any transformations passed in\n could mess up this functionality.\n\n Argument:\n index (int): index of img to show\n Return:\n PIL img\n '''\n img_id = self.ids[index]\n return cv2.imread(self._imgpath % img_id, cv2.IMREAD_COLOR)\n\n def pull_anno(self, index):\n '''Returns the original annotation of image at index\n\n Note: not using self.__getitem__(), as any transformations passed in\n could mess up this functionality.\n\n Argument:\n index (int): index of img to get annotation of\n Return:\n list: [img_id, [(label, bbox coords),...]]\n eg: ('001718', [('dog', (96, 13, 438, 332))])\n '''\n img_id = self.ids[index]\n anno = ET.parse(self._annopath % img_id).getroot()\n gt = self.target_transform(anno, 1, 1)\n return img_id[1], gt\n\n def pull_tensor(self, index):\n '''Returns the original image at an index in tensor form\n\n Note: not using self.__getitem__(), as any transformations passed in\n could mess up this functionality.\n\n Argument:\n index (int): index of img to show\n Return:\n tensorized version of img, squeezed\n '''\n return torch.Tensor(self.pull_image(index)).unsqueeze_(0)\n" ]
[ [ "numpy.array", "numpy.expand_dims", "torch.from_numpy" ] ]
hazananayurt/viref
[ "f7b5a2278d9211104ea2293077e2b85d7466d63a" ]
[ "viref/model.py" ]
[ "import torch\nfrom torch import optim\nfrom torch.nn import Parameter\nimport torch.nn.functional as F\n\nclass Encoder(torch.nn.Module):\n\tdef __init__(self, input_size, hidden_size, num_layers, dropout):\n\t\tsuper(Encoder, self).__init__()\n\t\t\n\t\tself.input_size = input_size\n\t\tself.hidden_size = hidden_size\n\t\tself.num_layers = num_layers\n\t\t\n\t\tself.lstm = torch.nn.LSTM(input_size=input_size,\n\t\t\t\t\t\t\t\t hidden_size=hidden_size,\n\t\t\t\t\t\t\t\t num_layers=num_layers,\n\t\t\t\t\t\t\t\t batch_first=True,\n\t\t\t\t\t\t\t\t dropout=dropout)\n\t\t\n\t\t\n\tdef forward(self, features, scale_weights, h0, c0):\n\t\tscaled_features = []\n\t\tfor feature_idx, feature in enumerate(features):\n\t\t\tscaled_features.append(feature*scale_weights[:, feature_idx].unsqueeze(1).unsqueeze(1))\n\t\tinp = torch.cat(scaled_features, dim=2)\n\t\tout, (hn, cn) = self.lstm(inp, (h0, c0))\n\t\treturn out, (hn, cn)\n\n\nclass Decoder(torch.nn.Module):\n\tdef __init__(self, input_size, hidden_size, num_layers, dropout):\n\t\tsuper(Decoder, self).__init__()\n\t\t\n\t\tself.input_size = input_size\n\t\tself.hidden_size = hidden_size\n\t\tself.num_layers = num_layers\n\t\t\n\t\tself.lstm = torch.nn.LSTM(input_size=input_size,\n\t\t\t\t\t\t\t\t hidden_size=hidden_size,\n\t\t\t\t\t\t\t\t num_layers=num_layers,\n\t\t\t\t\t\t\t\t batch_first=True,\n\t\t\t\t\t\t\t\t dropout=dropout)\n\t\t\n\t\t\n\tdef forward(self, inp, h0, c0):\n\t\tout, (hn, cn) = self.lstm(inp, (h0, c0))\n\t\treturn out, (hn, cn)\n\t\t\n\t\t\nclass FF1(torch.nn.Module):\n\tdef __init__(self, hidden_size, num_features):\n\t\tsuper(FF1, self).__init__()\n\t\t\n\t\tself.fc1 = torch.nn.Linear(hidden_size, hidden_size)\n\t\tself.fc2 = torch.nn.Linear(hidden_size, int(hidden_size/2))\n\t\tself.fc3 = torch.nn.Linear(int(hidden_size/2), num_features)\n\t\tself.softmax = torch.nn.Softmax(dim=2)\n\t\t\n\tdef forward(self, decoder_out):\n\t\tbatch_size = decoder_out.size(0)\n\t\tout = decoder_out\n\t\tout = out.contiguous()\n\t\tout = out.view(-1, out.size(2))\n\t\tout = self.fc1(out)\n\t\tout = F.relu(out)\n\t\tout = self.fc2(out)\n\t\tout = F.relu(out)\n\t\tout = self.fc3(out)\n\t\tout = out.view(batch_size, -1, out.size(1))\n\t\tout = self.softmax(out)\n\t\treturn out\n\t\t\n\t\t\n\nclass FF2(torch.nn.Module):\n\tdef __init__(self, hidden_size, num_layers, decoder_output_size):\n\t\tsuper(FF2, self).__init__()\n\t\t\n\t\tself.fc1 = torch.nn.Linear(hidden_size*(num_layers+1), hidden_size*2)\n\t\tself.fc2 = torch.nn.Linear(hidden_size*2, hidden_size)\n\t\tself.fc3 = torch.nn.Linear(hidden_size, decoder_output_size)\n\t\t\n\t\t\n\tdef forward(self, decoder_hidden_state, attended_features):\n\t\tbatch_size = decoder_hidden_state.size(0)\n\t\tinp2 = attended_features.permute(1, 0, 2).contiguous().view(batch_size, -1)\n\t\tinp = torch.cat([decoder_hidden_state, inp2], dim=1)\n\t\tout = self.fc1(inp)\n\t\tout = F.relu(out)\n\t\tout = self.fc2(out)\n\t\tout = F.relu(out)\n\t\tout = self.fc3(out)\n\t\tout = F.log_softmax(out, dim=1)\n\t\treturn out\n\n\t\t\nclass Model(torch.nn.Module):\n\tdef __init__(self, encoder_input_size, decoder_input_size, decoder_output_size, hidden_size, num_layers, num_features, dropout):\n\t\tsuper(Model, self).__init__()\n\t\t\n\t\tself.encoder_input_size = encoder_input_size\n\t\tself.decoder_input_size = decoder_input_size\n\t\tself.decoder_output_size = decoder_output_size\n\t\tself.hidden_size = hidden_size\n\t\tself.num_layers = num_layers\n\t\t\n\t\tself.encoder = Encoder(encoder_input_size, hidden_size, num_layers, dropout)\n\t\tself.decoder = Decoder(decoder_input_size, hidden_size, num_layers, dropout)\n\n\t\tself.ff1 = FF1(hidden_size, num_features)\n\t\tself.ff2 = FF2(hidden_size, num_layers, decoder_output_size)\n\t\t\n\t\t\n\tdef forward(self, features, initial_scale_weights, decoder_input, h0, c0):\n\t\tbatch_size = features[0].shape[0]\n\t\t_, (hn, cn) = self.encoder(features, initial_scale_weights, h0, c0)\n\t\tdecoder_out, _ = self.decoder(decoder_input, hn, cn)\n\t\tout = self.ff1(decoder_out)\n\t\tfinal_out_list = []\n\t\tfor i in range(int(out.size(1))):\n\t\t\tscale_weights = out[:, i, :]\n\t\t\t#print(scale_weights)\n\t\t\t_, (hn, _) = self.encoder(features, scale_weights, h0, c0)\n\t\t\tout_i = self.ff2(decoder_out[:, i, :], hn)\n\t\t\tfinal_out_list.append(out_i.unsqueeze(0))\n\t\tout = torch.cat(final_out_list, dim=0)\n\t\tout = out.permute(1, 0, 2)\n\t\treturn out\n\n" ]
[ [ "torch.nn.functional.log_softmax", "torch.nn.LSTM", "torch.nn.Linear", "torch.nn.Softmax", "torch.nn.functional.relu", "torch.cat" ] ]
XiaoJake/DS-Net
[ "8400da1bd7c7b1ccf4d5c6782b86372957e79a6b" ]
[ "network/model_zoo.py" ]
[ "# -*- coding:utf-8 -*-\n# author: Hong Fangzhou\n# @file: model_zoo.py\n# @time: 2020/09/26 17:05\n\nfrom .modules import BEV_Unet\nfrom .modules import PointNet\nfrom .modules import spconv_unet\nfrom .modules import pytorch_meanshift\nfrom .loss import instance_losses\nfrom .loss import lovasz_losses\nfrom utils.evaluate_panoptic import init_eval, eval_one_scan_w_fname, eval_one_scan_vps\nfrom utils.evaluate_panoptic import printResults, valid_xentropy_ids, class_lut\nfrom utils import clustering\nfrom utils import common_utils\nfrom utils.common_utils import grp_range_torch, parallel_FPS, SemKITTI2train\nfrom scipy.optimize import linear_sum_assignment\n\nimport io\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch_scatter\nimport numpy as np\nimport numba as nb\nimport multiprocessing\nfrom scipy import stats as s\nfrom sklearn.metrics import confusion_matrix as cm\nfrom easydict import EasyDict\nimport time\nimport os\nimport pickle\nfrom sklearn.cluster import MeanShift\nfrom sklearn import manifold, datasets\nfrom scipy import stats as s\nfrom utils import common_utils\nfrom utils.config import global_args\nimport spconv\n\nclass PolarBaseClass(nn.Module):\n def __init__(self, cfg):\n super(PolarBaseClass, self).__init__()\n self.ignore_label = cfg.DATA_CONFIG.DATALOADER.CONVERT_IGNORE_LABEL\n self.pt_pooling = cfg.MODEL.MODEL_FN.PT_POOLING\n self.max_pt = cfg.MODEL.MODEL_FN.MAX_PT_PER_ENCODE\n self.pt_selection = cfg.MODEL.MODEL_FN.PT_SELECTION\n if 'FEATURE_COMPRESSION' in cfg.MODEL.MODEL_FN.keys():\n self.fea_compre = cfg.MODEL.MODEL_FN.FEATURE_COMPRESSION\n else:\n self.fea_compre = cfg.DATA_CONFIG.DATALOADER.GRID_SIZE[2]\n self.grid_size = cfg.DATA_CONFIG.DATALOADER.GRID_SIZE\n\n if self.pt_pooling == 'max':\n self.pool_dim = cfg.MODEL.VFE.OUT_CHANNEL\n\n if self.fea_compre is not None:\n self.fea_compression = nn.Sequential(\n nn.Linear(self.pool_dim, self.fea_compre),\n nn.ReLU()\n ).cuda()\n self.pt_fea_dim = self.fea_compre\n\n def voxelize(self, inputs):\n grid_ind = inputs['grid']\n pt_fea = inputs['pt_fea']\n\n pt_fea_ten = [torch.from_numpy(i).type(torch.FloatTensor).cuda() for i in pt_fea]\n grid_ind_ten = [torch.from_numpy(i[:, :2]).cuda() for i in grid_ind]\n\n pt_fea = pt_fea_ten\n xy_ind = grid_ind_ten\n\n # concate everything\n cat_pt_ind = []\n for i_batch in range(len(xy_ind)):\n cat_pt_ind.append(F.pad(xy_ind[i_batch],(1,0),'constant',value = i_batch))\n\n cat_pt_fea = torch.cat(pt_fea,dim = 0)\n cat_pt_ind = torch.cat(cat_pt_ind,dim = 0)\n pt_num = cat_pt_ind.shape[0]\n\n # shuffle the data\n cur_dev = pt_fea[0].get_device()\n shuffled_ind = torch.randperm(pt_num,device = cur_dev)\n cat_pt_fea = cat_pt_fea[shuffled_ind,:]\n cat_pt_ind = cat_pt_ind[shuffled_ind,:]\n\n # unique xy grid index\n unq, unq_inv, unq_cnt = torch.unique(cat_pt_ind,return_inverse=True, return_counts=True, dim=0)\n unq = unq.type(torch.int64)\n\n # subsample pts\n if self.pt_selection == 'random':\n grp_ind = grp_range_torch(unq_cnt,cur_dev)[torch.argsort(torch.argsort(unq_inv))] # convert the array that is in the order of grid to the order of cat_pt_feature\n remain_ind = grp_ind < self.max_pt # randomly sample max_pt points inside a grid\n elif self.pt_selection == 'farthest':\n unq_ind = np.split(np.argsort(unq_inv.detach().cpu().numpy()), np.cumsum(unq_cnt.detach().cpu().numpy()[:-1]))\n remain_ind = np.zeros((pt_num,),dtype = np.bool)\n np_cat_fea = cat_pt_fea.detach().cpu().numpy()[:,:3]\n pool_in = []\n for i_inds in unq_ind:\n if len(i_inds) > self.max_pt:\n pool_in.append((np_cat_fea[i_inds,:],self.max_pt))\n if len(pool_in) > 0:\n pool = multiprocessing.Pool(multiprocessing.cpu_count())\n FPS_results = pool.starmap(parallel_FPS, pool_in)\n pool.close()\n pool.join()\n count = 0\n for i_inds in unq_ind:\n if len(i_inds) <= self.max_pt:\n remain_ind[i_inds] = True\n else:\n remain_ind[i_inds[FPS_results[count]]] = True\n count += 1\n\n cat_pt_fea = cat_pt_fea[remain_ind,:]\n cat_pt_ind = cat_pt_ind[remain_ind,:]\n unq_inv = unq_inv[remain_ind]\n unq_cnt = torch.clamp(unq_cnt,max=self.max_pt)\n\n # process feature\n processed_cat_pt_fea = self.vfe_model(cat_pt_fea)\n #TODO: maybe use pointnet to extract features inside each grid and each grid share the same parameters instead of apply pointnet to global point clouds?\n # This kind of global pointnet is more memory efficient cause otherwise we will have to alloc [480 x 360 x 32 x 64 x C] tensor in order to apply pointnet to each grid\n\n if self.pt_pooling == 'max':\n pooled_data = torch_scatter.scatter_max(processed_cat_pt_fea, unq_inv, dim=0)[0] # choose the max feature for each grid\n else: raise NotImplementedError\n\n if self.fea_compre:\n processed_pooled_data = self.fea_compression(pooled_data)\n else:\n processed_pooled_data = pooled_data\n\n # stuff pooled data into 4D tensor\n out_data_dim = [len(pt_fea),self.grid_size[0],self.grid_size[1],self.pt_fea_dim]\n out_data = torch.zeros(out_data_dim, dtype=torch.float32).to(cur_dev)\n out_data[unq[:,0],unq[:,1],unq[:,2],:] = processed_pooled_data\n out_data = out_data.permute(0,3,1,2)\n\n del pt_fea, xy_ind\n\n return out_data, grid_ind\n\n def voxelize_spconv(self, inputs, grid_name='grid', pt_fea_name='pt_fea'):\n grid_ind = inputs[grid_name]\n pt_fea = inputs[pt_fea_name]\n\n pt_fea_ten = [torch.from_numpy(i).type(torch.FloatTensor).cuda() for i in pt_fea]\n grid_ind_ten = [torch.from_numpy(i).cuda() for i in grid_ind]\n\n pt_fea = pt_fea_ten\n xy_ind = grid_ind_ten\n\n # concate everything\n cat_pt_ind = []\n for i_batch in range(len(xy_ind)):\n cat_pt_ind.append(F.pad(xy_ind[i_batch],(1,0),'constant',value = i_batch))\n\n cat_pt_fea = torch.cat(pt_fea,dim = 0)\n cat_pt_ind = torch.cat(cat_pt_ind,dim = 0)\n pt_num = cat_pt_ind.shape[0]\n\n # shuffle the data\n cur_dev = pt_fea[0].get_device()\n shuffled_ind = torch.randperm(pt_num,device = cur_dev)\n cat_pt_fea = cat_pt_fea[shuffled_ind,:]\n cat_pt_ind = cat_pt_ind[shuffled_ind,:]\n\n # unique xy grid index\n unq, unq_inv, unq_cnt = torch.unique(cat_pt_ind,return_inverse=True, return_counts=True, dim=0)\n unq = unq.type(torch.int64)\n\n # subsample pts\n if self.pt_selection == 'random':\n grp_ind = grp_range_torch(unq_cnt,cur_dev)[torch.argsort(torch.argsort(unq_inv))] # convert the array that is in the order of grid to the order of cat_pt_feature\n remain_ind = grp_ind < self.max_pt # randomly sample max_pt points inside a grid\n elif self.pt_selection == 'farthest':\n unq_ind = np.split(np.argsort(unq_inv.detach().cpu().numpy()), np.cumsum(unq_cnt.detach().cpu().numpy()[:-1]))\n remain_ind = np.zeros((pt_num,),dtype = np.bool)\n np_cat_fea = cat_pt_fea.detach().cpu().numpy()[:,:3]\n pool_in = []\n for i_inds in unq_ind:\n if len(i_inds) > self.max_pt:\n pool_in.append((np_cat_fea[i_inds,:],self.max_pt))\n if len(pool_in) > 0:\n pool = multiprocessing.Pool(multiprocessing.cpu_count())\n FPS_results = pool.starmap(parallel_FPS, pool_in)\n pool.close()\n pool.join()\n count = 0\n for i_inds in unq_ind:\n if len(i_inds) <= self.max_pt:\n remain_ind[i_inds] = True\n else:\n remain_ind[i_inds[FPS_results[count]]] = True\n count += 1\n\n cat_pt_fea = cat_pt_fea[remain_ind,:]\n cat_pt_ind = cat_pt_ind[remain_ind,:]\n unq_inv = unq_inv[remain_ind]\n unq_cnt = torch.clamp(unq_cnt,max=self.max_pt)\n\n # process feature\n processed_cat_pt_fea = self.vfe_model(cat_pt_fea)\n #TODO: maybe use pointnet to extract features inside each grid and each grid share the same parameters instead of apply pointnet to global point clouds?\n # This kind of global pointnet is more memory efficient cause otherwise we will have to alloc [480 x 360 x 32 x 64 x C] tensor in order to apply pointnet to each grid\n\n if self.pt_pooling == 'max':\n pooled_data = torch_scatter.scatter_max(processed_cat_pt_fea, unq_inv, dim=0)[0] # choose the max feature for each grid\n else: raise NotImplementedError\n\n if self.fea_compre:\n processed_pooled_data = self.fea_compression(pooled_data)\n else:\n processed_pooled_data = pooled_data\n\n # stuff pooled data into 4D tensor\n # out_data_dim = [len(pt_fea),self.grid_size[0],self.grid_size[1],self.pt_fea_dim]\n # out_data = torch.zeros(out_data_dim, dtype=torch.float32).to(cur_dev)\n # out_data[unq[:,0],unq[:,1],unq[:,2],:] = processed_pooled_data\n # out_data = out_data.permute(0,3,1,2)\n\n del pt_fea, xy_ind\n\n return unq, processed_pooled_data\n\n def calc_sem_label(self, sem_logits, inputs, need_add_one=True):\n vox_pred_labels = torch.argmax(sem_logits, dim=1)\n vox_pred_labels = vox_pred_labels.cpu().detach().numpy()\n grid_ind = inputs['grid']\n pt_pred_labels = []\n for i in range(len(grid_ind)):\n if need_add_one:\n pt_pred_labels.append(vox_pred_labels[i, grid_ind[i][:, 0], grid_ind[i][:, 1], grid_ind[i][:, 2]] + 1)\n else:\n pt_pred_labels.append(vox_pred_labels[i, grid_ind[i][:, 0], grid_ind[i][:, 1], grid_ind[i][:, 2]])\n return pt_pred_labels\n\n def calc_sem_label_point_logits(self, sem_logits, inputs, need_add_one=True):\n pts_pred_labels = torch.argmax(sem_logits, dim=1)\n pts_pred_labels = pts_pred_labels.cpu().detach().numpy()\n grid_ind = inputs['grid']\n pt_pred_labels = []\n for i in range(len(grid_ind)):\n if need_add_one:\n pt_pred_labels.append(pts_pred_labels + 1)\n else:\n pt_pred_labels.append(pts_pred_labels)\n return pt_pred_labels\n\n def update_evaluator(self, evaluator, sem_preds, ins_preds, inputs):\n for i in range(len(sem_preds)):\n eval_one_scan_w_fname(evaluator, inputs['pt_labs'][i].reshape(-1),\n inputs['pt_ins_labels'][i].reshape(-1),\n sem_preds[i], ins_preds[i], inputs['pcd_fname'][i])\n\n def update_evaluator_multi_frames(self, evaluator, sem_preds, ins_preds, inputs):\n for i in range(len(sem_preds)):\n eval_one_scan_w_fname(evaluator, inputs['pt_labs'][i][inputs['mask_np'][i].reshape(-1) == 0].reshape(-1),\n inputs['pt_ins_labels'][i][inputs['mask_np'][i].reshape(-1) == 0].reshape(-1),\n sem_preds[i][inputs['mask_np'][i].reshape(-1) == 0], ins_preds[i][inputs['mask_np'][i].reshape(-1) == 0], inputs['pcd_fname'][i])\n\n def forward(self, x):\n raise NotImplementedError\n\nclass PolarSpconv(PolarBaseClass):\n def __init__(self, cfg):\n super(PolarSpconv, self).__init__(cfg)\n self.backbone = getattr(spconv_unet, cfg.MODEL.BACKBONE.NAME)(cfg)\n self.sem_head = getattr(spconv_unet, cfg.MODEL.SEM_HEAD.NAME)(cfg)\n self.vfe_model = getattr(PointNet, cfg.MODEL.VFE.NAME)(cfg)\n\n if cfg.MODEL.SEM_LOSS == 'Lovasz_loss':\n self.sem_loss_lovasz = lovasz_losses.lovasz_softmax\n if cfg.DATA_CONFIG.DATASET_NAME.startswith('SemanticKitti'):\n weights = torch.zeros(20, dtype=torch.float)\n weights[0] = 1.0\n weights[1] = 2.293\n weights[2] = 85.756\n weights[3] = 71.511\n weights[4] = 31.596\n weights[5] = 35.624\n weights[6] = 74.761\n weights[7] = 88.722\n weights[8] = 96.389\n weights[9] = 1.00\n weights[10] = 6.362\n weights[11] = 1.00\n weights[12] = 20.387\n weights[13] = 1.00\n weights[14] = 1.363\n weights[15] = 1.00\n weights[16] = 14.214\n weights[17] = 1.263\n weights[18] = 25.936\n weights[19] = 61.896\n else:\n raise NotImplementedError\n self.sem_loss = torch.nn.CrossEntropyLoss(weight=weights.cuda(), ignore_index=0)\n else:\n raise NotImplementedError\n\n def calc_loss(self, sem_logits, inputs, need_minus_one=True):\n if need_minus_one:\n vox_label = SemKITTI2train(inputs['vox_label']).type(torch.LongTensor).cuda()\n else:\n vox_label = inputs['vox_label'].type(torch.LongTensor).cuda()\n\n sem_loss = self.sem_loss_lovasz(torch.nn.functional.softmax(sem_logits), vox_label,ignore=self.ignore_label) + self.sem_loss(sem_logits,vox_label)\n\n loss = sem_loss\n\n ret_dict = {}\n ret_dict['sem_loss'] = sem_loss\n ret_dict['loss'] = loss\n\n return ret_dict\n\n def forward(self, batch, is_test=False, before_merge_evaluator=None, after_merge_evaluator=None, require_cluster=True):\n coor, feature_3d = self.voxelize_spconv(batch)\n sem_fea, _ = self.backbone(feature_3d, coor, len(batch['grid']))\n sem_logits = self.sem_head(sem_fea)\n loss_dict = self.calc_loss(sem_logits, batch, need_minus_one=False)\n\n if is_test:\n pt_sem_preds = self.calc_sem_label(sem_logits, batch, need_add_one=False)\n pt_ins_ids_preds = [np.zeros_like(pt_sem_preds[i]) for i in range(len(pt_sem_preds))]\n merged_sem_preds = pt_sem_preds\n if 'mask' in batch:\n self.update_evaluator_multi_frames(after_merge_evaluator, merged_sem_preds, pt_ins_ids_preds, batch)\n else:\n self.update_evaluator(after_merge_evaluator, merged_sem_preds, pt_ins_ids_preds, batch)\n loss_dict['sem_preds'] = merged_sem_preds\n loss_dict['ins_preds'] = pt_ins_ids_preds\n loss_dict['ins_num'] = 0\n\n return loss_dict\n\nclass PolarOffset(PolarBaseClass):\n def __init__(self, cfg, need_create_model=True):\n super(PolarOffset, self).__init__(cfg)\n self.ins_loss_name = cfg.MODEL.INS_LOSS\n self.ins_embedding_dim = cfg.MODEL.INS_HEAD.EMBEDDING_CHANNEL\n if not need_create_model:\n return\n self.backbone = getattr(BEV_Unet, cfg.MODEL.BACKBONE.NAME)(cfg)\n self.sem_head = getattr(BEV_Unet, cfg.MODEL.SEM_HEAD.NAME)(cfg)\n self.ins_head = getattr(BEV_Unet, cfg.MODEL.INS_HEAD.NAME)(cfg)\n self.vfe_model = getattr(PointNet, cfg.MODEL.VFE.NAME)(cfg)\n\n self.ins_loss = getattr(instance_losses, cfg.MODEL.INS_LOSS)\n if cfg.MODEL.SEM_LOSS == 'Lovasz_loss':\n self.sem_loss_lovasz = lovasz_losses.lovasz_softmax\n self.sem_loss = torch.nn.CrossEntropyLoss(ignore_index=cfg.DATA_CONFIG.DATALOADER.CONVERT_IGNORE_LABEL)\n else:\n raise NotImplementedError\n\n self.cluster_fn_wrapper = getattr(clustering, cfg.MODEL.POST_PROCESSING.CLUSTER_ALGO)\n self.cluster_fn = self.cluster_fn_wrapper(cfg)\n\n self.merge_func_name = cfg.MODEL.POST_PROCESSING.MERGE_FUNC\n\n def calc_loss(self, sem_logits, pred_offsets, inputs, need_minus_one=True):\n if need_minus_one:\n vox_label = SemKITTI2train(inputs['vox_label']).type(torch.LongTensor).cuda()\n else:\n vox_label = inputs['vox_label'].type(torch.LongTensor).cuda()\n\n pt_valid = [torch.from_numpy(i).cuda() for i in inputs['pt_valid']]\n if self.ins_loss_name.find('semantic_centroids') != -1:\n offset_loss_list = self.ins_loss(pred_offsets, inputs['pt_ins_labels'], pt_valid, gt_semantic_label=inputs['pt_labs'])\n elif self.ins_loss_name.find('embedding_contrastive_loss') != -1:\n offset_loss_list = self.ins_loss(pred_offsets, inputs['pt_ins_labels'], pt_valid, gt_semantic_label=inputs['pt_labs'], xyz=inputs['pt_cart_xyz'])\n elif self.ins_loss_name.find('embedding_discriminative') != -1:\n offset_loss_list = self.ins_loss(pred_offsets, inputs['pt_ins_labels'], pt_valid)\n else:\n pt_offsets = [torch.from_numpy(i).cuda() for i in inputs['pt_offsets']]\n offset_loss_list = self.ins_loss(pred_offsets, pt_offsets, pt_valid)\n\n sem_loss = self.sem_loss_lovasz(torch.nn.functional.softmax(sem_logits), vox_label,ignore=self.ignore_label) + self.sem_loss(sem_logits,vox_label)\n #if self.ins_loss_name == 'embedding_contrastive_loss':\n # loss = 5 * sem_loss + sum(offset_loss_list)\n #else:\n loss = sem_loss + sum(offset_loss_list)\n\n ret_dict = {}\n ret_dict['offset_loss_list'] = offset_loss_list\n ret_dict['sem_loss'] = sem_loss\n ret_dict['loss'] = loss\n\n return ret_dict\n\n def clustering(self, sem_preds, pred_offsets, inputs):\n grid_ind = inputs['grid']\n pt_cart_xyz = inputs['pt_cart_xyz']\n pt_pred_offsets = [pred_offsets[i].detach().cpu().numpy().reshape(-1, self.ins_embedding_dim) for i in range(len(pred_offsets))]\n pt_pred_valid = []\n for i in range(len(grid_ind)):\n pt_pred_valid.append(np.isin(sem_preds[i], valid_xentropy_ids).reshape(-1))\n pred_ins_ids = self.cluster_fn(pt_cart_xyz, pt_pred_offsets, pt_pred_valid)\n return pred_ins_ids\n\n def merge_ins_sem(self, sem_preds, pred_ins_ids, logits=None, inputs=None):\n merged_sem_preds = []\n for i in range(len(sem_preds)):\n if self.merge_func_name == 'merge_ins_sem':\n merged_sem_preds.append(common_utils.merge_ins_sem(sem_preds[i], pred_ins_ids[i]))\n elif self.merge_func_name == 'merge_ins_sem_logits_size_based':\n merged_sem_preds.append(common_utils.merge_ins_sem_logits_size_based(sem_preds[i], pred_ins_ids[i], i, logits, inputs))\n elif self.merge_func_name == 'none':\n merged_sem_preds.append(sem_preds[i])\n return merged_sem_preds\n\n def forward(self, batch, is_test=False, before_merge_evaluator=None, after_merge_evaluator=None, require_cluster=True):\n out_data, grid_ind = self.voxelize(batch)\n sem_fea, ins_fea = self.backbone(out_data)\n sem_logits = self.sem_head(sem_fea)\n pred_offsets, _ = self.ins_head(ins_fea, grid_ind)\n loss_dict = self.calc_loss(sem_logits, pred_offsets, batch)\n\n if is_test:\n pt_sem_preds = self.calc_sem_label(sem_logits, batch)\n if require_cluster:\n pt_ins_ids_preds = self.clustering(pt_sem_preds, pred_offsets, batch)\n else:\n pt_ins_ids_preds = [np.zeros_like(pt_sem_preds[i]) for i in range(len(pt_sem_preds))]\n if require_cluster:\n merged_sem_preds = self.merge_ins_sem(pt_sem_preds, pt_ins_ids_preds)\n else:\n merged_sem_preds = pt_sem_preds\n if before_merge_evaluator != None:\n self.update_evaluator(before_merge_evaluator, pt_sem_preds, pt_ins_ids_preds, batch)\n if after_merge_evaluator != None:\n self.update_evaluator(after_merge_evaluator, merged_sem_preds, pt_ins_ids_preds, batch)\n\n loss_dict['sem_preds'] = merged_sem_preds\n loss_dict['ins_preds'] = pt_ins_ids_preds\n\n return loss_dict\n\nclass PolarOffsetSpconv(PolarOffset):\n def __init__(self, cfg):\n super(PolarOffsetSpconv, self).__init__(cfg, need_create_model=False)\n self.backbone = getattr(spconv_unet, cfg.MODEL.BACKBONE.NAME)(cfg)\n self.sem_head = getattr(spconv_unet, cfg.MODEL.SEM_HEAD.NAME)(cfg)\n self.ins_head = getattr(spconv_unet, cfg.MODEL.INS_HEAD.NAME)(cfg)\n self.vfe_model = getattr(PointNet, cfg.MODEL.VFE.NAME)(cfg)\n\n self.ins_loss = getattr(instance_losses, cfg.MODEL.INS_LOSS)\n if cfg.MODEL.SEM_LOSS == 'Lovasz_loss':\n self.sem_loss_lovasz = lovasz_losses.lovasz_softmax\n if cfg.DATA_CONFIG.DATASET_NAME.startswith('SemanticKitti'):\n weights = torch.zeros(20, dtype=torch.float)\n weights[0] = 1.0\n weights[1] = 2.293\n weights[2] = 85.756\n weights[3] = 71.511\n weights[4] = 31.596\n weights[5] = 35.624\n weights[6] = 74.761\n weights[7] = 88.722\n weights[8] = 96.389\n weights[9] = 1.00\n weights[10] = 6.362\n weights[11] = 1.00\n weights[12] = 20.387\n weights[13] = 1.00\n weights[14] = 1.363\n weights[15] = 1.00\n weights[16] = 14.214\n weights[17] = 1.263\n weights[18] = 25.936\n weights[19] = 61.896\n else:\n raise NotImplementedError\n self.sem_loss = torch.nn.CrossEntropyLoss(weight=weights.cuda(), ignore_index=0)\n else:\n raise NotImplementedError\n\n cluster_fn_wrapper = getattr(clustering, cfg.MODEL.POST_PROCESSING.CLUSTER_ALGO)\n self.cluster_fn = cluster_fn_wrapper(cfg)\n self.is_fix_semantic = False\n\n self.merge_func_name = cfg.MODEL.POST_PROCESSING.MERGE_FUNC\n\n def fix_semantic_parameters(self):\n fix_list = [self.backbone, self.sem_head, self.vfe_model, self.fea_compression]\n for mod in fix_list:\n for p in mod.parameters():\n p.requires_grad = False\n self.is_fix_semantic = True\n\n def forward(self, batch, is_test=False, before_merge_evaluator=None, after_merge_evaluator=None, require_cluster=True, require_merge=True):\n if self.is_fix_semantic:\n with torch.no_grad():\n coor, feature_3d = self.voxelize_spconv(batch)\n sem_fea, ins_fea = self.backbone(feature_3d, coor, len(batch['grid']))\n sem_logits = self.sem_head(sem_fea)\n else:\n coor, feature_3d = self.voxelize_spconv(batch)\n sem_fea, ins_fea = self.backbone(feature_3d, coor, len(batch['grid']))\n sem_logits = self.sem_head(sem_fea)\n pred_offsets, _ = self.ins_head(ins_fea, batch)\n loss_dict = self.calc_loss(sem_logits, pred_offsets, batch, need_minus_one=False)\n\n if is_test:\n pt_sem_preds = self.calc_sem_label(sem_logits, batch, need_add_one=False)\n if require_cluster:\n pt_ins_ids_preds = self.clustering(pt_sem_preds, pred_offsets, batch)\n else:\n pt_ins_ids_preds = [np.zeros_like(pt_sem_preds[i]) for i in range(len(pt_sem_preds))]\n if require_merge:\n merged_sem_preds = self.merge_ins_sem(pt_sem_preds, pt_ins_ids_preds, sem_logits, batch)\n else:\n merged_sem_preds = pt_sem_preds\n if before_merge_evaluator != None:\n if 'mask' in batch:\n self.update_evaluator_multi_frames(before_merge_evaluator, pt_sem_preds, pt_ins_ids_preds, batch)\n else:\n self.update_evaluator(before_merge_evaluator, pt_sem_preds, pt_ins_ids_preds, batch)\n if after_merge_evaluator != None:\n if 'mask' in batch:\n self.update_evaluator_multi_frames(after_merge_evaluator, merged_sem_preds, pt_ins_ids_preds, batch)\n else:\n self.update_evaluator(after_merge_evaluator, merged_sem_preds, pt_ins_ids_preds, batch)\n\n loss_dict['sem_preds'] = merged_sem_preds\n loss_dict['ins_preds'] = pt_ins_ids_preds\n loss_dict['ins_num'] = np.unique(pt_ins_ids_preds[0]).shape[0]\n\n return loss_dict\n\nclass PolarOffsetSpconvPytorchMeanshift(PolarOffsetSpconv):\n def __init__(self, cfg):\n super(PolarOffsetSpconvPytorchMeanshift, self).__init__(cfg)\n self.pytorch_meanshift = pytorch_meanshift.PytorchMeanshift(cfg, self.ins_loss, self.cluster_fn)\n self.is_fix_semantic_instance = False\n\n def fix_semantic_instance_parameters(self):\n fix_list = [self.backbone, self.sem_head, self.vfe_model, self.fea_compression, self.ins_head]\n for mod in fix_list:\n for p in mod.parameters():\n p.requires_grad = False\n self.is_fix_semantic_instance = True\n\n def forward(self, batch, is_test=False, before_merge_evaluator=None, after_merge_evaluator=None, require_cluster=True, require_merge=True):\n if self.is_fix_semantic_instance:\n with torch.no_grad():\n coor, feature_3d = self.voxelize_spconv(batch)\n sem_fea, ins_fea = self.backbone(feature_3d, coor, len(batch['grid']))\n sem_logits = self.sem_head(sem_fea)\n pred_offsets, ins_fea_list = self.ins_head(ins_fea, batch)\n else:\n if self.is_fix_semantic:\n with torch.no_grad():\n coor, feature_3d = self.voxelize_spconv(batch)\n sem_fea, ins_fea = self.backbone(feature_3d, coor, len(batch['grid']))\n sem_logits = self.sem_head(sem_fea)\n else:\n coor, feature_3d = self.voxelize_spconv(batch)\n sem_fea, ins_fea = self.backbone(feature_3d, coor, len(batch['grid']))\n sem_logits = self.sem_head(sem_fea)\n pred_offsets, ins_fea_list = self.ins_head(ins_fea, batch)\n loss_dict = self.calc_loss(sem_logits, pred_offsets, batch, need_minus_one=False)\n valid = batch['pt_valid']\n valid = [v.reshape(-1) for v in valid]\n if is_test:\n pt_sem_preds = self.calc_sem_label(sem_logits, batch, need_add_one=False)\n valid = []\n for i in range(len(batch['grid'])):\n valid.append(np.isin(pt_sem_preds[i], valid_xentropy_ids).reshape(-1))\n if self.pytorch_meanshift.data_mode == 'offset':\n embedding = [offset + torch.from_numpy(xyz).cuda() for offset, xyz in zip(pred_offsets, batch['pt_cart_xyz'])]\n else:\n raise NotImplementedError\n batch['ins_fea_list'] = ins_fea_list\n pt_ins_ids_preds, meanshift_loss, bandwidth_weight_summary = self.pytorch_meanshift(batch['pt_cart_xyz'], embedding, valid, batch, need_cluster=is_test)\n\n loss_dict['bandwidth_weight_summary'] = bandwidth_weight_summary\n loss_dict['meanshift_loss'] = meanshift_loss\n loss_dict['offset_loss_list'] += meanshift_loss\n loss_dict['loss'] += sum(meanshift_loss)\n\n if is_test:\n if require_cluster:\n merged_sem_preds = self.merge_ins_sem(pt_sem_preds, pt_ins_ids_preds)\n else:\n merged_sem_preds = pt_sem_preds\n # if before_merge_evaluator != None:\n # self.update_evaluator(before_merge_evaluator, pt_sem_preds, pt_ins_ids_preds, batch)\n # if after_merge_evaluator != None:\n # self.update_evaluator(after_merge_evaluator, merged_sem_preds, pt_ins_ids_preds, batch)\n if before_merge_evaluator != None:\n if 'mask' in batch:\n self.update_evaluator_multi_frames(before_merge_evaluator, pt_sem_preds, pt_ins_ids_preds, batch)\n else:\n self.update_evaluator(before_merge_evaluator, pt_sem_preds, pt_ins_ids_preds, batch)\n if after_merge_evaluator != None:\n if 'mask' in batch:\n self.update_evaluator_multi_frames(after_merge_evaluator, merged_sem_preds, pt_ins_ids_preds, batch)\n else:\n self.update_evaluator(after_merge_evaluator, merged_sem_preds, pt_ins_ids_preds, batch)\n\n if 'mask' in batch:\n loss_dict['sem_preds'] = [m[batch['mask_np'][i].reshape(-1) == 0] for i, m in enumerate(merged_sem_preds)]\n loss_dict['ins_preds'] = [p[batch['mask_np'][i].reshape(-1) == 0] for i, p in enumerate(pt_ins_ids_preds)]\n else:\n loss_dict['sem_preds'] = merged_sem_preds\n loss_dict['ins_preds'] = pt_ins_ids_preds\n loss_dict['ins_num'] = np.unique(pt_ins_ids_preds[0]).shape[0]\n\n return loss_dict\n\nclass PolarOffsetSpconvPytorchMeanshiftTrackingMultiFrames(PolarOffsetSpconvPytorchMeanshift):\n def __init__(self, cfg):\n super(PolarOffsetSpconvPytorchMeanshiftTrackingMultiFrames, self).__init__(cfg)\n self.is_init = False\n self.before_ins_ids_preds = None\n self.before_valid_preds = None\n self.before_seq = None\n\n def update_evaluator_multi_frames(self, evaluator, sem_preds, ins_preds, inputs, window_k):\n assert len(sem_preds) == 1\n for i in range(len(sem_preds)):\n eval_one_scan_vps(evaluator, inputs['pt_labs'][i][inputs['mask_np'][i].reshape(-1) == 0].reshape(-1),\n inputs['pt_ins_labels'][i][inputs['mask_np'][i].reshape(-1) == 0].reshape(-1),\n sem_preds[i][inputs['mask_np'][i].reshape(-1) == 0].reshape(-1),\n ins_preds[i].reshape(-1), window_k)\n\n def forward(self, batch, is_test=False, merge_evaluator_list=None, merge_evaluator_window_k_list=None, require_cluster=True, require_merge=True):\n assert is_test\n if self.is_fix_semantic_instance:\n with torch.no_grad():\n coor, feature_3d = self.voxelize_spconv(batch)\n sem_fea, ins_fea = self.backbone(feature_3d, coor, len(batch['grid']))\n sem_logits = self.sem_head(sem_fea)\n pred_offsets, ins_fea_list = self.ins_head(ins_fea, batch)\n else:\n if self.is_fix_semantic:\n with torch.no_grad():\n coor, feature_3d = self.voxelize_spconv(batch)\n sem_fea, ins_fea = self.backbone(feature_3d, coor, len(batch['grid']))\n sem_logits = self.sem_head(sem_fea)\n else:\n coor, feature_3d = self.voxelize_spconv(batch)\n sem_fea, ins_fea = self.backbone(feature_3d, coor, len(batch['grid']))\n sem_logits = self.sem_head(sem_fea)\n pred_offsets, ins_fea_list = self.ins_head(ins_fea, batch)\n loss_dict = self.calc_loss(sem_logits, pred_offsets, batch, need_minus_one=False)\n valid = batch['pt_valid']\n if is_test:\n pt_sem_preds = self.calc_sem_label(sem_logits, batch, need_add_one=False)\n valid = []\n for i in range(len(batch['grid'])):\n valid.append(np.isin(pt_sem_preds[i], valid_xentropy_ids).reshape(-1))\n if self.pytorch_meanshift.data_mode == 'offset':\n embedding = [offset + torch.from_numpy(xyz).cuda() for offset, xyz in zip(pred_offsets, batch['pt_cart_xyz'])]\n else:\n raise NotImplementedError\n batch['ins_fea_list'] = ins_fea_list\n pt_ins_ids_preds, meanshift_loss, bandwidth_weight_summary = self.pytorch_meanshift(batch['pt_cart_xyz'], embedding, valid, batch, need_cluster=is_test)\n\n loss_dict['bandwidth_weight_summary'] = bandwidth_weight_summary\n loss_dict['meanshift_loss'] = meanshift_loss\n loss_dict['offset_loss_list'] += meanshift_loss\n loss_dict['loss'] += sum(meanshift_loss)\n\n if is_test:\n if require_cluster:\n merged_sem_preds = self.merge_ins_sem(pt_sem_preds, pt_ins_ids_preds)\n else:\n merged_sem_preds = pt_sem_preds\n\n cur_pcd_fname = batch['pcd_fname'][0]\n cur_pcd_seq = cur_pcd_fname.split('/')[-3]\n if self.before_seq == None:\n self.before_seq = cur_pcd_seq\n elif self.before_seq != cur_pcd_seq:\n self.before_seq = cur_pcd_seq\n self.is_init = False\n\n ins_preds_tracking, matching_list = self.tracking_test(valid, pt_ins_ids_preds, batch)\n loss_dict['ins_preds'] = ins_preds_tracking\n loss_dict['matching_list'] = matching_list\n\n if merge_evaluator_list is not None:\n for evaluator, window_k in zip(merge_evaluator_list, merge_evaluator_window_k_list):\n self.update_evaluator_multi_frames(evaluator, merged_sem_preds, ins_preds_tracking, batch, window_k)\n\n loss_dict['sem_preds'] = [m[batch['mask_np'][i].reshape(-1) == 0] for i, m in enumerate(merged_sem_preds)]\n loss_dict['ins_num'] = np.unique(ins_preds_tracking[0]).shape[0]\n\n return loss_dict\n\n def matching(self, after_ins_ids_gt, after_valid_gt, after_ins_ids_preds, after_valid_preds):\n offset = 2**32\n\n x_inst_in_cl_mask = after_valid_preds.reshape(-1)\n y_inst_in_cl_mask = after_valid_gt.reshape(-1)\n \n x_inst_in_cl = after_ins_ids_preds.reshape(-1) * x_inst_in_cl_mask.astype(np.int64)\n y_inst_in_cl = after_ins_ids_gt.reshape(-1) * y_inst_in_cl_mask.astype(np.int64)\n\n unique_pred, counts_pred = np.unique(x_inst_in_cl[x_inst_in_cl > 0], return_counts=True)\n id2idx_pred = {id: idx for idx, id in enumerate(unique_pred)}\n matched_pred = np.array([False] * unique_pred.shape[0])\n\n unique_gt, counts_gt = np.unique(y_inst_in_cl[y_inst_in_cl > 0], return_counts=True)\n id2idx_gt = {id: idx for idx, id in enumerate(unique_gt)}\n matched_gt = np.array([False] * unique_gt.shape[0])\n\n valid_combos = np.logical_and(x_inst_in_cl > 0, y_inst_in_cl > 0)\n offset_combo = x_inst_in_cl[valid_combos] + offset * y_inst_in_cl[valid_combos]\n unique_combo, counts_combo = np.unique(offset_combo, return_counts=True)\n\n gt_labels = unique_combo // offset\n pred_labels = unique_combo % offset\n gt_areas = np.array([counts_gt[id2idx_gt[id]] for id in gt_labels])\n pred_areas = np.array([counts_pred[id2idx_pred[id]] for id in pred_labels])\n intersections = counts_combo\n unions = gt_areas + pred_areas - intersections\n ious = intersections.astype(np.float) / unions.astype(np.float)\n\n tp_indexes = ious > 0.5\n\n return pred_labels[tp_indexes], gt_labels[tp_indexes]\n\n def tracking_test(self, pred_valid, pred_ins_ids, batch):\n batch_size = len(pred_valid)\n assert batch_size == 1\n ins_ids_tracking_list = []\n matching_list = []\n for b in range(batch_size):\n after_mask = batch['mask_np'][b].reshape(-1) == 0\n after_ins_ids_preds = pred_ins_ids[b][after_mask]\n after_valid_preds = pred_valid[b][after_mask]\n \n after_valid_ins_ids_preds = after_ins_ids_preds[after_valid_preds].reshape(-1)\n after_unique_ins_ids_preds, after_unique_ins_ids_preds_counts = np.unique(after_valid_ins_ids_preds, return_counts=True)\n # after_unique_ins_ids_preds = after_unique_ins_ids_preds[after_unique_ins_ids_preds_counts > min_points].reshape(-1)\n if after_unique_ins_ids_preds.shape[0] == 0:\n self.is_init = False\n return [after_ins_ids_preds], matching_list\n\n if not self.is_init:\n self.is_init = True\n self.before_ins_ids_preds = after_ins_ids_preds\n self.before_valid_preds = after_valid_preds\n return [after_ins_ids_preds], matching_list\n\n before_mask = batch['mask_np'][b].reshape(-1) == 1\n cur_before_ins_ids_preds = pred_ins_ids[b][before_mask]\n cur_before_valid_preds = pred_valid[b][before_mask]\n\n cur_before_labels, before_labels = self.matching(\n self.before_ins_ids_preds, self.before_valid_preds,\n cur_before_ins_ids_preds, cur_before_valid_preds\n )\n cur2before_dict = {c:b for c,b in zip(cur_before_labels, before_labels)}\n\n ins_ids_tracking = np.zeros_like(after_ins_ids_preds)\n cur_max = np.max(self.before_ins_ids_preds)\n for au in after_unique_ins_ids_preds:\n if au in cur2before_dict:\n ins_ids_tracking[after_ins_ids_preds == au] = cur2before_dict[au]\n else:\n cur_max += 1\n ins_ids_tracking[after_ins_ids_preds == au] = cur_max\n ins_ids_tracking_list.append(ins_ids_tracking)\n\n self.before_ins_ids_preds = ins_ids_tracking\n self.before_valid_preds = after_valid_preds\n\n return ins_ids_tracking_list, matching_list\n" ]
[ [ "torch.nn.functional.softmax", "torch.argsort", "torch.no_grad", "torch.cat", "numpy.logical_and", "torch.nn.functional.pad", "numpy.isin", "torch.from_numpy", "torch.unique", "numpy.unique", "numpy.zeros", "torch.argmax", "numpy.max", "numpy.array", "numpy.zeros_like", "torch.nn.Linear", "torch.nn.CrossEntropyLoss", "torch.randperm", "torch.zeros", "torch.nn.ReLU", "torch.clamp" ] ]
vinitra/keras-onnx
[ "17d86705f566bee56307abd13a60b79776a58c0e" ]
[ "applications/nightly_build/test_deep_speech.py" ]
[ "###############################################################################\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n###############################################################################\nimport os\nimport sys\nimport unittest\nimport keras2onnx\nimport numpy as np\nfrom keras2onnx.proto import keras\nfrom onnxconverter_common.onnx_ex import get_maximum_opset_supported\nfrom os.path import dirname, abspath\nsys.path.insert(0, os.path.join(dirname(abspath(__file__)), '../../tests/'))\nfrom test_utils import run_keras_and_ort, test_level_0\nK = keras.backend\n\nActivation = keras.layers.Activation\nAveragePooling2D = keras.layers.AveragePooling2D\nAdd = keras.layers.Add\nBatchNormalization = keras.layers.BatchNormalization\nconcatenate = keras.layers.concatenate\nConv2D = keras.layers.Conv2D\nDense = keras.layers.Dense\nDropout = keras.layers.Dropout\nEmbedding = keras.layers.Embedding\nFlatten = keras.layers.Flatten\nGlobalAveragePooling2D = keras.layers.GlobalAveragePooling2D\nInput = keras.layers.Input\nLambda = keras.layers.Lambda\nLeakyReLU = keras.layers.LeakyReLU\nMaxPooling2D = keras.layers.MaxPooling2D\nmultiply = keras.layers.multiply\nPermute = keras.layers.Permute\nReshape = keras.layers.Reshape\nUpSampling2D = keras.layers.UpSampling2D\nZeroPadding2D = keras.layers.ZeroPadding2D\n\nSequential = keras.models.Sequential\nModel = keras.models.Model\nlayers = keras.layers\n\n\n# Model from https://github.com/rolczynski/Automatic-Speech-Recognition\nclass TestDeepSpeech(unittest.TestCase):\n\n def setUp(self):\n self.model_files = []\n\n def tearDown(self):\n for fl in self.model_files:\n os.remove(fl)\n\n @unittest.skipIf(get_maximum_opset_supported() < 11,\n \"Deep speech conversion need opset >= 11.\")\n def test_deep_speech(self):\n K.clear_session()\n input_dim = 20\n output_dim = 10\n context = 7\n units = 1024\n dropouts = (0.1, 0.1, 0)\n\n # Define input tensor [batch, time, features]\n input_tensor = layers.Input([None, input_dim], name='X')\n\n # Add 4th dimension [batch, time, frequency, channel]\n x = layers.Lambda(keras.backend.expand_dims,\n arguments=dict(axis=-1))(input_tensor)\n # Fill zeros around time dimension\n x = layers.ZeroPadding2D(padding=(context, 0))(x)\n # Convolve signal in time dim\n receptive_field = (2 * context + 1, input_dim)\n x = layers.Conv2D(filters=units, kernel_size=receptive_field)(x)\n # Squeeze into 3rd dim array\n x = layers.Lambda(keras.backend.squeeze, arguments=dict(axis=2))(x)\n # Add non-linearity\n x = layers.ReLU(max_value=20)(x)\n # Use dropout as regularization\n x = layers.Dropout(rate=dropouts[0])(x)\n\n # 2nd and 3rd FC layers do a feature extraction base on a narrow\n # context of convolutional layer\n x = layers.TimeDistributed(layers.Dense(units))(x)\n x = layers.ReLU(max_value=20)(x)\n x = layers.Dropout(rate=dropouts[1])(x)\n\n x = layers.TimeDistributed(layers.Dense(units))(x)\n x = layers.ReLU(max_value=20)(x)\n x = layers.Dropout(rate=dropouts[2])(x)\n\n # Use recurrent layer to have a broader context\n x = layers.Bidirectional(layers.LSTM(units, return_sequences=True),\n merge_mode='sum')(x)\n\n # Return at each time step logits along characters. Then CTC\n # computation is more stable, in contrast to the softmax.\n output_tensor = layers.TimeDistributed(layers.Dense(output_dim))(x)\n model = keras.Model(input_tensor, output_tensor, name='DeepSpeech')\n data = np.random.rand(2, 3, input_dim).astype(np.float32)\n expected = model.predict(data)\n onnx_model = keras2onnx.convert_keras(model, model.name)\n self.assertTrue(\n run_keras_and_ort(onnx_model.graph.name, onnx_model, model, data, expected, self.model_files))\n\n @unittest.skipIf(get_maximum_opset_supported() < 11,\n \"Deep speech conversion need opset >= 11.\")\n def test_deep_speech_2(self):\n K.clear_session()\n input_dim = 20\n output_dim = 10\n rnn_units = 800\n # Define input tensor [batch, time, features]\n input_tensor = layers.Input([None, input_dim], name='X')\n\n # Add 4th dimension [batch, time, frequency, channel]\n x = layers.Lambda(keras.backend.expand_dims,\n arguments=dict(axis=-1))(input_tensor)\n x = layers.Conv2D(filters=32,\n kernel_size=[11, 41],\n strides=[2, 2],\n padding='same',\n use_bias=False,\n name='conv_1')(x)\n x = layers.BatchNormalization(name='conv_1_bn')(x)\n x = layers.ReLU(name='conv_1_relu')(x)\n\n x = layers.Conv2D(filters=32,\n kernel_size=[11, 21],\n strides=[1, 2],\n padding='same',\n use_bias=False,\n name='conv_2')(x)\n x = layers.BatchNormalization(name='conv_2_bn')(x)\n x = layers.ReLU(name='conv_2_relu')(x)\n # We need to squeeze to 3D tensor. Thanks to the stride in frequency\n # domain, we reduce the number of features four times for each channel.\n x = layers.Reshape([-1, input_dim//4*32])(x)\n\n for i in [1, 2, 3, 4, 5]:\n recurrent = layers.GRU(units=rnn_units,\n activation='tanh',\n recurrent_activation='sigmoid',\n use_bias=True,\n return_sequences=True,\n reset_after=True,\n name='gru_'+str(i))\n x = layers.Bidirectional(recurrent,\n name='bidirectional'+str(i),\n merge_mode='concat')(x)\n x = layers.Dropout(rate=0.5)(x) if i < 5 else x # Only between\n\n # Return at each time step logits along characters. Then CTC\n # computation is more stable, in contrast to the softmax.\n x = layers.TimeDistributed(layers.Dense(units=rnn_units*2), name='dense_1')(x)\n x = layers.ReLU(name='dense_1_relu')(x)\n x = layers.Dropout(rate=0.5)(x)\n output_tensor = layers.TimeDistributed(layers.Dense(units=output_dim),\n name='dense_2')(x)\n\n model = keras.Model(input_tensor, output_tensor, name='DeepSpeech2')\n data = np.random.rand(2, 3, input_dim).astype(np.float32)\n expected = model.predict(data)\n onnx_model = keras2onnx.convert_keras(model, model.name)\n self.assertTrue(\n run_keras_and_ort(onnx_model.graph.name, onnx_model, model, data, expected, self.model_files))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.random.rand" ] ]
schmocker/Pyjamas
[ "52a72d6e8b915f77a2194d4e7d53c46d0ec28c17" ]
[ "Models/Electricity_Market/Tiers/V001/model.py" ]
[ "from pyjamas_core import Supermodel\nfrom pyjamas_core.util import Input, Output, Property\nfrom datetime import datetime, timedelta\nfrom Models._utils.time import datetime2utc_time, utc_time2datetime\nimport numpy as np\nfrom pytz import timezone\nimport json\nfrom scipy.interpolate import griddata\nimport pandas as pd\nimport requests\nimport os\n\n# define the model class and inherit from class \"Supermodel\"\nclass Model(Supermodel):\n # model constructor\n def __init__(self, id, name: str):\n # instantiate supermodel\n super(Model, self).__init__(id, name)\n\n # define inputs\n self.inputs['stock_ex_price'] = Input(name='Stock exchange price', unit='€/J', info=\"stock exchange price\")\n self.inputs['distnet_costs'] = Input(name='Distribution network cost', unit='{-, €/J}', info=\"distribution network cost\")\n self.inputs['service_cost'] = Input(name='Service cost', unit='€/J', info=\"service cost\")\n self.inputs['taxes'] = Input(name='Taxes', unit='€/J', info=\"taxes\")\n self.inputs['futures'] = Input(name='Futures', unit='s', info=\"Futures\")\n\n # define outputs\n self.outputs['el_rate'] = Output(name='Electricity rate', unit='€/J', info='electricity rate')\n self.outputs['times'] = Output(name='Times', unit='s', info='Times')\n self.outputs['y_scaling'] = Output(name='Scaling of y axis', unit='', info='Scaling of y axis')\n self.outputs['y_unit'] = Output(name='Unit of y axis', unit='', info='Unit of y axis')\n self.outputs['y_label'] = Output(name='y label', unit='', info='Label of y axis')\n\n # define properties\n ET_def = {\"location\": [\"Baden\"],\n \"border\": [[-1.0, -0.5, -0.2, 0.0, 0.2, 0.5, 1.0]],\n \"weight\": [[-0.3, -0.6, -0.8, 1.1, 1.3, 1.5]]}\n NT_def = {\"location\": [\"Baden\"],\n \"border\": [[-1.0, -0.8, -0.5, 0.0, 0.4, 0.8, 1.0]],\n \"weight\": [[-0.5, -0.6, -0.8, 1.2, 1.5, 1.8]]}\n ET_def = json.dumps(ET_def)\n NT_def = json.dumps(NT_def)\n self.properties['weight_ET'] = Property(default=ET_def, data_type=str, name='energy tiers', unit='-',\n info='borders and weights of energy tiers', example=ET_def)\n self.properties['weight_NT'] = Property(default=NT_def, data_type=str, name='net tiers', unit='-',\n info='borders and weights of net tiers', example=NT_def)\n self.properties[\"scaling\"] = Property(default=1, data_type=float, name='Scaling factor', unit='-',\n info='Scaling factor for y axis', example='3.6e9')\n self.properties[\"y_unit\"] = Property(default='€/MWh', data_type=str, name='unit of y label', unit='-',\n info='Unit of label for y axis', example='[€/MWh]')\n self.properties[\"y_labeling\"] = Property(default='Price', data_type=str, name='y label', unit='-',\n info='Label for y axis', example='Price [€/MWh]')\n\n # define persistent variables\n self.weight_ET = None\n self.weight_NT = None\n self.y_scaling = None\n self.y_unit = None\n self.y_labeling = None\n\n async def func_birth(self):\n pass\n\n async def func_amend(self, keys=[]):\n\n if 'weight_ET' in keys:\n weight_ET_i = self.get_property('weight_ET')\n self.weight_ET = json.loads(weight_ET_i)\n\n if 'weight_NT' in keys:\n weight_NT_i = self.get_property('weight_NT')\n self.weight_NT = json.loads(weight_NT_i)\n\n if 'scaling' in keys:\n self.y_scaling = self.get_property(\"scaling\")\n\n if 'y_unit' in keys:\n self.y_unit = self.get_property(\"y_unit\")\n\n if 'y_labeling' in keys:\n self.y_labeling = self.get_property(\"y_labeling\")\n\n async def func_peri(self, prep_to_peri=None):\n\n # locations information\n loc_tiers = self.weight_ET['location']\n\n # read prices\n stock_prices_input = await self.get_input('stock_ex_price')\n\n # read distribution costs\n dn_costs_input = await self.get_input('distnet_costs')\n loc_distnet = dn_costs_input['distribution_networks']\n len_loc_distnet = len(loc_distnet)\n\n # DLK\n DLK_val = await self.get_input('service_cost')\n\n # Abgaben\n abgaben_val = await self.get_input('taxes')\n\n # electricity rate\n el_rate = []\n border_tiers = []\n border_val = []\n ET_val = []\n NT_val = []\n MP_val = []\n for nt in range(0, len_loc_distnet):\n\n # compare location of distribution network with tiers locations, in it?\n if loc_distnet[nt] in loc_tiers:\n idx = loc_tiers.index(loc_distnet[nt])\n else: # if not in list, take default values\n idx = 0\n\n # distribution cost\n dist_costs = dn_costs_input['costs'][nt]\n\n # read and determine borders and tiers\n border_tiers_i = self.det_border_tiers(idx)\n\n # stock prices\n stock_prices = stock_prices_input['prices'][nt]\n\n el_rate_i = []\n for i_mt in range(0, len(stock_prices)):\n # stock price\n mt = stock_prices[i_mt]\n # electricity rate\n el_rate_ii = np.multiply(mt, border_tiers_i['ET_tiers']) + np.multiply(dist_costs, border_tiers_i['NT_tiers']) + DLK_val + abgaben_val\n el_rate_ii = el_rate_ii.tolist()\n el_rate_i.append(el_rate_ii)\n\n el_rate.append(el_rate_i)\n border_tiers.append(border_tiers_i)\n\n border_val_i = []\n ET_val_i = []\n NT_val_i = []\n border_i = border_tiers[nt]\n len_border_i = len(border_i[\"borders\"])\n\n for ni in range(0, len_border_i):\n if ni == 0:\n border_val_i.append(border_i[\"borders\"][ni])\n ET_val_i.append(border_i[\"ET_tiers\"][ni])\n NT_val_i.append(border_i[\"NT_tiers\"][ni])\n if ni == (len_border_i-1):\n border_val_i.append(border_i[\"borders\"][ni])\n ET_val_i.append(border_i[\"ET_tiers\"][ni-1])\n NT_val_i.append(border_i[\"NT_tiers\"][ni-1])\n if ((ni>0) & (ni<(len_border_i-1))):\n border_val_i.append(border_i[\"borders\"][ni])\n ET_val_i.append(border_i[\"ET_tiers\"][ni-1])\n NT_val_i.append(border_i[\"NT_tiers\"][ni-1])\n border_val_i.append(border_i[\"borders\"][ni])\n ET_val_i.append(border_i[\"ET_tiers\"][ni])\n NT_val_i.append(border_i[\"NT_tiers\"][ni])\n\n\n border_val.append(border_val_i)\n ET_val.append(ET_val_i)\n NT_val.append(NT_val_i)\n\n MP_val_data = []\n for mi in range(0, el_rate_i.__len__()):\n MP_val_i = [];\n for ni in range(0, len_border_i):\n erate_i = el_rate_i[mi]\n if ni == 0:\n MP_val_i.append(erate_i[ni])\n if ni == (len_border_i - 1):\n MP_val_i.append(erate_i[ni-1])\n if ((ni > 0) & (ni < (len_border_i - 1))):\n MP_val_i.append(erate_i[ni-1])\n MP_val_i.append(erate_i[ni])\n\n MP_val_data.append(MP_val_i)\n MP_val.append(MP_val_data)\n\n\n tier_val = [ET_val, NT_val]\n border_lines = {\"borders\": border_val,\n \"tiers\": [\"ET Tiers\", \"NT Tiers\"],\n \"tier_values\": tier_val,\n \"prices\": MP_val}\n\n output = {'Stao_ID': loc_distnet,\n 'values': el_rate,\n 'borders': border_tiers,\n 'border_lines': border_lines\n }\n\n # set output\n self.set_output(\"el_rate\", output)\n self.set_output(\"times\", await self.get_input('futures'))\n self.set_output(\"y_scaling\", self.y_scaling)\n self.set_output(\"y_unit\", self.y_unit)\n self.set_output(\"y_label\", self.y_labeling)\n\n def det_border_tiers(self, it):\n\n # read borders\n ET_border = self.weight_ET[\"border\"][it]\n NT_border = self.weight_NT[\"border\"][it]\n\n ET_border = np.array(ET_border)\n NT_border = np.array(NT_border)\n\n # merge\n borders = np.append(ET_border, NT_border)\n borders = np.unique(borders)\n\n # read tiers\n ET_tiers_orig = self.weight_ET[\"weight\"][it]\n NT_tiers_orig = self.weight_NT[\"weight\"][it]\n\n # create tiers corresponding to border\n ind_ET = 0\n ind_NT = 0\n ET_tiers = np.array(ET_tiers_orig[ind_ET])\n NT_tiers = np.array(NT_tiers_orig[ind_NT])\n for it in range(1, len(borders) - 1):\n\n # ET\n if ET_border[ind_ET+1] <= borders[it]:\n ind_ET = ind_ET + 1\n ET_tiers = np.append(ET_tiers, ET_tiers_orig[ind_ET])\n else:\n ET_tiers = np.append(ET_tiers, ET_tiers_orig[ind_ET])\n\n # NT\n if NT_border[ind_NT+1] <= borders[it]:\n ind_NT = ind_NT + 1\n NT_tiers = np.append(NT_tiers, NT_tiers_orig[ind_NT])\n else:\n NT_tiers = np.append(NT_tiers, NT_tiers_orig[ind_NT])\n\n #print(it)\n\n # return dict\n border_tiers = {'borders': borders.tolist(),\n 'ET_tiers': ET_tiers.tolist(),\n 'NT_tiers': NT_tiers.tolist()}\n\n return border_tiers\n\nif __name__ == \"__main__\":\n\n # input\n stock_ex_price = {'distribution_networks': ['Baden', 'Brugg'],\n 'prices': [[1, 2, 3], [1.1, 2.2, 3.3]]}\n distnet_costs = {'distribution_networks': stock_ex_price['distribution_networks'],\n 'costs': [100, 111]}\n DLK = [0.5]\n abgaben = [0.25]\n\n # properties\n ET = {\"location\": ['Baden', 'Brugg'],\n \"border\": [[-1., -0.8, -0.3, 0., 0.3, 0.8, 1.], [-1., -0.85, -0.35, 0., 0.35, 0.85, 1.]],\n \"weight\": [[-2., -1.25, -0.75, 0.75, 1.25, 2.], [-2., -1.3, -0.8, 0.8, 1.3, 2.]]}\n NT = {\"location\": ['Baden', 'Brugg'],\n \"border\": [[-1., -0.7, -0.4, 0., 0.4, 0.7, 1.], [-1., -0.75, -0.45, 0., 0.45, 0.75, 1.]],\n \"weight\": [[-1.75, -1., -0.5, 0.5, 1., 1.75], [-1.8, -1.05, -0.55, 0.55, 1.05, 1.8]]}\n ET = json.dumps(ET)\n NT = json.dumps(NT)\n\n inputs = {'stock_ex_price': stock_ex_price,\n 'distnet_costs': distnet_costs,\n 'service_cost': DLK,\n 'taxes': abgaben}\n props = {'weight_ET': ET,\n 'weight_NT': NT}\n\n outputs = Model.test(inputs, props)\n" ]
[ [ "numpy.array", "numpy.multiply", "numpy.unique", "numpy.append" ] ]
Leon-Francis/Script-role-emotion-recognition
[ "e80b8366f1e868b6611c149ad18945a994784b3d" ]
[ "train.py" ]
[ "import torch\nimport tqdm\nfrom torch.utils.data import DataLoader\nimport torch.nn.functional as F\nfrom torch import optim, nn\nfrom dataset import Script_dataset\nfrom config import TrainingConfig, CONFIG_PATH\nfrom model import BaseModel\nfrom tools import logging, get_time\nfrom datetime import datetime\nimport os\nfrom shutil import copyfile\nimport copy\nimport math\n\ndef save_config(path):\n copyfile(CONFIG_PATH, path + r'/config.txt')\n\ndef build_dataset():\n train_dataset_orig = Script_dataset(train_data=True, full_train_mode=False)\n test_dataset_orig = Script_dataset(train_data=False, full_train_mode=False)\n\n train_data = DataLoader(train_dataset_orig,\n batch_size=TrainingConfig.batch_size,\n shuffle=True,\n num_workers=4)\n test_data = DataLoader(test_dataset_orig,\n batch_size=TrainingConfig.batch_size,\n shuffle=False,\n num_workers=4)\n\n return train_data, test_data, train_dataset_orig.tokenizer\n\ndef train(train_data, model, criterion, optimizer):\n model.train()\n loss_mean = 0.0\n for train_features, train_labels in train_data:\n input_ids = train_features['input_ids'].to(TrainingConfig.train_device)\n token_type_ids = train_features['token_type_ids'].to(TrainingConfig.train_device)\n attention_mask = train_features['attention_mask'].to(TrainingConfig.train_device)\n\n outputs = model(input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask)\n\n loss_love = criterion(outputs['love'], train_labels['love'].view(-1, 1).to(TrainingConfig.train_device))\n loss_joy = criterion(outputs['joy'], train_labels['joy'].view(-1, 1).to(TrainingConfig.train_device))\n loss_fright = criterion(outputs['fright'], train_labels['fright'].view(-1, 1).to(TrainingConfig.train_device))\n loss_anger = criterion(outputs['anger'], train_labels['anger'].view(-1, 1).to(TrainingConfig.train_device))\n loss_fear = criterion(outputs['fear'], train_labels['fear'].view(-1, 1).to(TrainingConfig.train_device))\n loss_sorrow = criterion(outputs['sorrow'], train_labels['sorrow'].view(-1, 1).to(TrainingConfig.train_device))\n loss = loss_love + loss_joy + loss_fright + loss_anger + loss_fear + loss_sorrow\n\n loss_mean += loss.item()\n if loss.item() > TrainingConfig.skip_loss:\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n return loss_mean / len(train_data)\n\n\[email protected]_grad()\ndef evaluate(test_data, model, criterion):\n model.eval()\n loss_mean = 0.0\n score = 0.0\n total = 0\n for test_features, test_labels in test_data:\n input_ids = test_features['input_ids'].to(TrainingConfig.train_device)\n token_type_ids = test_features['token_type_ids'].to(TrainingConfig.train_device)\n attention_mask = test_features['attention_mask'].to(TrainingConfig.train_device)\n\n outputs = model(input_ids=input_ids,token_type_ids=token_type_ids,attention_mask=attention_mask)\n\n loss_love = criterion(outputs['love'], test_labels['love'].view(-1, 1).to(TrainingConfig.train_device))\n loss_joy = criterion(outputs['joy'], test_labels['joy'].view(-1, 1).to(TrainingConfig.train_device))\n loss_fright = criterion(outputs['fright'], test_labels['fright'].view(-1, 1).to(TrainingConfig.train_device))\n loss_anger = criterion(outputs['anger'], test_labels['anger'].view(-1, 1).to(TrainingConfig.train_device))\n loss_fear = criterion(outputs['fear'], test_labels['fear'].view(-1, 1).to(TrainingConfig.train_device))\n loss_sorrow = criterion(outputs['sorrow'], test_labels['sorrow'].view(-1, 1).to(TrainingConfig.train_device))\n loss = loss_love + loss_joy + loss_fright + loss_anger + loss_fear + loss_sorrow\n\n loss_mean += loss.item()\n\n for key, value in outputs.items():\n score += torch.sum((outputs[key].sigmoid().squeeze(1) * 3 - test_labels[key].to(TrainingConfig.train_device) * 3) ** 2).item()\n\n total += test_labels['love'].size()[0]\n\n return loss_mean / len(test_data), 1 / (1 + math.sqrt(score / total / 6))\n\n\nif __name__ == \"__main__\":\n logging('Using cuda device gpu: ' + str(TrainingConfig.cuda_idx))\n cur_dir = TrainingConfig.output_dir + '/train_model/' + datetime.now().strftime(\"%Y-%m-%d_%H:%M:%S\")\n cur_models_dir = cur_dir + '/models'\n if not os.path.isdir(cur_dir):\n os.makedirs(cur_dir)\n os.makedirs(cur_models_dir)\n\n logging('Saving into directory ' + cur_dir)\n save_config(cur_dir)\n\n logging('preparing data...')\n train_data, test_data, tokenizer = build_dataset()\n\n logging('init models, optimizer, criterion...')\n model = BaseModel(tokenizer).to(TrainingConfig.train_device)\n\n optimizer = optim.AdamW([{\n 'params': model.bert.parameters(),\n 'lr': TrainingConfig.Bert_lr\n }, {\n 'params': model.out_love.parameters()\n }, {\n 'params': model.out_joy.parameters()\n }, {\n 'params': model.out_fright.parameters()\n }, {\n 'params': model.out_anger.parameters()\n }, {\n 'params': model.out_fear.parameters()\n }, {\n 'params': model.out_sorrow.parameters()\n }],\n lr=TrainingConfig.lr,\n betas=TrainingConfig.betas,\n eps=TrainingConfig.eps,\n weight_decay=TrainingConfig.weight_decay)\n\n scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer,\n mode='min',\n factor=0.95,\n patience=3,\n verbose=True,\n min_lr=3e-9)\n warmup_scheduler = optim.lr_scheduler.LambdaLR(optimizer,\n lr_lambda=lambda ep: 1e-2\n if ep < 3 else 1.0)\n\n criterion = nn.BCEWithLogitsLoss().to(TrainingConfig.train_device)\n\n logging('Start training...')\n best_score = 0.0\n temp_path = cur_models_dir + f'/temp_model.pt'\n for ep in range(TrainingConfig.epoch):\n logging(f'epoch {ep} start train')\n train_loss = train(train_data, model, criterion, optimizer)\n logging(f'epoch {ep} start evaluate')\n evaluate_loss, score = evaluate(test_data, model, criterion)\n if score > best_score:\n best_score = score\n best_path = cur_models_dir + f'/best_score_{get_time()}_{score:.5f}.pt'\n best_state = copy.deepcopy(model.state_dict())\n\n if ep > 3 and best_score > TrainingConfig.save_score_limit and best_state != None:\n logging(f'saving best model score {best_score:.5f} in {temp_path}')\n torch.save(best_state, temp_path)\n\n if ep < 4:\n warmup_scheduler.step(ep)\n else:\n scheduler.step(evaluate_loss, epoch=ep)\n\n logging(\n f'epoch {ep} done! train_loss {train_loss:.5f} evaluate_loss {evaluate_loss:.5f} \\n'\n f'score {score:.5f} now best_score {best_score:.5f}')\n\n if best_score > TrainingConfig.save_score_limit and best_state != None:\n logging(f'saving best model score {best_score:.5f} in {best_path}')\n torch.save(best_state, best_path)" ]
[ [ "torch.utils.data.DataLoader", "torch.optim.lr_scheduler.LambdaLR", "torch.save", "torch.no_grad", "torch.nn.BCEWithLogitsLoss", "torch.optim.lr_scheduler.ReduceLROnPlateau" ] ]
granttremblay/aoide
[ "ea25bdf92013f7dc3b254e261039c43e697ee901" ]
[ "aoide/make_sky_mask.py" ]
[ "#!/usr/bin/env python\n'''\nAoide | Reduction & Analysis of MUSE observations\n-------------------------------------------------\nDr. Grant R. Tremblay | Harvard-Smithsonian Center for Astrophysics\ngrant.tremblay @ cfa.harvard.edu\n\nSee the README associated with this repository for documentation & examples.\n'''\n\n\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom astropy.io import fits as pyfits\n\n\"\"\"\nInteractive Masking of a FITS-file. The FITS-file must be provided upon\ncreating a new instance. If no mask is provided, the routine will create one\nfrom scratch. Otherwise, the supplied mask will be modified.\nThe masking porcess is carried out using the mouse: An area to mask is selected\nby moving the mouse over it while pressing the left button. To unmask an area,\nuse the right button. The cuts might be changed by clicking on the wheel.\nNote that plt.show() must be called after an instance of MaskFrame has been\ncreated!\n\n\"\"\"\n\n\nclass MaskFrame:\n \"\"\"\n Initiate an instance\n \"\"\"\n\n def __init__(self, image, mask_name, cuts=(0, 10), extension=0):\n fits_ima = pyfits.open(image)\n self.true_arr = fits_ima[extension].data\n if len(self.true_arr.shape) == 3:\n self.true_arr = self.true_arr[0, :]\n fits_ima.close()\n self.mask_name = mask_name\n self.extension = extension\n\n if os.path.exists(mask_name):\n self.in_mask = pyfits.open(mask_name, mode='update')\n self.mask = self.in_mask[0].data\n else:\n self.in_mask = None\n self.mask = np.zeros(self.true_arr.shape, dtype='Int16')\n\n self.plot_arr = self.true_arr + (self.mask * 1e9)\n\n self.lo_cut = cuts[0]\n self.hi_cut = cuts[1]\n\n self.fig = plt.figure(figsize=(8,8))\n self.ax = self.fig.add_subplot(111)\n self.ax.set_title('LEFT: Mask | RIGHT: Unmask | Wheel: Change cuts')\n self.im = self.ax.imshow(\n self.true_arr, origin='lower', interpolation='nearest', cmap='magma')\n\n self.update()\n\n self.xM = []\n self.yM = []\n\n self._connect()\n\n \"\"\"\n Connect the button_***_events to the corresponding methods\n \"\"\"\n\n def _connect(self):\n self.ax.figure.canvas.mpl_connect('button_press_event', self.__on)\n self.ax.figure.canvas.mpl_connect('button_release_event', self.__off)\n\n \"\"\"\n The actions that are carried out when a mouse button is pressed:\n \"\"\"\n\n def __on(self, event):\n if event.button == 2:\n print('Current cut levels are: {}, {}'.format(\n self.lo_cut, self.hi_cut))\n new_c = input('Enter new cut levels as low,high e.g. 0,20: ')\n self.lo_cut = float(new_c.split(',')[0])\n self.hi_cut = float(new_c.split(',')[1])\n self.update()\n else:\n if event.inaxes != self.ax.axes:\n print('Out of bounds!')\n return\n self.xM.append(int(round(event.xdata)))\n self.yM.append(int(round(event.ydata)))\n\n \"\"\"\n The actions that are carried out when a mouse button is released.\n \"\"\"\n\n def __off(self, event):\n if event.inaxes != self.ax.axes:\n print('Out of bounds!')\n return\n else:\n self.xM.append(int(round(event.xdata)))\n self.yM.append(int(round(event.ydata)))\n\n if len(self.xM) == 2:\n if event.button == 1:\n self.mask[min(self.yM):max(self.yM) + 1,\n min(self.xM):max(self.xM) + 1] = 1\n elif event.button == 3:\n self.mask[min(self.yM):max(self.yM) + 1,\n min(self.xM):max(self.xM) + 1] = 0\n\n self.plot_arr = self.true_arr + (self.mask * 1e9)\n self.update()\n\n self.xM = []\n self.yM = []\n\n \"\"\"\n This method updates the graphical interface:\n \"\"\"\n\n def update(self):\n self.im.set_data(self.plot_arr[:, :])\n self.im.set_clim(vmin=self.lo_cut, vmax=self.hi_cut)\n self.im.axes.figure.canvas.draw()\n\n \"\"\"\n Save the mask under the filename specified in FrameMask.__init__\n Note that unlike the other methods, this method must be called explicitely\n \"\"\"\n\n def save_mask(self):\n extension = self.extension\n if self.in_mask == None:\n maskHDU = pyfits.PrimaryHDU(self.mask)\n maskHDU.writeto(self.mask_name, overwrite=True)\n else:\n self.in_mask[0].data = self.mask\n self.in_mask.flush()\n\n\n\ndef main():\n if len(sys.argv) == 3:\n make_mask = MaskFrame(sys.argv[1], sys.argv[2])\n elif len(sys.argv) == 4:\n make_mask = MaskFrame(\n sys.argv[1], sys.argv[2], extension=int(sys.argv[3]))\n plt.show()\n make_mask.save_mask()\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "matplotlib.pyplot.figure", "matplotlib.pyplot.show", "numpy.zeros" ] ]
serge-m/jina
[ "9c9af3cd2982daabc75dd3d3e2f380e17c21aac0" ]
[ "tests/unit/executors/evaluators/rank/test_recall.py" ]
[ "import numpy as np\nimport pytest\n\nfrom jina.executors.evaluators.rank.recall import RecallEvaluator\n\n\[email protected](\n 'eval_at, expected',\n [\n (0, 0.0),\n (1, 0.2),\n (2, 0.4),\n (3, 0.4),\n (5, 0.4),\n (100, 0.4)\n ]\n)\ndef test_recall_evaluator(eval_at, expected):\n matches_ids = [0, 1, 2, 3, 4]\n\n desired_ids = [1, 0, 20, 30, 40]\n\n evaluator = RecallEvaluator(eval_at=eval_at)\n assert evaluator.evaluate(actual=matches_ids, desired=desired_ids) == expected\n assert evaluator._running_stats._n == 1\n np.testing.assert_almost_equal(evaluator.mean, expected)\n\n\[email protected](\n 'eval_at, expected_first',\n [\n (0, 0.0),\n (1, 0.2),\n (2, 0.4),\n (3, 0.4),\n (5, 0.4),\n (100, 0.4)\n ]\n)\ndef test_recall_evaluator_average(eval_at, expected_first):\n matches_ids = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]\n\n desired_ids = [[1, 0, 20, 30, 40], [-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1]]\n\n evaluator = RecallEvaluator(eval_at=eval_at)\n assert evaluator.evaluate(actual=matches_ids[0], desired=desired_ids[0]) == expected_first\n assert evaluator.evaluate(actual=matches_ids[1], desired=desired_ids[1]) == 0.0\n assert evaluator.evaluate(actual=matches_ids[2], desired=desired_ids[2]) == 0.0\n assert evaluator._running_stats._n == 3\n np.testing.assert_almost_equal(evaluator.mean, expected_first / 3)\n\n\ndef test_recall_evaluator_no_matches():\n matches_ids = []\n\n desired_ids = [1, 0, 20, 30, 40]\n\n evaluator = RecallEvaluator(eval_at=2)\n assert evaluator.evaluate(actual=matches_ids, desired=desired_ids) == 0.0\n assert evaluator._running_stats._n == 1\n np.testing.assert_almost_equal(evaluator.mean, 0.0)\n" ]
[ [ "numpy.testing.assert_almost_equal" ] ]
HaowenWeiJohn/RealityNavigationRealTimeInference
[ "cef6906d939f56c88ea38e4394f13f35f055e3d9" ]
[ "utils/data_utils.py" ]
[ "import os\nfrom pathlib import Path\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom scipy.signal import resample\n\nfrom utils.sig_proc_utils import notch_filter, baseline_correction\n\n\ndef window_slice(data, window_size, stride, channel_mode='channel_last'):\n assert len(data.shape) == 2\n if channel_mode == 'channel_first':\n data = np.transpose(data)\n elif channel_mode == 'channel_last':\n pass\n else:\n raise Exception('Unsupported channel mode')\n assert window_size <= len(data)\n assert stride > 0\n rtn = np.expand_dims(data, axis=0) if window_size == len(data) else []\n for i in range(window_size, len(data), stride):\n rtn.append(data[i - window_size:i])\n return np.array(rtn)\n\n\ndef modify_indice_to_cover(i1, i2, coverage, tolerance=3):\n assert i1 < i2\n assert abs(coverage - (i2 - i1)) <= tolerance\n is_modifying_i1 = True\n if i2 - i1 > coverage:\n while i2 - i1 != coverage:\n if is_modifying_i1:\n i1 += 1\n else:\n i2 -= 1\n print('Modified')\n\n elif i2 - i1 < coverage:\n while i2 - i1 != coverage:\n if is_modifying_i1:\n i1 -= 1\n else:\n i2 += 1\n print('Modified')\n\n return i1, i2\n\n\n\ndef interp_negative(y):\n idx = y < 0\n x = np.arange(len(y))\n y_interp = np.copy(y)\n y_interp[idx] = np.interp(x[idx], x[~idx], y[~idx])\n return y_interp\n\n\ndef clutter_removal(cur_frame, clutter, signal_clutter_ratio):\n if clutter is None:\n clutter = cur_frame\n else:\n clutter = signal_clutter_ratio * clutter + (1 - signal_clutter_ratio) * cur_frame\n return cur_frame - clutter, clutter\n\n\ndef integer_one_hot(a, num_classes):\n a = a.astype(int)\n return np.squeeze(np.eye(num_classes)[a.reshape(-1)]).astype(int)\n\n\ndef corrupt_frame_padding(time_series_data, min_threshold=np.NINF, max_threshold=np.PINF, frame_channel_first=True):\n if not frame_channel_first:\n time_series_data = np.moveaxis(time_series_data, -1, 0)\n\n if np.min(time_series_data[0]) < min_threshold or np.max(time_series_data[0]) > max_threshold:\n print('error: first frame is broken')\n return\n\n if np.min(time_series_data[-1]) < min_threshold or np.max(time_series_data[-1]) > max_threshold:\n print('error: last frame is broken')\n return\n\n broken_frame_counter = 0\n\n # check first and last frame\n for frame_index in range(1, len(time_series_data) - 1):\n data = np.squeeze(time_series_data[frame_index], axis=-1)\n if np.min(time_series_data[frame_index]) < min_threshold or np.max(\n time_series_data[frame_index]) > max_threshold:\n # find broken frame, padding with frame +1 and frame -1\n broken_frame_before = time_series_data[frame_index - 1]\n broken_frame = time_series_data[frame_index]\n broken_frame_next = time_series_data[frame_index + 1]\n if np.min(time_series_data[frame_index + 1]) >= min_threshold and np.max(\n time_series_data[frame_index + 1]) < max_threshold:\n time_series_data[frame_index] = (time_series_data[frame_index - 1] + time_series_data[\n frame_index + 1]) * 0.5\n broken_frame_counter += 1\n print('find broken frame at index:', frame_index, ' interpolate by the frame before and after.')\n else:\n time_series_data[frame_index] = time_series_data[frame_index - 1]\n print('find two continues broken frames at index: ', frame_index, ', equalize with previous frame.')\n\n if not frame_channel_first:\n time_series_data = np.moveaxis(time_series_data, 0, -1)\n\n print('pad broken frame: ', broken_frame_counter)\n return time_series_data\n\n\ndef time_series_static_clutter_removal(time_series_data, init_clutter=None, signal_clutter_ratio=0.1,\n frame_channel_first=True):\n if not frame_channel_first:\n time_series_data = np.moveaxis(time_series_data, -1, 0)\n\n clutter = None\n if init_clutter:\n clutter = init_clutter\n else: # using first two frames as the init_clutter\n clutter = (time_series_data[0] + time_series_data[1]) * 0.5\n\n for frame_index in range(0, len(time_series_data)):\n clutter_removal_frame, clutter = clutter_removal(\n cur_frame=time_series_data[frame_index],\n clutter=clutter,\n signal_clutter_ratio=signal_clutter_ratio)\n\n time_series_data[frame_index] = clutter_removal_frame\n\n if not frame_channel_first:\n time_series_data = np.moveaxis(time_series_data, 0, -1)\n\n return time_series_data\n\ndef is_broken_frame(frame, min_threshold=np.NINF, max_threshold=np.PINF):\n if np.min(frame) < min_threshold or np.max(frame) > max_threshold:\n return True\n else:\n return False\n\n\ndef levenshtein_ratio_and_distance(s, t, ratio_calc=False):\n \"\"\" levenshtein_ratio_and_distance:\n Calculates levenshtein distance between two strings.\n If ratio_calc = True, the function computes the\n levenshtein distance ratio of similarity between two strings\n For all i and j, distance[i,j] will contain the Levenshtein\n distance between the first i characters of s and the\n first j characters of t\n \"\"\"\n # Initialize matrix of zeros\n rows = len(s) + 1\n cols = len(t) + 1\n distance = np.zeros((rows, cols), dtype=int)\n\n # Populate matrix of zeros with the indeces of each character of both strings\n for i in range(1, rows):\n for k in range(1, cols):\n distance[i][0] = i\n distance[0][k] = k\n\n # Iterate over the matrix to compute the cost of deletions,insertions and/or substitutions\n for col in range(1, cols):\n for row in range(1, rows):\n if s[row - 1] == t[col - 1]:\n cost = 0 # If the characters are the same in the two strings in a given position [i,j] then the cost is 0\n else:\n # In order to align the results with those of the Python Levenshtein package, if we choose to calculate the ratio\n # the cost of a substitution is 2. If we calculate just distance, then the cost of a substitution is 1.\n if ratio_calc == True:\n cost = 2\n else:\n cost = 1\n distance[row][col] = min(distance[row - 1][col] + 1, # Cost of deletions\n distance[row][col - 1] + 1, # Cost of insertions\n distance[row - 1][col - 1] + cost) # Cost of substitutions\n if ratio_calc == True:\n # Computation of the Levenshtein Distance Ratio\n Ratio = ((len(s) + len(t)) - distance[row][col]) / (len(s) + len(t))\n return Ratio\n else:\n # print(distance) # Uncomment if you want to see the matrix showing how the algorithm computes the cost of deletions,\n # insertions and/or substitutions\n # This is the minimum number of edits needed to convert string a to string b\n return \"The strings are {} edits away\".format(distance[row][col])\n\ndef replace_special(target_str: str, replacement_dict):\n for special, replacement in replacement_dict.items():\n # print('replacing ' + special)\n target_str = target_str.replace(special, replacement)\n return target_str" ]
[ [ "numpy.eye", "numpy.transpose", "numpy.interp", "numpy.zeros", "numpy.squeeze", "numpy.moveaxis", "numpy.copy", "numpy.expand_dims", "numpy.max", "numpy.min", "numpy.array" ] ]
stefanv/dipy
[ "4d4518861a796502826f053c17161487db126487" ]
[ "doc/examples/tractography_clustering.py" ]
[ "\"\"\" \n\n=============================\nTractography Clustering\n=============================\n\nOverview\n========\n\n**This example gives a tour of clustering related features of dipy.**\n\nFirst import the necessary modules\n----------------------------------\n\n``numpy`` is for numerical computation\n\n\"\"\"\n\nimport numpy as np\n\nimport time\n\nfrom nibabel import trackvis as tv\n\nfrom dipy.tracking import metrics as tm\nfrom dipy.tracking import distances as td\nfrom dipy.io import pickles as pkl\nfrom dipy.viz import fvtk\n\n\n#fname='/home/user/Data_Backup/Data/PBC/pbc2009icdm/brain1/brain1_scan1_fiber_track_mni.trk'\n#fname='/home/user/Data/PBC/pbc2009icdm/brain1/brain1_scan1_fiber_track_mni.trk'\nfrom dipy.data import get_data\n\nfname=get_data('fornix')\nprint(fname)\n\n\"\"\"\nLoad Trackvis file for *Fornix*:\n\"\"\"\n\nstreams,hdr=tv.read(fname)\n\n\"\"\"\nCopy tracks:\n\"\"\"\n\nT=[i[0] for i in streams]\n\n#T=T[:1000]\n\n\"\"\"\nDownsample tracks to just 3 points:\n\"\"\"\n\ntracks=[tm.downsample(t,3) for t in T]\n\n\"\"\"\nDelete unnecessary data:\n\"\"\"\n\ndel streams,hdr\n\n\"\"\"\nPerform Local Skeleton Clustering (LSC) with a 5mm threshold:\n\"\"\"\n\nnow=time.clock()\nC=td.local_skeleton_clustering(tracks,d_thr=5)\nprint('Done in %.2f s' % (time.clock()-now,))\n\n\n\"\"\"\nReduce the number of points for faster visualization using the ``approx_polygon_track`` algorithm which retains points depending on how much they are need to define the shape of the track:\n\"\"\"\n\nT=[td.approx_polygon_track(t) for t in T]\n\n\"\"\"\nShow the initial *Fornix* dataset:\n\"\"\"\n\nr=fvtk.ren()\nfvtk.add(r,fvtk.line(T,fvtk.white,opacity=1))\n#fvtk.show(r)\nfvtk.record(r,n_frames=1,out_path='fornix_initial',size=(600,600))\n\n\"\"\"\n.. figure:: fornix_initial1000000.png\n :align: center\n\n **Initial Fornix dataset**.\n\"\"\"\n\n\"\"\"\nShow the *Fornix* after clustering (with random bundle colors):\n\"\"\"\n\nfvtk.clear(r)\ncolors=np.zeros((len(T),3))\nfor c in C:\n color=np.random.rand(1,3)\n for i in C[c]['indices']:\n colors[i]=color\nfvtk.add(r,fvtk.line(T,colors,opacity=1))\n#fvtk.show(r)\nfvtk.record(r,n_frames=1,out_path='fornix_clust',size=(600,600))\n\n\"\"\"\n.. figure:: fornix_clust1000000.png\n :align: center\n\n **Showing the different clusters with random colors**.\n\n\"\"\"\n\n\"\"\"\nCalculate some statistics about the clusters\n\"\"\"\n\nlens=[len(C[c]['indices']) for c in C]\nprint('max %d min %d' %(max(lens), min(lens)))\nprint('singletons %d ' % lens.count(1))\nprint('doubletons %d' % lens.count(2))\nprint('tripletons %d' % lens.count(3))\n\n\"\"\"\nFind and display the skeleton of most representative tracks in each cluster:\n\"\"\"\n\nskeleton=[]\n\nfvtk.clear(r)\n\nfor c in C:\n \n bundle=[T[i] for i in C[c]['indices']]\n si,s=td.most_similar_track_mam(bundle,'avg') \n skeleton.append(bundle[si])\n fvtk.label(r,text=str(len(bundle)),pos=(bundle[si][-1]),scale=(2,2,2))\n\nfvtk.add(r,fvtk.line(skeleton,colors,opacity=1))\n#fvtk.show(r)\nfvtk.record(r,n_frames=1,out_path='fornix_most',size=(600,600))\n\n\"\"\"\n.. figure:: fornix_most1000000.png\n :align: center\n\n **Showing skeleton with the most representative tracks as the skeletal representation**.\n \n The numbers are depicting the number of tracks in each cluster. This is a very compact way to see the underlying\n structures an alternative would be to draw the representative tracks with different widths.\n \n\"\"\"\n\n\"\"\"\nSave the skeleton information in the dictionary. Now try to play with different thresholds LSC and check the different results.\nTry it with your datasets and gives us some feedback.\n\n\"\"\"\n\nfor (i,c) in enumerate(C): \n C[c]['most']=skeleton[i]\n \nfor c in C: \n print('Keys in bundle %d' % c)\n print(C[c].keys())\n print('Shape of skeletal track (%d, %d) ' % C[c]['most'].shape)\n\npkl.save_pickle('skeleton_fornix.pkl',C)\n\n\n\n\n" ]
[ [ "numpy.random.rand" ] ]
dougalsutherland/cvxpy
[ "34349b5e41c124a6a1e32426e68af95b5044498c" ]
[ "cvxpy/reductions/solvers/qp_solvers/qp_solver.py" ]
[ "\"\"\"\nCopyright 2017 Robin Verschueren\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport numpy as np\nimport scipy.sparse as sp\n\nfrom cvxpy.atoms.affine.add_expr import AddExpression\nfrom cvxpy.atoms.affine.binary_operators import MulExpression\nfrom cvxpy.atoms.quad_form import QuadForm\nfrom cvxpy.constraints import NonPos, Zero\nfrom cvxpy.problems.objective import Minimize\nfrom cvxpy.reductions import InverseData\nfrom cvxpy.reductions.solvers.conic_solvers.conic_solver import ConicSolver\nfrom cvxpy.reductions.solvers.solver import Solver\nfrom cvxpy.reductions.utilities import are_args_affine\nimport cvxpy.settings as s\n\n\ndef is_stuffed_qp_objective(objective):\n \"\"\"QPSolver requires objectives to be stuffed in the following way.\n \"\"\"\n expr = objective.expr\n return (type(expr) == AddExpression\n and len(expr.args) == 2\n and type(expr.args[0]) == QuadForm\n and type(expr.args[1]) == MulExpression\n and expr.args[1].is_affine())\n\n\nclass QpSolver(Solver):\n \"\"\"\n A QP solver interface.\n \"\"\"\n\n def accepts(self, problem):\n return (type(problem.objective) == Minimize\n and is_stuffed_qp_objective(problem.objective)\n and all(type(c) == Zero or type(c) == NonPos\n for c in problem.constraints)\n and are_args_affine(problem.constraints))\n\n def apply(self, problem):\n \"\"\"\n Construct QP problem data stored in a dictionary.\n The QP has the following form\n\n minimize 1/2 x' P x + q' x\n subject to A x = b\n F x <= g\n\n \"\"\"\n inverse_data = InverseData(problem)\n\n obj = problem.objective\n # quadratic part of objective is x.T * P * x but solvers expect\n # 0.5*x.T * P * x.\n P = 2*obj.expr.args[0].args[1].value\n q = obj.expr.args[1].args[0].value.flatten()\n\n # Get number of variables\n n = problem.size_metrics.num_scalar_variables\n\n # TODO(akshayka): This dependence on ConicSolver is hacky; something\n # should change here.\n eq_cons = [c for c in problem.constraints if type(c) == Zero]\n if eq_cons:\n eq_coeffs = list(zip(*[ConicSolver.get_coeff_offset(con.expr)\n for con in eq_cons]))\n A = sp.vstack(eq_coeffs[0])\n b = - np.concatenate(eq_coeffs[1])\n else:\n A, b = sp.csr_matrix((0, n)), -np.array([])\n\n ineq_cons = [c for c in problem.constraints if type(c) == NonPos]\n if ineq_cons:\n ineq_coeffs = list(zip(*[ConicSolver.get_coeff_offset(con.expr)\n for con in ineq_cons]))\n F = sp.vstack(ineq_coeffs[0])\n g = - np.concatenate(ineq_coeffs[1])\n else:\n F, g = sp.csr_matrix((0, n)), -np.array([])\n\n # Create dictionary with problem data\n variables = problem.variables()[0]\n data = {}\n data[s.P] = sp.csc_matrix(P)\n data[s.Q] = q\n data[s.A] = sp.csc_matrix(A)\n data[s.B] = b\n data[s.F] = sp.csc_matrix(F)\n data[s.G] = g\n data[s.BOOL_IDX] = [t[0] for t in variables.boolean_idx]\n data[s.INT_IDX] = [t[0] for t in variables.integer_idx]\n data['n_var'] = n\n data['n_eq'] = A.shape[0]\n data['n_ineq'] = F.shape[0]\n\n inverse_data.sorted_constraints = ineq_cons + eq_cons\n\n # Add information about integer variables\n inverse_data.is_mip = \\\n len(data[s.BOOL_IDX]) > 0 or len(data[s.INT_IDX]) > 0\n\n return data, inverse_data\n" ]
[ [ "scipy.sparse.csc_matrix", "scipy.sparse.csr_matrix", "numpy.array", "numpy.concatenate", "scipy.sparse.vstack" ] ]
jpjuvo/RSNA-MICCAI-Brain-Tumor-Classification
[ "a8a4e9257b7475bc328870504edd18fdd9ec9d2f" ]
[ "src/seg_model_utils/torchio_transforms.py" ]
[ "import torch\nimport torchio as tio\nimport numpy as np\n\ndef load_tio_image(fn):\n \"\"\"\n ScalarImage(shape: (c, w, h, d))\n dtype: torch.DoubleTensor\n \"\"\"\n arr = np.load(fn).swapaxes(0,3)\n return tio.ScalarImage(tensor=arr)\n\ndef arr_2_tio_image(arr):\n \"\"\"\n ScalarImage(shape: (c, w, h, d))\n dtype: torch.DoubleTensor\n \"\"\"\n arr = arr.swapaxes(0,3)\n return tio.ScalarImage(tensor=arr)\n\ndef load_tio_seg_image(fn):\n \"\"\"\n LabelMap(shape: (c, w, h, d))\n dtype: torch.FloatTensor\n \n Intensity transforms are not applied to these images.\n Nearest neighbor interpolation is always used to resample label maps.\n \"\"\"\n if fn is None:\n return None\n if not os.path.exists(fn):\n return None\n arr = (np.expand_dims(np.load(fn),3).swapaxes(0,3) > 0).astype(np.float32)\n return tio.LabelMap(tensor=arr)\n\ndef arr_2_tio_seg_image(arr):\n \"\"\"\n LabelMap(shape: (c, w, h, d))\n dtype: torch.FloatTensor\n \n Intensity transforms are not applied to these images.\n Nearest neighbor interpolation is always used to resample label maps.\n \"\"\"\n if arr is None:\n return None\n arr = (np.expand_dims(arr,3).swapaxes(0,3) > 0).astype(np.float32)\n return tio.LabelMap(tensor=arr)\n\ndef load_tio_subject(image_fn:str, label:int, seg_fn=None):\n return tio.Subject(\n rgb_image=load_tio_image(image_fn),\n segmentation=load_tio_seg_image(seg_fn),\n label=int(label),\n name=os.path.basename(image_fn).split('.')[0])" ]
[ [ "numpy.load", "numpy.expand_dims" ] ]
levitsky/biosaur2
[ "5cc8474906408c58ff043af722607c1452aa444f" ]
[ "biosaur2/utils.py" ]
[ "from pyteomics import mzml\nimport numpy as np\nfrom collections import defaultdict, Counter\nfrom os import path\nimport math\nfrom scipy.optimize import curve_fit\nimport logging\nlogger = logging.getLogger(__name__)\nfrom .cutils import get_fast_dict, get_and_calc_apex_intensity_and_scan\n\nclass MS1OnlyMzML(mzml.MzML): \n _default_iter_path = '//spectrum[./*[local-name()=\"cvParam\" and @name=\"ms level\" and @value=\"1\"]]' \n _use_index = False \n _iterative = False\n\ndef noisygaus(x, a, x0, sigma, b):\n return a * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2)) + b\n\ndef calibrate_mass(bwidth, mass_left, mass_right, true_md):\n\n bbins = np.arange(-mass_left, mass_right, bwidth)\n H1, b1 = np.histogram(true_md, bins=bbins)\n b1 = b1 + bwidth\n b1 = b1[:-1]\n\n popt, pcov = curve_fit(noisygaus, b1, H1, p0=[1, np.median(true_md), 1, 1])\n mass_shift, mass_sigma = popt[1], abs(popt[2])\n return mass_shift, mass_sigma, pcov[0][0]\n\n\ndef calc_peptide_features(hills_dict, peptide_features, negative_mode, faims_val, RT_dict, data_start_id):\n\n for pep_feature in peptide_features:\n\n pep_feature['mz'] = pep_feature['hill_mz_1']\n pep_feature['isoerror'] = pep_feature['isotopes'][0]['mass_diff_ppm']\n pep_feature['isoerror2'] = pep_feature['isotopes'][1]['mass_diff_ppm'] if len(pep_feature['isotopes']) > 1 else -100\n pep_feature['nScans'] = hills_dict['hills_lengths'][pep_feature['monoisotope idx']]\n\n pep_feature['massCalib'] = pep_feature['mz'] * pep_feature['charge'] - 1.0072765 * pep_feature['charge'] * (-1 if negative_mode else 1)\n\n hills_dict, _, _ = get_and_calc_apex_intensity_and_scan(hills_dict, pep_feature['monoisotope idx'])\n\n pep_feature['scanApex'] = hills_dict['hills_scan_apex'][pep_feature['monoisotope idx']]\n pep_feature['rtApex'] = RT_dict[hills_dict['hills_scan_apex'][pep_feature['monoisotope idx']]+data_start_id]\n pep_feature['intensityApex'] = hills_dict['hills_intensity_apex'][pep_feature['monoisotope idx']]\n pep_feature['rtStart'] = RT_dict[hills_dict['hills_scan_lists'][pep_feature['monoisotope idx']][0]+data_start_id]\n pep_feature['rtEnd'] = RT_dict[hills_dict['hills_scan_lists'][pep_feature['monoisotope idx']][-1]+data_start_id]\n pep_feature['mono_hills_scan_lists'] = hills_dict['hills_scan_lists'][pep_feature['monoisotope idx']]\n pep_feature['mono_hills_intensity_list'] = hills_dict['hills_intensity_array'][pep_feature['monoisotope idx']]\n\n return peptide_features\n\n\ndef write_output(peptide_features, args, write_header=True):\n\n input_mzml_path = args['file']\n\n if args['o']:\n output_file = args['o']\n else:\n output_file = path.splitext(input_mzml_path)[0]\\\n + path.extsep + 'features.tsv'\n\n columns_for_output = [\n 'massCalib',\n 'rtApex',\n 'intensityApex',\n 'charge',\n 'nIsotopes',\n 'nScans',\n 'mz',\n 'rtStart',\n 'rtEnd',\n 'FAIMS',\n 'im',\n 'mono_hills_scan_lists',\n 'mono_hills_intensity_list',\n 'scanApex',\n 'isoerror2',\n ]\n\n if write_header:\n\n out_file = open(output_file, 'w')\n out_file.write('\\t'.join(columns_for_output) + '\\n')\n out_file.close()\n\n out_file = open(output_file, 'a')\n for pep_feature in peptide_features:\n out_file.write('\\t'.join([str(pep_feature[col]) for col in columns_for_output]) + '\\n')\n\n out_file.close()\n\n\ndef centroid_pasef_data(data_for_analyse_tmp, args, mz_step):\n\n cnt_ms1_scans = len(data_for_analyse_tmp)\n for spec_idx, z in enumerate(data_for_analyse_tmp):\n\n logger.info('PASEF scans analysis: %d/%d', spec_idx+1, cnt_ms1_scans)\n logger.info('number of m/z peaks in scan: %d', len(z['m/z array']))\n\n if 'ignore_ion_mobility' not in z:\n\n mz_ar_new = []\n intensity_ar_new = []\n ion_mobility_ar_new = []\n\n mz_ar = z['m/z array']\n intensity_ar = z['intensity array']\n ion_mobility_ar = z['mean inverse reduced ion mobility array']\n\n ion_mobility_accuracy = args['paseftol']\n ion_mobility_step = max(ion_mobility_ar) * ion_mobility_accuracy\n\n ion_mobility_ar_fast = (ion_mobility_ar/ion_mobility_step).astype(int)\n mz_ar_fast = (mz_ar/mz_step).astype(int)\n\n idx = np.argsort(mz_ar_fast)\n mz_ar_fast = mz_ar_fast[idx]\n ion_mobility_ar_fast = ion_mobility_ar_fast[idx]\n\n mz_ar = mz_ar[idx]\n intensity_ar = intensity_ar[idx]\n ion_mobility_ar = ion_mobility_ar[idx]\n\n max_peak_idx = len(mz_ar)\n\n banned_idx = set()\n\n peak_idx = 0\n while peak_idx < max_peak_idx:\n\n if peak_idx not in banned_idx:\n\n mass_accuracy_cur = mz_ar[peak_idx] * 1e-6 * args['itol']\n\n mz_val_int = mz_ar_fast[peak_idx]\n ion_mob_val_int = ion_mobility_ar_fast[peak_idx]\n\n tmp = [peak_idx, ]\n\n peak_idx_2 = peak_idx + 1\n\n while peak_idx_2 < max_peak_idx:\n\n\n if peak_idx_2 not in banned_idx:\n\n mz_val_int_2 = mz_ar_fast[peak_idx_2]\n if mz_val_int_2 - mz_val_int > 1:\n break\n elif abs(mz_ar[peak_idx]-mz_ar[peak_idx_2]) <= mass_accuracy_cur:\n ion_mob_val_int_2 = ion_mobility_ar_fast[peak_idx_2]\n if abs(ion_mob_val_int - ion_mob_val_int_2) <= 1:\n tmp.append(peak_idx_2)\n peak_idx = peak_idx_2\n peak_idx_2 += 1\n\n all_intensity = [intensity_ar[p_id] for p_id in tmp]\n i_val_new = sum(all_intensity)\n\n if i_val_new >= args['pasefmini'] and len(all_intensity) >= args['pasefminlh']:\n\n all_mz = [mz_ar[p_id] for p_id in tmp]\n all_ion_mob = [ion_mobility_ar[p_id] for p_id in tmp]\n\n mz_val_new = np.average(all_mz, weights=all_intensity)\n ion_mob_new = np.average(all_ion_mob, weights=all_intensity)\n\n intensity_ar_new.append(i_val_new)\n mz_ar_new.append(mz_val_new)\n ion_mobility_ar_new.append(ion_mob_new)\n\n banned_idx.update(tmp)\n\n peak_idx += 1\n\n data_for_analyse_tmp[spec_idx]['m/z array'] = np.array(mz_ar_new)\n data_for_analyse_tmp[spec_idx]['intensity array'] = np.array(intensity_ar_new)\n data_for_analyse_tmp[spec_idx]['mean inverse reduced ion mobility array'] = np.array(ion_mobility_ar_new)\n\n logger.info('number of m/z peaks in scan after centroiding: %d', len(data_for_analyse_tmp[spec_idx]['m/z array']))\n\n data_for_analyse_tmp = [z for z in data_for_analyse_tmp if len(z['m/z array'] > 0)]\n logger.info('Number of MS1 scans after combining ion mobility peaks: %d', len(data_for_analyse_tmp))\n\n # fast_dict = defaultdict(set)\n # for peak_idx, (mz_val_int, ion_mob_val_int) in enumerate(zip(mz_ar_fast, ion_mobility_ar_fast)):\n\n # fast_dict[(mz_val_int-1, ion_mob_val_int)].add(peak_idx)\n # fast_dict[(mz_val_int, ion_mob_val_int)].add(peak_idx)\n # fast_dict[(mz_val_int+1, ion_mob_val_int)].add(peak_idx)\n\n # fast_dict[(mz_val_int-1, ion_mob_val_int-1)].add(peak_idx)\n # fast_dict[(mz_val_int, ion_mob_val_int-1)].add(peak_idx)\n # fast_dict[(mz_val_int+1, ion_mob_val_int-1)].add(peak_idx)\n\n # fast_dict[(mz_val_int-1, ion_mob_val_int+1)].add(peak_idx)\n # fast_dict[(mz_val_int, ion_mob_val_int+1)].add(peak_idx)\n # fast_dict[(mz_val_int+1, ion_mob_val_int+1)].add(peak_idx)\n\n\n # print('HERE2')\n\n # hill_length = []\n # peak_idx_array = []\n # for peak_idx, (mz_val_int, ion_mob_val_int) in enumerate(zip(mz_ar_fast, ion_mobility_ar_fast)):\n # hill_length.append(len(fast_dict[(mz_val_int, ion_mob_val_int)]))\n # peak_idx_array.append(peak_idx)\n # peak_idx_array = np.array(peak_idx_array)\n\n\n # print('HERE3')\n\n # added_idx = set()\n # idx_sort = np.argsort(hill_length)[::-1]\n # for peak_idx in peak_idx_array[idx_sort]:\n # if peak_idx not in added_idx:\n # mz_val_int = mz_ar_fast[peak_idx]\n # ion_mob_val_int = ion_mobility_ar_fast[peak_idx]\n # all_idx = set([p_id for p_id in fast_dict[(mz_val_int, ion_mob_val_int)] if p_id not in added_idx])\n # if len(all_idx):\n # added_idx.update(all_idx)\n\n # all_intensity = [intensity_ar[p_id] for p_id in all_idx]\n # i_val_new = sum(all_intensity)\n\n # if i_val_new >= args['pasefmini']:\n\n # all_mz = [mz_ar[p_id] for p_id in all_idx]\n # all_ion_mob = [ion_mobility_ar[p_id] for p_id in all_idx]\n\n # mz_val_new = np.average(all_mz, weights=all_intensity)\n # ion_mob_new = np.average(all_ion_mob, weights=all_intensity)\n\n # intensity_ar_new.append(i_val_new)\n # mz_ar_new.append(mz_val_new)\n # ion_mobility_ar_new.append(ion_mob_new)\n\n # data_for_analyse_tmp[spec_idx]['m/z array'] = np.array(mz_ar_new)\n # data_for_analyse_tmp[spec_idx]['intensity array'] = np.array(intensity_ar_new)\n # data_for_analyse_tmp[spec_idx]['mean inverse reduced ion mobility array'] = np.array(ion_mobility_ar_new)\n\n # data_for_analyse_tmp = [z for z in data_for_analyse_tmp if len(z['m/z array'] > 0)]\n # print('Number of MS1 scans after combining ion mobility peaks: ', len(data_for_analyse_tmp))\n\n return data_for_analyse_tmp\n\ndef process_profile(data_for_analyse_tmp):\n\n data_for_analyse_tmp_out = []\n\n for z in data_for_analyse_tmp:\n\n best_mz = 0\n best_int = 0\n best_im = 0\n prev_mz = False\n prev_int = False\n\n threshold = 0.05\n\n ar1 = []\n ar2 = []\n ar3 = []\n for mzv, intv, imv in zip(z['m/z array'], z['intensity array'], z['mean inverse reduced ion mobility array']):\n if prev_mz is False:\n best_mz = mzv\n best_int = intv\n best_im = imv\n elif mzv - prev_mz > threshold:\n ar1.append(best_mz)\n ar2.append(best_int)\n ar3.append(best_im)\n best_mz = mzv\n best_int = intv\n best_im = imv\n elif best_int > prev_int and intv > prev_int:\n ar1.append(best_mz)\n ar2.append(best_int)\n ar3.append(best_im)\n best_mz = mzv\n best_int = intv\n best_im = imv\n elif intv > best_int:\n best_mz = mzv\n best_int = intv\n best_im = imv\n prev_mz = mzv\n prev_int = intv\n\n ar1.append(best_mz)\n ar2.append(best_int)\n ar3.append(best_im)\n\n z['m/z array'] = np.array(ar1)\n z['intensity array'] = np.array(ar2)\n z['mean inverse reduced ion mobility array'] = np.array(ar3)\n\n data_for_analyse_tmp_out.append(z)\n return data_for_analyse_tmp_out\n\n\n\ndef process_tof(data_for_analyse_tmp):\n\n # print(len(z['m/z array']))\n universal_dict = {}\n cnt = 0\n\n for z in data_for_analyse_tmp:\n\n fast_set = z['m/z array'] // 50\n if cnt == 1:\n\n\n for l in set(fast_set):\n idxt = fast_set == l\n true_i = np.log10(z['intensity array'])[idxt]\n\n if len(true_i) > 150:\n\n i_left = true_i.min()\n i_right = true_i.max()\n\n i_shift, i_sigma, covvalue = calibrate_mass(0.05, i_left, i_right, true_i)\n # median_val = \n print(i_shift, i_sigma, covvalue)\n universal_dict[l] = 10**(i_shift + 3 * i_sigma)#10**(np.median(true_i[idxt]) * 2)\n \n\n \n thresholds = [universal_dict.get(zz, 150) for zz in list(fast_set)]\n idxt2 = z['intensity array'] <= thresholds\n z['intensity array'][idxt2] = -1\n\n\n idx = z['intensity array'] > 0\n z['intensity array'] = z['intensity array'][idx]\n z['m/z array'] = z['m/z array'][idx]\n z['mean inverse reduced ion mobility array'] = z['mean inverse reduced ion mobility array'][idx]\n\n\n\n cnt += 1\n\n data_for_analyse_tmp = [z for z in data_for_analyse_tmp if len(z['m/z array'])]\n\n return data_for_analyse_tmp\n\n\ndef process_mzml(args):\n\n input_mzml_path = args['file']\n min_intensity = args['mini']\n min_mz = args['minmz']\n max_mz = args['maxmz']\n\n skipped = 0\n data_for_analyse = []\n\n cnt = 0\n\n for z in MS1OnlyMzML(source=input_mzml_path):\n if z['ms level'] == 1:\n\n if 'mean inverse reduced ion mobility array' not in z:\n z['ignore_ion_mobility'] = True\n z['mean inverse reduced ion mobility array'] = np.zeros(len(z['m/z array']))\n\n idx = z['intensity array'] >= min_intensity\n z['intensity array'] = z['intensity array'][idx]\n z['m/z array'] = z['m/z array'][idx]\n z['mean inverse reduced ion mobility array'] = z['mean inverse reduced ion mobility array'][idx]\n\n idx = z['m/z array'] >= min_mz\n z['m/z array'] = z['m/z array'][idx]\n z['intensity array'] = z['intensity array'][idx]\n z['mean inverse reduced ion mobility array'] = z['mean inverse reduced ion mobility array'][idx]\n\n idx = z['m/z array'] <= max_mz\n z['m/z array'] = z['m/z array'][idx]\n z['intensity array'] = z['intensity array'][idx]\n z['mean inverse reduced ion mobility array'] = z['mean inverse reduced ion mobility array'][idx]\n\n idx = np.argsort(z['m/z array'])\n z['m/z array'] = z['m/z array'][idx]\n z['intensity array'] = z['intensity array'][idx]\n z['mean inverse reduced ion mobility array'] = z['mean inverse reduced ion mobility array'][idx]\n\n cnt += 1\n\n # if len(data_for_analyse) > 50:\n # break\n\n if len(z['m/z array']):\n data_for_analyse.append(z)\n else:\n skipped += 1\n\n\n logger.info('Number of MS1 scans: %d', len(data_for_analyse))\n logger.info('Number of skipped MS1 scans: %d', skipped)\n\n if len(data_for_analyse) == 0:\n raise Exception('no MS1 scans in input file')\n\n return data_for_analyse\n\n\n\ndef process_mzml_dia(args):\n\n input_mzml_path = args['file']\n # min_intensity = args['mini']\n # min_mz = args['minmz']\n # max_mz = args['maxmz']\n min_intensity = 0\n min_mz = 1\n max_mz = 1e6\n\n skipped = 0\n data_for_analyse = []\n\n cnt = 0\n\n for z in mzml.read(input_mzml_path):\n if z['ms level'] == 2:\n\n if 'mean inverse reduced ion mobility array' not in z:\n z['ignore_ion_mobility'] = True\n z['mean inverse reduced ion mobility array'] = np.zeros(len(z['m/z array']))\n\n idx = z['intensity array'] >= min_intensity\n z['intensity array'] = z['intensity array'][idx]\n z['m/z array'] = z['m/z array'][idx]\n z['mean inverse reduced ion mobility array'] = z['mean inverse reduced ion mobility array'][idx]\n\n idx = z['m/z array'] >= min_mz\n z['m/z array'] = z['m/z array'][idx]\n z['intensity array'] = z['intensity array'][idx]\n z['mean inverse reduced ion mobility array'] = z['mean inverse reduced ion mobility array'][idx]\n\n idx = z['m/z array'] <= max_mz\n z['m/z array'] = z['m/z array'][idx]\n z['intensity array'] = z['intensity array'][idx]\n z['mean inverse reduced ion mobility array'] = z['mean inverse reduced ion mobility array'][idx]\n\n idx = np.argsort(z['m/z array'])\n z['m/z array'] = z['m/z array'][idx]\n z['intensity array'] = z['intensity array'][idx]\n z['mean inverse reduced ion mobility array'] = z['mean inverse reduced ion mobility array'][idx]\n\n cnt += 1\n\n # if len(data_for_analyse) > 5000:\n # break\n\n if len(z['m/z array']):\n data_for_analyse.append(z)\n else:\n skipped += 1\n\n\n logger.info('Number of MS2 scans: %d', len(data_for_analyse))\n logger.info('Number of skipped MS2 scans: %d', skipped)\n\n return data_for_analyse\n" ]
[ [ "numpy.histogram", "numpy.argsort", "numpy.median", "numpy.exp", "numpy.arange", "numpy.log10", "numpy.array", "numpy.average" ] ]
kaczmarj/robustness
[ "79d371fd799885ea5fe5553c2b749f41de1a2c4e" ]
[ "robustness/attack_steps.py" ]
[ "\"\"\"\n**For most use cases, this can just be considered an internal class and\nignored.**\n\nThis module contains the abstract class AttackerStep as well as a few subclasses. \n\nAttackerStep is a generic way to implement optimizers specifically for use with\n:class:`robustness.attacker.AttackerModel`. In general, except for when you want\nto :ref:`create a custom optimization method <adding-custom-steps>`, you probably do not need to\nimport or edit this module and can just think of it as internal.\n\"\"\"\n\nimport torch as ch\n\nclass AttackerStep:\n '''\n Generic class for attacker steps, under perturbation constraints\n specified by an \"origin input\" and a perturbation magnitude.\n Must implement project, step, and random_perturb\n '''\n def __init__(self, orig_input, eps, step_size, use_grad=True):\n '''\n Initialize the attacker step with a given perturbation magnitude.\n\n Args:\n eps (float): the perturbation magnitude\n orig_input (ch.tensor): the original input\n '''\n self.orig_input = orig_input\n self.eps = eps\n self.step_size = step_size\n self.use_grad = use_grad\n\n def project(self, x):\n '''\n Given an input x, project it back into the feasible set\n\n Args:\n ch.tensor x : the input to project back into the feasible set.\n\n Returns:\n A `ch.tensor` that is the input projected back into\n the feasible set, that is,\n .. math:: \\min_{x' \\in S} \\|x' - x\\|_2\n '''\n raise NotImplementedError\n\n def step(self, x, g):\n '''\n Given a gradient, make the appropriate step according to the\n perturbation constraint (e.g. dual norm maximization for :math:`\\ell_p`\n norms).\n\n Parameters:\n g (ch.tensor): the raw gradient\n\n Returns:\n The new input, a ch.tensor for the next step.\n '''\n raise NotImplementedError\n\n def random_perturb(self, x):\n '''\n Given a starting input, take a random step within the feasible set\n '''\n raise NotImplementedError\n\n def to_image(self, x):\n '''\n Given an input (which may be in an alternative parameterization),\n convert it to a valid image (this is implemented as the identity\n function by default as most of the time we use the pixel\n parameterization, but for alternative parameterizations this functino\n must be overriden).\n '''\n return x\n\n### Instantiations of the AttackerStep class\n\n# L-infinity threat model\nclass LinfStep(AttackerStep):\n \"\"\"\n Attack step for :math:`\\ell_\\infty` threat model. Given :math:`x_0`\n and :math:`\\epsilon`, the constraint set is given by:\n\n .. math:: S = \\{x | \\|x - x_0\\|_\\infty \\leq \\epsilon\\}\n \"\"\"\n def project(self, x):\n \"\"\"\n \"\"\"\n diff = x - self.orig_input\n diff = ch.clamp(diff, -self.eps, self.eps)\n return ch.clamp(diff + self.orig_input, 0, 1)\n\n def step(self, x, g):\n \"\"\"\n \"\"\"\n step = ch.sign(g) * self.step_size\n return x + step\n\n def random_perturb(self, x):\n \"\"\"\n \"\"\"\n new_x = x + 2 * (ch.rand_like(x) - 0.5) * self.eps\n return ch.clamp(new_x, 0, 1)\n\n# L2 threat model\nclass L2Step(AttackerStep):\n \"\"\"\n Attack step for :math:`\\ell_\\infty` threat model. Given :math:`x_0`\n and :math:`\\epsilon`, the constraint set is given by:\n\n .. math:: S = \\{x | \\|x - x_0\\|_2 \\leq \\epsilon\\}\n \"\"\"\n def project(self, x):\n \"\"\"\n \"\"\"\n diff = x - self.orig_input\n diff = diff.renorm(p=2, dim=0, maxnorm=self.eps)\n return ch.clamp(self.orig_input + diff, 0, 1)\n\n def step(self, x, g):\n \"\"\"\n \"\"\"\n l = len(x.shape) - 1\n g_norm = ch.norm(g.view(g.shape[0], -1), dim=1).view(-1, *([1]*l))\n scaled_g = g / (g_norm + 1e-10)\n return x + scaled_g * self.step_size\n\n def random_perturb(self, x):\n \"\"\"\n \"\"\"\n l = len(x.shape) - 1\n rp = ch.randn_like(x)\n rp_norm = rp.view(rp.shape[0], -1).norm(dim=1).view(-1, *([1]*l))\n return ch.clamp(x + self.eps * rp / (rp_norm + 1e-10), 0, 1)\n\n# Unconstrained threat model\nclass UnconstrainedStep(AttackerStep):\n \"\"\"\n Unconstrained threat model, :math:`S = [0, 1]^n`.\n \"\"\"\n def project(self, x):\n \"\"\"\n \"\"\"\n return ch.clamp(x, 0, 1)\n\n def step(self, x, g):\n \"\"\"\n \"\"\"\n return x + g * self.step_size\n\n def random_perturb(self, x):\n \"\"\"\n \"\"\"\n new_x = x + (ch.rand_like(x) - 0.5).renorm(p=2, dim=0, maxnorm=step_size)\n return ch.clamp(new_x, 0, 1)\n\nclass FourierStep(AttackerStep):\n \"\"\"\n Step under the Fourier (decorrelated) parameterization of an image.\n\n See https://distill.pub/2017/feature-visualization/#preconditioning for more information.\n \"\"\"\n def project(self, x):\n \"\"\"\n \"\"\"\n return x\n\n def step(self, x, g):\n \"\"\"\n \"\"\"\n return x + g * self.step_size\n\n def random_perturb(self, x):\n \"\"\"\n \"\"\"\n return x\n\n def to_image(self, x):\n \"\"\"\n \"\"\"\n return ch.sigmoid(ch.irfft(x, 2, normalized=True, onesided=False))\n\nclass RandomStep(AttackerStep):\n \"\"\"\n Step for Randomized Smoothing.\n \"\"\"\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.use_grad = False\n\n def project(self, x):\n \"\"\"\n \"\"\"\n return x\n\n def step(self, x, g):\n \"\"\"\n \"\"\"\n return x + self.step_size * ch.randn_like(x)\n\n def random_perturb(self, x):\n \"\"\"\n \"\"\"\n return x\n" ]
[ [ "torch.irfft", "torch.randn_like", "torch.rand_like", "torch.sign", "torch.clamp" ] ]
MourabitElBachir/visual-recognition-server-control-back
[ "859b385480e16de16cc4c4adb57f49e98bfd3ade" ]
[ "object_detection/builders/optimizer_builder.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\n\"\"\"Functions to build DetectionModel training optimizers.\"\"\"\n\nimport tensorflow as tf\nfrom object_detection.utils import learning_schedules\n\nslim = tf.contrib.slim\n\n\ndef build(optimizer_config, global_summaries):\n \"\"\"Create optimizer based on config.\n\n Args:\n optimizer_config: A Optimizer proto message.\n global_summaries: A set to attach learning rate summary to.\n\n Returns:\n An optimizer.\n\n Raises:\n ValueError: when using an unsupported input data type.\n \"\"\"\n optimizer_type = optimizer_config.WhichOneof('optimizer')\n optimizer = None\n\n if optimizer_type == 'rms_prop_optimizer':\n config = optimizer_config.rms_prop_optimizer\n optimizer = tf.train.RMSPropOptimizer(\n _create_learning_rate(config.learning_rate, global_summaries),\n decay=config.decay,\n momentum=config.momentum_optimizer_value,\n epsilon=config.epsilon)\n\n if optimizer_type == 'momentum_optimizer':\n config = optimizer_config.momentum_optimizer\n optimizer = tf.train.MomentumOptimizer(\n _create_learning_rate(config.learning_rate, global_summaries),\n momentum=config.momentum_optimizer_value)\n\n if optimizer_type == 'adam_optimizer':\n config = optimizer_config.adam_optimizer\n optimizer = tf.train.AdamOptimizer(\n _create_learning_rate(config.learning_rate, global_summaries))\n\n if optimizer is None:\n raise ValueError('Optimizer %s not supported.' % optimizer_type)\n\n if optimizer_config.use_moving_average:\n optimizer = tf.contrib.opt.MovingAverageOptimizer(\n optimizer, average_decay=optimizer_config.moving_average_decay)\n\n return optimizer\n\n\ndef _create_learning_rate(learning_rate_config, global_summaries):\n \"\"\"Create optimizer learning rate based on config.\n\n Args:\n learning_rate_config: A LearningRate proto message.\n global_summaries: A set to attach learning rate summary to.\n\n Returns:\n A learning rate.\n\n Raises:\n ValueError: when using an unsupported input data type.\n \"\"\"\n learning_rate = None\n learning_rate_type = learning_rate_config.WhichOneof('learning_rate')\n if learning_rate_type == 'constant_learning_rate':\n config = learning_rate_config.constant_learning_rate\n learning_rate = config.learning_rate\n\n if learning_rate_type == 'exponential_decay_learning_rate':\n config = learning_rate_config.exponential_decay_learning_rate\n learning_rate = tf.train.exponential_decay(\n config.initial_learning_rate,\n slim.get_or_create_global_step(),\n config.decay_steps,\n config.decay_factor,\n staircase=config.staircase)\n\n if learning_rate_type == 'manual_step_learning_rate':\n config = learning_rate_config.manual_step_learning_rate\n if not config.schedule:\n raise ValueError('Empty learning rate schedule.')\n learning_rate_step_boundaries = [x.step for x in config.schedule]\n learning_rate_sequence = [config.initial_learning_rate]\n learning_rate_sequence += [x.learning_rate for x in config.schedule]\n learning_rate = learning_schedules.manual_stepping(\n slim.get_or_create_global_step(), learning_rate_step_boundaries,\n learning_rate_sequence)\n\n if learning_rate is None:\n raise ValueError('Learning_rate %s not supported.' % learning_rate_type)\n\n global_summaries.add(tf.summary.scalar('Learning Rate', learning_rate))\n return learning_rate\n" ]
[ [ "tensorflow.contrib.opt.MovingAverageOptimizer", "tensorflow.summary.scalar" ] ]
while0l1/ranzcr2020
[ "64edbcbe638e7d52cd831e9edd40c72e96a7e3a0" ]
[ "load_dataset.py" ]
[ "from sklearn.model_selection import GroupKFold\nimport pandas as pd\nimport cv2\nimport os\nimport numpy as np\nimport ast\nimport torch\nimport albumentations\nfrom config import CFG\nfrom torch.utils.data import DataLoader\n\nclass RanzcrDataset(object):\n def __init__(self, root, df, mode='test', transforms=None, train_anno=None):\n self.root = root\n self.transforms = transforms\n self.filenames = (df['StudyInstanceUID']).values\n self.mode = mode\n self.train_anno = train_anno\n\n def __len__(self):\n return len(self.filenames)\n\n def __getitem__(self, idx):\n img_path = os.path.join(self.root, self.filenames[idx] + '.jpg')\n img = cv2.imread(img_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n if self.mode == 'test':\n img = self.transforms(image=img)['image']\n img = img.astype('float32').transpose(2, 0, 1) / 255.\n return img\n else:\n mask = np.zeros((img.shape[0], img.shape[1], 2)).astype('float32')\n mask0 = mask[:, :, 0].copy()\n mask1 = mask[:, :, 1].copy()\n this_anno = self.train_anno.query(f'StudyInstanceUID == \"{self.filenames[idx]}\"')\n for _, anno in this_anno.iterrows():\n data = np.array(ast.literal_eval(anno[\"data\"]))\n mask0 = cv2.polylines(mask0, np.int32([data]), isClosed=False, color=1, thickness=15, lineType=16) # 管道位置画线\n mask1 = cv2.circle(mask1, (data[0][0], data[0][1]), radius=15, color=1, thickness=25) # 管道开始位置画圈\n mask1 = cv2.circle(mask1, (data[-1][0], data[-1][1]), radius=15, color=1, thickness=25) # 管道结束位置画圈\n \n mask[:, :, 0] = mask0\n mask[:, :, 1] = mask1\n res = self.transforms(image=img, mask=mask)\n img = res['image']\n mask = res['mask']\n img = img.astype('float32').transpose(2, 0, 1) / 255.\n mask = mask.astype('float32').transpose(2, 0, 1)\n return torch.tensor(img), torch.tensor(mask)\n \ntransforms_train = albumentations.Compose([\n albumentations.Resize(CFG.image_size, CFG.image_size), \n albumentations.HorizontalFlip(p=0.5),\n albumentations.RandomBrightness(limit=0.1, p=0.75),\n # albumentations.OneOf([\n # albumentations.GaussNoise(var_limit=[10, 50]),\n # albumentations.MotionBlur(),\n # albumentations.MedianBlur(),\n # ], p=0.2),\n albumentations.ShiftScaleRotate(shift_limit=0.2, scale_limit=0.2, rotate_limit=30, border_mode=0, p=0.75),\n albumentations.Cutout(max_h_size=int(CFG.image_size * 0.3), max_w_size=int(CFG.image_size * 0.3), num_holes=1, p=0.75),\n# albumentations.Normalize(),\n])\ntransforms_valid = albumentations.Compose([\n albumentations.Resize(CFG.image_size, CFG.image_size),\n# albumentations.Normalize(),\n])\n\n\n'''\nK-fold划分数据集\n'''\ndef get_folds(nfolds=5):\n traindf = pd.read_csv(CFG.train_df_path)\n folds = traindf.copy()\n Fold = GroupKFold(n_splits=nfolds)\n groups = folds['PatientID'].values\n for n, (train_index, val_index) in enumerate(Fold.split(folds, folds[CFG.target_cols], groups)):\n folds.loc[val_index, 'fold'] = int(n) # 添加一个fold列,将val_index对应的行设置为n\n\n folds['fold'] = folds['fold'].astype(int)\n return folds\n\n'''\n得到有标注信息的样本表格\n'''\ndef get_df_with_anno():\n folds = get_folds(5) # k折\n train_anno = pd.read_csv(CFG.train_anno_path)\n unique_anno = train_anno.drop_duplicates(['StudyInstanceUID']).copy() # 去掉重复的样本名\n unique_anno['with_anno'] = True\n\n # 连接两个表\n train_v2 = pd.merge(folds, unique_anno[['StudyInstanceUID', 'with_anno']], left_on='StudyInstanceUID', right_on='StudyInstanceUID', how='left')\n\n # 将没有annotation的样本设置为False\n train_v2['with_anno'] = train_v2['with_anno'].fillna(value=False)\n sample_with_anno_df = train_v2[train_v2['with_anno'] == True].copy()\n return sample_with_anno_df\n\ndef get_seg_loader(fold_id, debug=False):\n sample_with_anno_df = get_df_with_anno()\n train_df = sample_with_anno_df[sample_with_anno_df.fold != fold_id]\n valid_df = sample_with_anno_df[sample_with_anno_df.fold == fold_id]\n\n # 小样本用作测试\n if debug:\n train_df = train_df.iloc[:16]\n valid_df = train_df.iloc[:16]\n\n train_anno = pd.read_csv(CFG.train_anno_path)\n\n train_data = RanzcrDataset(CFG.train_img_path, train_df, mode='train', transforms=transforms_train, train_anno=train_anno)\n valid_data = RanzcrDataset(CFG.train_img_path, valid_df, mode='valid', transforms=transforms_valid, train_anno=train_anno)\n\n train_loader = DataLoader(train_data, batch_size=CFG.seg_batch_size, shuffle=True, num_workers=CFG.num_workers)\n valid_loader = DataLoader(valid_data, batch_size=CFG.seg_batch_size, shuffle=False, num_workers=CFG.num_workers)\n return train_loader, valid_loader" ]
[ [ "torch.utils.data.DataLoader", "numpy.zeros", "pandas.read_csv", "sklearn.model_selection.GroupKFold", "torch.tensor", "numpy.int32", "pandas.merge" ] ]
jimthompson5802/ludwig
[ "8a369328a3f839d9cdb3710be315952c7891d7c0" ]
[ "tests/ludwig/encoders/test_text_encoders.py" ]
[ "import pytest\nimport torch\n\nfrom ludwig.encoders import text_encoders\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [None, \"sum\"])\[email protected](\"max_sequence_length\", [20])\ndef test_albert_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n albert_encoder = text_encoders.ALBERTEncoder(\n use_pretrained=use_pretrained,\n reduce_output=reduce_output,\n max_sequence_length=max_sequence_length,\n )\n inputs = torch.rand((2, max_sequence_length)).type(albert_encoder.input_dtype)\n inputs = torch.rand((2, max_sequence_length)).type(albert_encoder.input_dtype)\n outputs = albert_encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == albert_encoder.output_shape\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [None, \"cls_pooled\", \"sum\"])\[email protected](\"max_sequence_length\", [20])\ndef test_bert_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n bert = text_encoders.BERTEncoder(\n use_pretrained=use_pretrained,\n reduce_output=reduce_output,\n max_sequence_length=max_sequence_length,\n )\n inputs = torch.rand((2, max_sequence_length)).type(bert.input_dtype)\n outputs = bert(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == bert.output_shape\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [\"last\", \"sum\", \"mean\"])\[email protected](\"max_sequence_length\", [20])\ndef test_xlm_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n xlm_encoder = text_encoders.XLMEncoder(\n use_pretrained=use_pretrained,\n reduce_output=reduce_output,\n max_sequence_length=max_sequence_length,\n )\n inputs = torch.rand((2, max_sequence_length)).type(xlm_encoder.input_dtype)\n outputs = xlm_encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == xlm_encoder.output_shape\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [None, \"sum\"])\[email protected](\"max_sequence_length\", [20])\ndef test_gpt_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n gpt_encoder = text_encoders.GPTEncoder(\n use_pretrained=use_pretrained,\n reduce_output=reduce_output,\n max_sequence_length=max_sequence_length,\n )\n inputs = torch.rand((2, max_sequence_length)).type(gpt_encoder.input_dtype)\n outputs = gpt_encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == gpt_encoder.output_shape\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [\"cls_pooled\", \"sum\"])\[email protected](\"max_sequence_length\", [20])\ndef test_roberta_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n roberta_encoder = text_encoders.RoBERTaEncoder(\n use_pretrained=use_pretrained,\n reduce_output=reduce_output,\n max_sequence_length=max_sequence_length,\n )\n inputs = torch.rand((2, max_sequence_length)).type(roberta_encoder.input_dtype)\n outputs = roberta_encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == roberta_encoder.output_shape\n\n\[email protected](\"use_pretrained\", [True, False])\[email protected](\"reduce_output\", [None, \"sum\"])\[email protected](\"max_sequence_length\", [20])\ndef test_gpt2_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n gpt_encoder = text_encoders.GPT2Encoder(\n use_pretrained=use_pretrained,\n reduce_output=reduce_output,\n max_sequence_length=max_sequence_length,\n )\n inputs = torch.rand((2, max_sequence_length)).type(gpt_encoder.input_dtype)\n outputs = gpt_encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == gpt_encoder.output_shape\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [None, \"sum\"])\[email protected](\"max_sequence_length\", [20])\ndef test_distil_bert(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n distil_bert_encoder = text_encoders.DistilBERTEncoder(\n use_pretrained=use_pretrained,\n reduce_output=reduce_output,\n max_sequence_length=max_sequence_length,\n )\n inputs = torch.rand((2, max_sequence_length)).type(distil_bert_encoder.input_dtype)\n outputs = distil_bert_encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == distil_bert_encoder.output_shape\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [None, \"sum\"])\[email protected](\"max_sequence_length\", [20])\ndef test_transfoxl_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n transfo = text_encoders.TransformerXLEncoder(\n use_pretrained=use_pretrained,\n reduce_output=reduce_output,\n max_sequence_length=max_sequence_length,\n )\n inputs = torch.randint(10, (2, max_sequence_length)).type(transfo.input_dtype)\n outputs = transfo(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == transfo.output_shape\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [None, \"sum\"])\[email protected](\"max_sequence_length\", [20])\ndef test_ctrl_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n encoder = text_encoders.CTRLEncoder(\n max_sequence_length,\n use_pretrained=use_pretrained,\n reduce_output=reduce_output,\n )\n inputs = torch.rand((2, max_sequence_length)).type(encoder.input_dtype)\n outputs = encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == encoder.output_shape\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [None, \"cls_pooled\"])\[email protected](\"max_sequence_length\", [20])\ndef test_camembert_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n encoder = text_encoders.CamemBERTEncoder(\n use_pretrained=use_pretrained,\n reduce_output=reduce_output,\n max_sequence_length=max_sequence_length,\n )\n inputs = torch.rand((2, max_sequence_length)).type(encoder.input_dtype)\n outputs = encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == encoder.output_shape\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [None, \"cls_pooled\"])\[email protected](\"max_sequence_length\", [20])\ndef test_longformer_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n encoder = text_encoders.LongformerEncoder(\n use_pretrained=use_pretrained,\n reduce_output=reduce_output,\n max_sequence_length=max_sequence_length,\n )\n inputs = torch.rand((2, max_sequence_length)).type(encoder.input_dtype)\n outputs = encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == encoder.output_shape\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [None, \"sum\"])\[email protected](\"max_sequence_length\", [20])\ndef test_mt5_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n mt5_encoder = text_encoders.MT5Encoder(\n use_pretrained=use_pretrained,\n reduce_output=reduce_output,\n max_sequence_length=max_sequence_length,\n )\n inputs = torch.rand((2, max_sequence_length)).type(mt5_encoder.input_dtype)\n outputs = mt5_encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == mt5_encoder.output_shape\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [None, \"sum\"])\[email protected](\"max_sequence_length\", [20])\ndef test_xlmroberta_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n xlmroberta_encoder = text_encoders.XLMRoBERTaEncoder(\n use_pretrained=use_pretrained,\n reduce_output=reduce_output,\n max_sequence_length=max_sequence_length,\n )\n inputs = torch.rand((2, max_sequence_length)).type(xlmroberta_encoder.input_dtype)\n outputs = xlmroberta_encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == xlmroberta_encoder.output_shape\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [None, \"cls_pooled\"])\[email protected](\"max_sequence_length\", [20])\ndef test_longformer_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n encoder = text_encoders.LongformerEncoder(\n use_pretrained=use_pretrained, reduce_output=reduce_output, max_sequence_length=max_sequence_length\n )\n inputs = torch.rand((2, max_sequence_length)).type(encoder.input_dtype)\n outputs = encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == encoder.output_shape\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [None, \"sum\"])\[email protected](\"max_sequence_length\", [20])\ndef test_electra_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n encoder = text_encoders.ELECTRAEncoder(\n use_pretrained=use_pretrained, reduce_output=reduce_output, max_sequence_length=max_sequence_length\n )\n inputs = torch.rand((2, max_sequence_length)).type(encoder.input_dtype)\n outputs = encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == encoder.output_shape\n\n\[email protected](\"pretrained_model_name_or_path\", [\"bert-base-uncased\"])\[email protected](\"reduce_output\", [None, \"sum\", \"cls_pooled\"])\[email protected](\"max_sequence_length\", [20])\ndef test_auto_transformer_encoder(pretrained_model_name_or_path: str, reduce_output: str, max_sequence_length: int):\n encoder = text_encoders.AutoTransformerEncoder(\n pretrained_model_name_or_path=pretrained_model_name_or_path,\n reduce_output=reduce_output,\n max_sequence_length=max_sequence_length,\n )\n inputs = torch.rand((2, max_sequence_length)).type(encoder.input_dtype)\n outputs = encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == encoder.output_shape\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [None, \"sum\"])\[email protected](\"max_sequence_length\", [20])\ndef test_flaubert_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n encoder = text_encoders.FlauBERTEncoder(\n use_pretrained=use_pretrained, reduce_output=reduce_output, max_sequence_length=max_sequence_length\n )\n inputs = torch.rand((2, max_sequence_length)).type(encoder.input_dtype)\n outputs = encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == encoder.output_shape\n\n\[email protected](\"use_pretrained\", [False])\[email protected](\"reduce_output\", [None, \"sum\"])\[email protected](\"max_sequence_length\", [20])\ndef test_t5_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length: int):\n encoder = text_encoders.T5Encoder(\n use_pretrained=use_pretrained, reduce_output=reduce_output, max_sequence_length=max_sequence_length\n )\n inputs = torch.rand((2, max_sequence_length)).type(encoder.input_dtype)\n outputs = encoder(inputs)\n assert outputs[\"encoder_output\"].shape[1:] == encoder.output_shape\n" ]
[ [ "torch.rand", "torch.randint" ] ]
ZitongYu/Flex-Modal-FAS
[ "b5aad6aae1737ea5746ee7ae7330eb9893043095" ]
[ "Load_FAS_MultiModal.py" ]
[ "from __future__ import print_function, division\nimport os\nimport torch\nimport pandas as pd\n#from skimage import io, transform\nimport cv2\nimport numpy as np\nimport random\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nimport pdb\nimport math\nimport os \nimport imgaug.augmenters as iaa\n\n\n \n\n\n#face_scale = 0.9 #default for test, for training , can be set from [0.8 to 1.0]\n\n# data augment from 'imgaug' --> Add (value=(-40,40), per_channel=True), GammaContrast (gamma=(0.5,1.5))\nseq = iaa.Sequential([\n iaa.Add(value=(-40,40), per_channel=True), # Add color \n iaa.GammaContrast(gamma=(0.5,1.5)) # GammaContrast with a gamma of 0.5 to 1.5\n])\n\n\n\n# Tensor\nclass Cutout(object):\n def __init__(self, length=30):\n self.length = length\n\n def __call__(self, sample):\n img, image_x_depth, image_x_ir, spoofing_label, map_x1 = sample['image_x'],sample['image_x_depth'],sample['image_x_ir'],sample['spoofing_label'],sample['map_x1']\n h, w = img.shape[1], img.shape[2] # Tensor [1][2], nparray [0][1]\n mask = np.ones((h, w), np.float32)\n y = np.random.randint(h)\n x = np.random.randint(w)\n length_new = np.random.randint(1, self.length)\n \n y1 = np.clip(y - length_new // 2, 0, h)\n y2 = np.clip(y + length_new // 2, 0, h)\n x1 = np.clip(x - length_new // 2, 0, w)\n x2 = np.clip(x + length_new // 2, 0, w)\n\n mask[y1: y2, x1: x2] = 0.\n mask = torch.from_numpy(mask)\n mask = mask.expand_as(img)\n img *= mask\n image_x_depth *= mask\n image_x_ir *= mask\n \n return {'image_x': img, 'image_x_depth': image_x_depth, 'image_x_ir': image_x_ir, 'spoofing_label': spoofing_label, 'map_x1': map_x1}\n\n\nclass Normaliztion(object):\n \"\"\"\n same as mxnet, normalize into [-1, 1]\n image = (image - 127.5)/128\n \"\"\"\n def __call__(self, sample):\n image_x, image_x_depth, image_x_ir, spoofing_label, map_x1 = sample['image_x'],sample['image_x_depth'],sample['image_x_ir'],sample['spoofing_label'],sample['map_x1']\n new_image_x = (image_x - 127.5)/128 # [-1,1]\n new_image_x_depth = (image_x_depth - 127.5)/128 # [-1,1]\n new_image_x_ir = (image_x_ir - 127.5)/128 # [-1,1]\n return {'image_x': new_image_x, 'image_x_depth': new_image_x_depth, 'image_x_ir': new_image_x_ir, 'spoofing_label': spoofing_label, 'map_x1': map_x1}\n\n\n\nclass RandomHorizontalFlip(object):\n \"\"\"Horizontally flip the given Image randomly with a probability of 0.5.\"\"\"\n def __call__(self, sample):\n image_x, image_x_depth, image_x_ir, spoofing_label, map_x1 = sample['image_x'],sample['image_x_depth'],sample['image_x_ir'],sample['spoofing_label'],sample['map_x1']\n \n new_image_x = np.zeros((224, 224, 3))\n new_image_x_depth = np.zeros((224, 224, 3))\n new_image_x_ir = np.zeros((224, 224, 3))\n\n p = random.random()\n if p < 0.5:\n #print('Flip')\n\n new_image_x = cv2.flip(image_x, 1)\n new_image_x_depth = cv2.flip(image_x_depth, 1)\n new_image_x_ir = cv2.flip(image_x_ir, 1)\n\n \n return {'image_x': new_image_x, 'image_x_depth': new_image_x_depth, 'image_x_ir': new_image_x_ir, 'spoofing_label': spoofing_label, 'map_x1': map_x1}\n else:\n #print('no Flip')\n return {'image_x': image_x, 'image_x_depth': image_x_depth, 'image_x_ir': image_x_ir, 'spoofing_label': spoofing_label, 'map_x1': map_x1}\n\n\n\nclass ToTensor(object):\n \"\"\"\n Convert ndarrays in sample to Tensors.\n process only one batch every time\n \"\"\"\n\n def __call__(self, sample):\n image_x, image_x_depth, image_x_ir, spoofing_label, map_x1 = sample['image_x'],sample['image_x_depth'],sample['image_x_ir'],sample['spoofing_label'],sample['map_x1']\n \n # swap color axis because\n # numpy image: (batch_size) x H x W x C\n # torch image: (batch_size) x C X H X W\n image_x = image_x[:,:,::-1].transpose((2, 0, 1))\n image_x = np.array(image_x)\n \n image_x_depth = image_x_depth[:,:,::-1].transpose((2, 0, 1))\n image_x_depth = np.array(image_x_depth)\n \n image_x_ir = image_x_ir[:,:,::-1].transpose((2, 0, 1))\n image_x_ir = np.array(image_x_ir)\n \n map_x1 = np.array(map_x1)\n \n spoofing_label_np = np.array([0],dtype=np.long)\n spoofing_label_np[0] = spoofing_label\n \n \n return {'image_x': torch.from_numpy(image_x.astype(np.float)).float(), 'image_x_depth': torch.from_numpy(image_x_depth.astype(np.float)).float(), 'image_x_ir': torch.from_numpy(image_x_ir.astype(np.float)).float(), 'spoofing_label': torch.from_numpy(spoofing_label_np.astype(np.long)).long(), 'map_x1': torch.from_numpy(map_x1.astype(np.float)).float()}\n\n\n# /home/ztyu/FAS_dataset/OULU/Train_images/ 6_3_20_5_121_scene.jpg 6_3_20_5_121_scene.dat\n# /home/ztyu/FAS_dataset/OULU/IJCB_re/OULUtrain_images/ 6_3_20_5_121_depth1D.jpg\nclass Spoofing_train(Dataset):\n\n def __init__(self, info_list, root_dir, transform=None):\n\n self.landmarks_frame = pd.read_csv(info_list, delimiter=' ', header=None)\n self.root_dir = root_dir\n self.transform = transform\n\n def __len__(self):\n return len(self.landmarks_frame)\n\n \n def __getitem__(self, idx):\n #print(self.landmarks_frame.iloc[idx, 0])\n videoname = str(self.landmarks_frame.iloc[idx, 0])\n image_path = os.path.join(self.root_dir, videoname)\n \n videoname_depth = str(self.landmarks_frame.iloc[idx, 1])\n image_path_depth = os.path.join(self.root_dir, videoname_depth) \n \n videoname_ir = str(self.landmarks_frame.iloc[idx, 2])\n image_path_ir = os.path.join(self.root_dir, videoname_ir) \n \n \n #log_file2 = open('temp.txt', 'w')\n #log_file2.write('%s \\n' % (image_path))\n #log_file2.write('%s \\n' % (image_path_depth))\n #log_file2.write('%s \\n' % (image_path_ir))\n #log_file2.flush()\n \n image_x, map_x1 = self.get_single_image_x_RGB(image_path)\n image_x_depth = self.get_single_image_x(image_path_depth)\n image_x_ir = self.get_single_image_x(image_path_ir)\n\t\t \n spoofing_label = self.landmarks_frame.iloc[idx, 3]\n \n if spoofing_label == 1: # real\n spoofing_label = 1 # real\n #map_x1 = np.zeros((28, 28)) # real\n #map_x1 = np.ones((28, 28))\n else: # fake\n spoofing_label = 0\n #map_x1 = np.ones((28, 28)) # fake\n map_x1 = np.zeros((28, 28))\n \n\n sample = {'image_x': image_x, 'image_x_depth': image_x_depth, 'image_x_ir': image_x_ir, 'spoofing_label': spoofing_label, 'map_x1': map_x1}\n\n if self.transform:\n sample = self.transform(sample)\n return sample\n\n def get_single_image_x_RGB(self, image_path):\n \n image_x = np.zeros((224, 224, 3))\n binary_mask = np.zeros((28, 28))\n\n # RGB\n image_x_temp = cv2.imread(image_path)\n \n #cv2.imwrite('temp.jpg', image_x_temp)\n \n image_x = cv2.resize(image_x_temp, (224, 224))\n \n # data augment from 'imgaug' --> Add (value=(-40,40), per_channel=True), GammaContrast (gamma=(0.5,1.5))\n image_x_aug = seq.augment_image(image_x) \n \n image_x_temp_gray = cv2.imread(image_path, 0)\n image_x_temp_gray = cv2.resize(image_x_temp_gray, (28, 28))\n for i in range(28):\n for j in range(28):\n if image_x_temp_gray[i,j]>0:\n binary_mask[i,j]=1\n else:\n binary_mask[i,j]=0\n \n return image_x_aug, binary_mask\n \n def get_single_image_x(self, image_path):\n \n image_x = np.zeros((224, 224, 3))\n\n # RGB\n image_x_temp = cv2.imread(image_path)\n \n #cv2.imwrite('temp.jpg', image_x_temp)\n \n image_x = cv2.resize(image_x_temp, (224, 224))\n \n # data augment from 'imgaug' --> Add (value=(-40,40), per_channel=True), GammaContrast (gamma=(0.5,1.5))\n image_x_aug = seq.augment_image(image_x) \n \n \n return image_x_aug\n\n\n\n\n" ]
[ [ "numpy.ones", "numpy.zeros", "pandas.read_csv", "torch.from_numpy", "numpy.clip", "numpy.array", "numpy.random.randint" ] ]
AtreyeeS/gammapy
[ "a3b47c3da08900a833f0360e0374203e054cadfc" ]
[ "gammapy/datasets/flux_points.py" ]
[ "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport logging\nimport numpy as np\nfrom astropy import units as u\nfrom astropy.table import Table\nfrom astropy.visualization import quantity_support\nfrom gammapy.modeling.models import DatasetModels\nfrom gammapy.utils.scripts import make_name, make_path\nfrom .core import Dataset\nfrom .utils import get_axes\n\nlog = logging.getLogger(__name__)\n\n__all__ = [\"FluxPointsDataset\"]\n\n\nclass FluxPointsDataset(Dataset):\n \"\"\"\n Fit a set of flux points with a parametric model.\n\n Parameters\n ----------\n models : `~gammapy.modeling.models.Models`\n Models (only spectral part needs to be set)\n data : `~gammapy.estimators.FluxPoints`\n Flux points.\n mask_fit : `numpy.ndarray`\n Mask to apply for fitting\n mask_safe : `numpy.ndarray`\n Mask defining the safe data range. By default upper limit values are excluded.\n meta_table : `~astropy.table.Table`\n Table listing informations on observations used to create the dataset.\n One line per observation for stacked datasets.\n\n Examples\n --------\n Load flux points from file and fit with a power-law model::\n\n from gammapy.modeling import Fit\n from gammapy.modeling.models import PowerLawSpectralModel, SkyModel\n from gammapy.estimators import FluxPoints\n from gammapy.datasets import FluxPointsDataset\n\n filename = \"$GAMMAPY_DATA/tests/spectrum/flux_points/diff_flux_points.fits\"\n flux_points = FluxPoints.read(filename)\n\n model = SkyModel(spectral_model=PowerLawSpectralModel())\n\n dataset = FluxPointsDataset(model, flux_points)\n fit = Fit()\n result = fit.run([dataset])\n print(result)\n print(result.parameters.to_table())\n\n Note: In order to reproduce the example you need the tests datasets folder.\n You may download it with the command\n ``gammapy download datasets --tests --out $GAMMAPY_DATA``\n \"\"\"\n\n stat_type = \"chi2\"\n tag = \"FluxPointsDataset\"\n\n def __init__(\n self,\n models=None,\n data=None,\n mask_fit=None,\n mask_safe=None,\n name=None,\n meta_table=None,\n ):\n self.data = data\n self.mask_fit = mask_fit\n self._name = make_name(name)\n self.models = models\n self.meta_table = meta_table\n\n if mask_safe is None:\n mask_safe = (~data.is_ul).data[:, 0, 0]\n\n self.mask_safe = mask_safe\n\n @property\n def name(self):\n return self._name\n\n @property\n def gti(self):\n \"\"\"Good time interval info (`GTI`)\"\"\"\n return self.data.gti\n\n @property\n def models(self):\n return self._models\n\n @models.setter\n def models(self, models):\n if models is None:\n self._models = None\n else:\n models = DatasetModels(models)\n self._models = models.select(datasets_names=self.name)\n\n def write(self, filename, overwrite=True, **kwargs):\n \"\"\"Write flux point dataset to file.\n\n Parameters\n ----------\n filename : str\n Filename to write to.\n overwrite : bool\n Overwrite existing file.\n **kwargs : dict\n Keyword arguments passed to `~astropy.table.Table.write`.\n \"\"\"\n table = self.data.to_table()\n\n if self.mask_fit is None:\n mask_fit = self.mask_safe\n else:\n mask_fit = self.mask_fit\n\n table[\"mask_fit\"] = mask_fit\n table[\"mask_safe\"] = self.mask_safe\n table.write(make_path(filename), overwrite=overwrite, **kwargs)\n\n @classmethod\n def from_dict(cls, data, **kwargs):\n \"\"\"Create flux point dataset from dict.\n\n Parameters\n ----------\n data : dict\n Dict containing data to create dataset from.\n\n Returns\n -------\n dataset : `FluxPointsDataset`\n Flux point datasets.\n \"\"\"\n from gammapy.estimators import FluxPoints\n\n filename = make_path(data[\"filename\"])\n table = Table.read(filename)\n mask_fit = table[\"mask_fit\"].data.astype(\"bool\")\n mask_safe = table[\"mask_safe\"].data.astype(\"bool\")\n table.remove_columns([\"mask_fit\", \"mask_safe\"])\n return cls(\n name=data[\"name\"],\n data=FluxPoints.from_table(table, format=\"gadf-sed\"),\n mask_fit=mask_fit,\n mask_safe=mask_safe,\n )\n\n def __str__(self):\n str_ = f\"{self.__class__.__name__}\\n\"\n str_ += \"-\" * len(self.__class__.__name__) + \"\\n\"\n str_ += \"\\n\"\n\n str_ += \"\\t{:32}: {} \\n\\n\".format(\"Name\", self.name)\n\n # data section\n n_bins = 0\n if self.data is not None:\n n_bins = self.data.energy_axis.nbin\n str_ += \"\\t{:32}: {} \\n\".format(\"Number of total flux points\", n_bins)\n\n n_fit_bins = 0\n if self.mask is not None:\n n_fit_bins = np.sum(self.mask.data)\n str_ += \"\\t{:32}: {} \\n\\n\".format(\"Number of fit bins\", n_fit_bins)\n\n # likelihood section\n str_ += \"\\t{:32}: {}\\n\".format(\"Fit statistic type\", self.stat_type)\n\n stat = np.nan\n if self.data is not None and self.models is not None:\n stat = self.stat_sum()\n str_ += \"\\t{:32}: {:.2f}\\n\\n\".format(\"Fit statistic value (-2 log(L))\", stat)\n\n # model section\n n_models = 0\n if self.models is not None:\n n_models = len(self.models)\n\n str_ += \"\\t{:32}: {} \\n\".format(\"Number of models\", n_models)\n\n str_ += \"\\t{:32}: {}\\n\".format(\n \"Number of parameters\", len(self.models.parameters)\n )\n str_ += \"\\t{:32}: {}\\n\\n\".format(\n \"Number of free parameters\", len(self.models.parameters.free_parameters)\n )\n\n if self.models is not None:\n str_ += \"\\t\" + \"\\n\\t\".join(str(self.models).split(\"\\n\")[2:])\n\n return str_.expandtabs(tabsize=2)\n\n def data_shape(self):\n \"\"\"Shape of the flux points data (tuple).\"\"\"\n return self.data.energy_ref.shape\n\n def flux_pred(self):\n \"\"\"Compute predicted flux.\"\"\"\n flux = 0.0\n for model in self.models:\n flux += model.spectral_model(self.data.energy_ref)\n return flux\n\n def stat_array(self):\n \"\"\"Fit statistic array.\"\"\"\n model = self.flux_pred()\n data = self.data.dnde.quantity[:, 0, 0]\n try:\n sigma = self.data.dnde_err\n except AttributeError:\n sigma = (self.data.dnde_errn + self.data.dnde_errp) / 2\n return ((data - model) / sigma.quantity[:, 0, 0]).to_value(\"\") ** 2\n\n def residuals(self, method=\"diff\"):\n \"\"\"Compute the flux point residuals ().\n\n Parameters\n ----------\n method: {\"diff\", \"diff/model\"}\n Method used to compute the residuals. Available options are:\n - `diff` (default): data - model\n - `diff/model`: (data - model) / model\n\n Returns\n -------\n residuals : `~numpy.ndarray`\n Residuals array.\n \"\"\"\n fp = self.data\n\n model = self.flux_pred()\n\n residuals = self._compute_residuals(fp.dnde.quantity[:, 0, 0], model, method)\n # Remove residuals for upper_limits\n residuals[fp.is_ul.data[:, 0, 0]] = np.nan\n return residuals\n\n def plot_fit(\n self,\n ax_spectrum=None,\n ax_residuals=None,\n kwargs_spectrum=None,\n kwargs_residuals=None,\n ):\n \"\"\"Plot flux points, best fit model and residuals in two panels.\n\n Calls `~FluxPointsDataset.plot_spectrum` and `~FluxPointsDataset.plot_residuals`.\n\n Parameters\n ----------\n ax_spectrum : `~matplotlib.axes.Axes`\n Axes to plot flux points and best fit model on.\n ax_residuals : `~matplotlib.axes.Axes`\n Axes to plot residuals on.\n kwargs_spectrum : dict\n Keyword arguments passed to `~FluxPointsDataset.plot_spectrum`.\n kwargs_residuals : dict\n Keyword arguments passed to `~FluxPointsDataset.plot_residuals`.\n\n Returns\n -------\n ax_spectrum, ax_residuals : `~matplotlib.axes.Axes`\n Flux points, best fit model and residuals plots.\n \"\"\"\n import matplotlib.pyplot as plt\n from matplotlib.gridspec import GridSpec\n\n fig = plt.figure(figsize=(9, 7))\n\n gs = GridSpec(7, 1)\n if ax_spectrum is None:\n ax_spectrum = fig.add_subplot(gs[:5, :])\n\n if ax_residuals is None:\n ax_residuals = fig.add_subplot(gs[5:, :], sharex=ax_spectrum)\n\n kwargs_spectrum = kwargs_spectrum or {}\n kwargs_residuals = kwargs_residuals or {}\n kwargs_residuals.setdefault(\"method\", \"diff/model\")\n\n self.plot_spectrum(ax=ax_spectrum, **kwargs_spectrum)\n self.plot_residuals(ax=ax_residuals, **kwargs_residuals)\n return ax_spectrum, ax_residuals\n\n @property\n def _energy_bounds(self):\n try:\n return u.Quantity([self.data.energy_min.min(), self.data.energy_max.max()])\n except KeyError:\n return u.Quantity([self.data.energy_ref.min(), self.data.energy_ref.max()])\n\n @property\n def _energy_unit(self):\n return self.data.energy_ref.unit\n\n def plot_residuals(self, ax=None, method=\"diff\", **kwargs):\n \"\"\"Plot flux point residuals.\n\n Parameters\n ----------\n ax : `~matplotlib.axes.Axes`\n Axes to plot on.\n method : {\"diff\", \"diff/model\"}\n Normalization used to compute the residuals, see `FluxPointsDataset.residuals`.\n **kwargs : dict\n Keyword arguments passed to `~matplotlib.axes.Axes.errorbar`.\n\n Returns\n -------\n ax : `~matplotlib.axes.Axes`\n Axes object.\n \"\"\"\n import matplotlib.pyplot as plt\n\n ax = ax or plt.gca()\n\n fp = self.data\n residuals = self.residuals(method)\n\n xerr = self.data.energy_axis.as_plot_xerr\n\n yerr = fp._plot_get_flux_err(sed_type=\"dnde\")\n\n if method == \"diff/model\":\n model = self.flux_pred()\n yerr = (yerr[0].quantity[:, 0, 0] / model), (yerr[1].quantity[:, 0, 0] / model)\n elif method == \"diff\":\n yerr = yerr[0].quantity[:, 0, 0], yerr[1].quantity[:, 0, 0]\n else:\n raise ValueError('Invalid method, choose between \"diff\" and \"diff/model\"')\n\n kwargs.setdefault(\"color\", kwargs.pop(\"c\", \"black\"))\n kwargs.setdefault(\"marker\", \"+\")\n kwargs.setdefault(\"linestyle\", kwargs.pop(\"ls\", \"none\"))\n\n with quantity_support():\n ax.errorbar(\n fp.energy_ref, residuals, xerr=xerr, yerr=yerr, **kwargs\n )\n\n ax.axhline(0, color=kwargs[\"color\"], lw=0.5)\n\n # format axes\n ax.set_xlabel(f\"Energy [{self._energy_unit}]\")\n ax.set_xscale(\"log\")\n label = self._residuals_labels[method]\n ax.set_ylabel(f\"Residuals\\n {label}\")\n ymin = np.nanmin(residuals - yerr[0])\n ymax = np.nanmax(residuals + yerr[1])\n ymax = max(abs(ymin), ymax)\n ax.set_ylim(-1.05 * ymax, 1.05 * ymax)\n return ax\n\n def plot_spectrum(self, ax=None, kwargs_fp=None, kwargs_model=None):\n \"\"\"Plot spectrum including flux points and model.\n\n Parameters\n ----------\n ax : `~matplotlib.axes.Axes`\n Axes to plot on.\n kwargs_fp : dict\n Keyword arguments passed to `gammapy.estimators.FluxPoints.plot`.\n kwargs_model : dict\n Keyword arguments passed to `gammapy.modeling.models.SpectralModel.plot` and\n `gammapy.modeling.models.SpectralModel.plot_error`.\n\n Returns\n -------\n ax : `~matplotlib.axes.Axes`\n Axes object.\n \"\"\"\n kwargs_fp = (kwargs_fp or {}).copy()\n kwargs_model = (kwargs_model or {}).copy()\n\n # plot flux points\n kwargs_fp.setdefault(\"label\", \"Flux points\")\n kwargs_fp.setdefault(\"sed_type\", \"e2dnde\")\n ax = self.data.plot(ax, **kwargs_fp)\n\n kwargs_model.setdefault(\"energy_bounds\", self._energy_bounds)\n kwargs_model.setdefault(\"label\", \"Best fit model\")\n kwargs_model.setdefault(\"sed_type\", \"e2dnde\")\n kwargs_model.setdefault(\"zorder\", 10)\n\n for model in self.models:\n if model.datasets_names is None or self.name in model.datasets_names:\n model.spectral_model.plot(ax=ax, **kwargs_model)\n\n kwargs_model[\"color\"] = ax.lines[-1].get_color()\n kwargs_model.pop(\"label\")\n\n for model in self.models:\n if model.datasets_names is None or self.name in model.datasets_names:\n model.spectral_model.plot_error(ax=ax, **kwargs_model)\n\n return ax\n" ]
[ [ "numpy.sum", "numpy.nanmax", "matplotlib.pyplot.figure", "matplotlib.pyplot.gca", "numpy.nanmin", "matplotlib.gridspec.GridSpec" ] ]
NeolithEra/mbin
[ "27e9aea4ed67a48cc2d993a0fbd142a651e9ee7b" ]
[ "mbin/controls.py" ]
[ "import os,sys\nimport optparse\nimport logging\nfrom pbcore.io.align.CmpH5IO import CmpH5Reader\nfrom pbcore.io import openIndexedAlignmentFile\nfrom pbcore.io.BasH5IO import BasH5Reader\nimport glob\nimport numpy as np\nimport logging\nimport shutil\nimport pickle\nimport math\nimport mbin\nimport motif_tools\n\ndef launch():\n\topts,control_aln_fn = __parseArgs()\n\t__initLog(opts)\n\n\textract_controls(opts, control_aln_fn)\n\n\tprint >> sys.stderr, \"mBin control extraction has finished running. See log for details.\"\n\ndef extract_controls(opts, control_aln_fn):\n\t\"\"\"\n\n\t\"\"\"\n\tcontrols = ControlRunner(control_aln_fn, opts)\n\tmbinRunner = mbin.mbinRunner(opts)\n\n\t# Pulling the IPD data for each motif from the WGA cmp.h5 file\n\tmotifs,bi_motifs = motif_tools.build_motif_sets(opts)\n\topts.motifs = motifs\n\topts.bi_motifs = bi_motifs\n\n\tlogging.info(\"\")\n\tlogging.info(\"Preparing to create new control data in %s\" % opts.control_tmp)\n\tcontrols.goto_control_output_dir()\n\t\n\topts = controls.scan_WGA_aligns()\n\tfilter_N_reads = opts.N_reads\n\n\tmbinRunner.launch_data_loader( control_aln_fn, filter_N_reads, 1, opts )\n\t\n\tcontrols.analyze_WGA_reads()\n\tlogging.info(\"Done.\")\n\tlogging.info(\"\")\n\n\t# Building dictionary of mean control IPD values for each motif\n\tlogging.info(\"Building dictionary of control values for all motifs...\")\n\tlogging.info(\" * Initial build requires significant time and memory.\")\n\tcontrols.combine_control_data_from_contigs()\n\n\t\n\tcontrol_means = controls.build_control_IPD_dict(motifs, bi_motifs)\n\tcontrols.return_to_orig_dir()\n\n\tlogging.info(\"\")\n\tlogging.info(\"Cleaning up temp files from control data processing...\")\n\tshutil.rmtree(opts.control_tmp)\n\n\t# Controls are loaded into control_means, now pickle them for easy\n\t# passing between parallel processes\n\tpickle.dump(control_means, open(opts.control_pkl_name, \"wb\"))\n\ndef chunks( l, n ):\n\t\"\"\"\n\tYield successive n-sized chunks from l.\n\t\"\"\"\n\tfor i in xrange(0, len(l), n):\n\t\tyield l[i:i+n]\n\ndef __parseArgs():\n\t\"\"\"Handle command line argument parsing\"\"\"\n\n\tusage = \"\"\"%prog [--help] [options] [input]\n\n\tbuildcontrols takes a set of whole-genome amplified (WGA) sequencing \n\talignments, either in the legacy *.cmp.h5 PacBio format or the newer\n\taligned BAM format. buildcontrols then reads the polymerase kinetics\n\tvalues from these alignments and constructs a pickled dictionary of\n\tcontrol IPD values for the specified set of motifs. This output is \n\twritten to ./control_ipds.pkl by default.\n\n\tExamples:\n\n\t### Get control IPD values from BAM file of aligned WGA reads ###\n\n\tbuildcontrols -i --ref=reference.fasta wga_aligned_reads.bam\n\n\t\n\t### Use 4 cores to process legacy cmp.h5 file of aligned WGA reads ###\n\n\tbuildcontrols -i --procs=4 wga_aligned_reads.cmp.h5\n\n\t\n\t### Only include data from the first 500 alignments (e.g. for testing) ###\n\n\tbuildcontrols -i --N_reads=500 --ref=reference.fasta wga_aligned_reads.bam\n\n\n\t### Exclude all bipartite motifs from the control dictionary ###\n\n\tbuildcontrols -i --no_bipartite --ref=reference.fasta wga_aligned_reads.bam\n\t\"\"\"\n\n\tparser = optparse.OptionParser( usage=usage, description=__doc__ )\n\n\tparser.add_option( \"-d\", \"--debug\", action=\"store_true\", help=\"Increase verbosity of logging\" )\n\n\tparser.add_option( \"-i\", \"--info\", action=\"store_true\", help=\"Add basic logging\" )\n\n\tparser.add_option( \"--logFile\", type=\"str\", help=\"Write logging to file [log.controls]\" )\n\n\tparser.add_option( \"--ref\", type=\"str\", help=\"Path to reference fasta file used in the alignment. Must be accompanied by an index file (use samtools faidx). Required if input is BAM file of aligned reads (not needed for cmp.h5). [None]\" )\n\t\n\tparser.add_option( \"--subreadlength_min\", type=\"int\", help=\"Minimum subread length to include for analysis [100]\" )\n\n\tparser.add_option( \"--readlength_min\", type=\"int\", help=\"Minimum read length to include for analysis [100]\" )\n\n\tparser.add_option( \"--min_kmer\", type=\"int\", help=\"Minimum motif size to scan (contiguous motifs) [4]\" )\n\n\tparser.add_option( \"--max_kmer\", type=\"int\", help=\"Maximum motif size to scan (contiguous motifs) [6]\" )\n\n\tparser.add_option( \"--no_bipartite\", action=\"store_true\", help=\"Omit bipartite motifs [False]\" )\n\t\n\tparser.add_option( \"--bipart_first\", type=\"str\", help=\"Bipartite motif configuration: acceptable length of first determinate component (comma-separated string of integers) [3,4]\" )\n\t\n\tparser.add_option( \"--bipart_Ns\", type=\"str\", help=\"Bipartite motif configuration: acceptable length of middle indeterminate component (comma-separated string of integers) [5,6]\" )\n\t\n\tparser.add_option( \"--bipart_second\", type=\"str\", help=\"Bipartite motif configuration: acceptable length of second determinate component (comma-separated string of integers) [3,4]\" )\n\n\tparser.add_option( \"--mod_bases\", type=\"str\", help=\"String containing bases to query for mods. Changing this is not recommended ['A']\" )\n\n\tparser.add_option( \"--minAcc\", type=\"float\", help=\"Min subread accuracy of read [0.8]\" )\n\n\tparser.add_option( \"--minMapQV\", type=\"float\", help=\"Min mapping QV of aligned read [240]\" )\n\n\tparser.add_option( \"--procs\", type=\"int\", help=\"Number of cores to use [4]\" )\n\n\tparser.add_option( \"--N_reads\", type=\"int\", help=\"Number of qualifying reads to include in analysis [1000000000]\" )\n\t\n\tparser.add_option( \"--min_motif_count\", type=\"int\", help=\"Number of motif sites required in WGA data to be included in controls dictionary [10]\" )\n\n\tparser.add_option( \"--control_pkl_name\", type=\"str\", help=\"Filename to save control IPD data from WGA sequencing [control_ipds.pkl]\" )\n\t\n\tparser.set_defaults( logFile=\"log.buildcontrols\", \\\n\t\t\t\t\t\t info=False, \\\n\t\t\t\t\t\t debug=False, \\\n\t\t\t\t\t\t ref=None, \\\n\t\t\t\t\t\t subreadlength_min=100, \\\n\t\t\t\t\t\t readlength_min=100, \\\n\t\t\t\t\t\t min_kmer=4, \\\n\t\t\t\t\t\t max_kmer=6, \\\n\t\t\t\t\t\t no_bipartite=False, \\\n\t\t\t\t\t\t bipart_first=\"3,4\", \\\n\t\t\t\t\t\t bipart_Ns=\"5,6\", \\\n\t\t\t\t\t\t bipart_second=\"3,4\", \\\n\t\t\t\t\t\t mod_bases=\"A\", \\\n\t\t\t\t\t\t minAcc=0.8, \\\n\t\t\t\t\t\t minMapQV=240, \\\n\t\t\t\t\t\t procs=4, \\\n\t\t\t\t\t\t N_reads=1000000000, \\\n\t\t\t\t\t\t min_motif_count=10, \\\n\t\t\t\t\t\t control_pkl_name=\"control_ipds.pkl\")\n\n\topts, args = parser.parse_args( )\n\tcontrol_aln_fn = __check_input( opts, args, parser )\n\n\tif opts.no_bipartite:\n\t\topts.bipartite = False\n\telse:\n\t\topts.bipartite = True\n\n\t############################################\n\t# Define the types of bipartite motifs to \n\t# include in the analysis. This describes the\n\t# acceptable sizes of the three components of\n\t# bipartite motifs. For example, the motif \n\t# ACCT/NNNNN/CTT (first/Ns/last) would be \n\t# described by 4/5/3.\n\t\n\tfirst = map(lambda x: int(x), opts.bipart_first.split(\",\"))\n\tmiddle = map(lambda x: int(x), opts.bipart_Ns.split(\",\"))\n\tsecond = map(lambda x: int(x), opts.bipart_second.split(\",\"))\n\topts.bipart_config = [(first), (middle), (second)]\n\t\n\t# As set, acceptible bipartite motifs would have\n\t# the following component lengths.\n\t# First: 3 or 4 ACGT bases\n\t# Ns: 5 or 6 unspecified N bases\n\t# Last: 3 or 4 ACGT bases\n\t############################################\n\n\topts.control_tmp = \"ctrl_tmp\"\n\topts.tmp = \"tmp\"\n\topts.minContigLength = 0\n\topts.comp_kmer = 5\n\t# opts.h5_type = \"cmp\"\n\topts.cross_cov_bins = None\n\topts.sam = None\n\topts.motifs_file = None\n\topts.skip_motifs = None\n\t\n\topts.control_pkl_name = os.path.abspath(opts.control_pkl_name)\n\tif opts.ref!=None:\n\t\topts.ref = os.path.abspath(opts.ref)\n\n\treturn opts,control_aln_fn\n\ndef __initLog( opts ):\n\t\"\"\"Sets up logging based on command line arguments. Allows for three levels of logging:\n\tlogging.error( ): always emitted\n\tlogging.info( ) : emitted with --info or --debug\n\tlogging.debug( ): only with --debug\"\"\"\n\n\tif os.path.exists(opts.logFile):\n\t\tos.remove(opts.logFile)\n\n\tlogLevel = logging.DEBUG if opts.debug \\\n\t\t\t\telse logging.INFO if opts.info \\\n\t\t\t\telse logging.ERROR\n\n\tlogger = logging.getLogger(\"\")\n\tlogger.setLevel(logLevel)\n\t\n\t# create file handler which logs even debug messages\n\tfh = logging.FileHandler(opts.logFile)\n\tfh.setLevel(logLevel)\n\t\n\t# create console handler with a higher log level\n\tch = logging.StreamHandler()\n\tch.setLevel(logLevel)\n\t\n\t# create formatter and add it to the handlers\n\tlogFormat = \"%(asctime)s [%(levelname)s] %(message)s\"\n\tformatter = logging.Formatter(logFormat, \"%Y-%m-%d %H:%M:%S\")\n\tch.setFormatter(formatter)\n\tfh.setFormatter(formatter)\n\t\n\t# add the handlers to logger\n\tlogger.addHandler(ch)\n\tlogger.addHandler(fh)\n\ndef __check_input( opts, args, parser ):\n\tcontrol_aln_fn = os.path.abspath(args[0])\n\n\tif control_aln_fn[-7:]==\".cmp.h5\":\n\t\topts.aln_ftype = \"cmp\"\n\t\topts.aligned = True\n\telif control_aln_fn[-4:]==\".bam\":\n\t\topts.aln_ftype = \"bam\"\n\t\topts.aligned = True\n\telse:\n\t\tparser.error(\"Could not recognize valid input (BAM or cmp.h5 file of aligned reads): %s\" % control_aln_fn)\n\n\tif opts.aln_ftype==\"bam\" and opts.ref==None:\n\t\tparser.error(\"With BAM input, must specify reference fasta using --ref. Fasta must be indexed (use samtools faidx).\")\n\n\t# if opts.contigs==None:\n\t# \tparser.error(\"Please specify the fasta file used for the alignments in %s!\" % control_aln_fn)\n\n\tif len(args) != 1:\n\t\tparser.error( \"Expected 1 argument.\" )\n\n\treturn control_aln_fn\n\ndef process_contig_chunk( args ):\n\tchunk_id = args[0]\n\tcut_CMDs = args[1]\n\tkmers = args[2]\n\tcols_chunk = args[3]\n\tn_chunks = args[4]\n\tmin_motif_count = args[5]\n\tlogging.info(\" - Control data: chunk %s/%s\" % ((chunk_id+1), (n_chunks+1)))\n\tcontrol_means = {}\n\t\n\tfor cut_CMD in cut_CMDs:\n\t\tsts,stdOutErr = mbin.run_OS_command( cut_CMD )\n\t\n\tfns = map(lambda x: x.split(\"> \")[-1], cut_CMDs)\n\tcontrol_ipds_sub = np.loadtxt(fns[0], dtype=\"float\")\n\tcontrol_ipds_N_sub = np.loadtxt(fns[1], dtype=\"int\")\n\t# If there is only one row (read) for this contig, still treat as\n\t# a 2d matrix of many reads\n\tcontrol_ipds_sub = np.atleast_2d(control_ipds_sub)\n\tcontrol_ipds_N_sub = np.atleast_2d(control_ipds_N_sub)\n\t\n\tnot_found = 0\n\tfor j in range(len(cols_chunk)):\n\t\tmotif = kmers[cols_chunk[j]]\n\t\tif np.sum(control_ipds_N_sub[:,j])>=min_motif_count:\n\t\t\tif np.sum(control_ipds_N_sub[:,j])>0:\n\t\t\t\tcontrol_mean = np.dot(control_ipds_sub[:,j], control_ipds_N_sub[:,j]) / np.sum(control_ipds_N_sub[:,j])\n\t\t\telse:\n\t\t\t\tcontrol_mean = 0\n\t\t\tcontrol_means[motif] = control_mean\n\t\telse:\n\t\t\tnot_found += 1\n\n\treturn control_means,not_found\n\nclass ControlRunner:\n\tdef __init__( self, wga_h5, opts ):\n\t\t\"\"\"\n\t\tPoint to the appropriate WGA sequencing data files\n\t\tto generate the control IPD values for the motifs. \n\t\t\"\"\"\n\t\tself.control_aln_fn = wga_h5\n\t\tself.opts = opts\n\t\tself.orig_dir = os.getcwd()\n\n\tdef build_insilico_controls( self ):\n\t\t\"\"\"\n\t\tTo be added...\n\t\t\"\"\"\n\t\tpass\n\n\tdef goto_control_output_dir( self ):\n\t\t\"\"\"\n\t\tCreate directory where data from control reads \n\t\twill be gathered and analyzed.\n\t\t\"\"\"\n\t\t# Make control directory\n\t\tif os.path.exists(self.opts.control_tmp):\n\t\t\tshutil.rmtree(self.opts.control_tmp)\n\t\tos.mkdir(self.opts.control_tmp)\n\t\tos.chdir(self.opts.control_tmp)\n\t\t\n\t\t# Make tmp directory inside control directory\n\t\tif os.path.exists(self.opts.tmp):\n\t\t\tshutil.rmtree(self.opts.tmp)\n\t\tos.mkdir(self.opts.tmp)\n\n\tdef return_to_orig_dir( self ):\n\t\t\"\"\"\n\t\tBack out of the control directory.\n\t\t\"\"\"\n\t\tos.chdir(self.orig_dir)\n\n\tdef scan_WGA_aligns( self ):\n\t\t\"\"\"\n\t\tGet some necessary information about the WGA cmp.h5 \n\t\tbeing used to generate the control IPD data.\n\t\t\"\"\"\n\t\tself.opts.aln_fn_labels = {}\n\t\tself.opts.aln_fn_contig_lens = {}\n\t\tself.opts.aln_fn_labels[self.control_aln_fn] = \"control\"\n\t\tself.opts.aln_fn_contig_lens[self.control_aln_fn] = {}\n\t\t\n\t\t# reader = CmpH5Reader(self.control_aln_fn)\n\t\treader = openIndexedAlignmentFile(self.control_aln_fn)\n\t\tfor entry in reader.referenceInfoTable:\n\t\t\tname = entry[3]\n\t\t\tlength = entry[4]\n\t\t\tslug_name = mbin.slugify(name)\n\t\t\tself.opts.aln_fn_contig_lens[self.control_aln_fn][slug_name] = length\n\t\treader.close()\n\n\t\treturn self.opts\n\n\tdef analyze_WGA_reads( self ):\n\t\t\"\"\"\n\t\tLaunch read scanning pipeline for building up\n\t\tcontrol IPD values for motifs.\n\t\t\"\"\"\n\t\tcontrol_fns = glob.glob( os.path.join(self.opts.tmp, \"*.tmp\"))\n\t\tftypes = set( map(lambda x: \"_\".join(os.path.basename(x).split(\"_\")[2:]), control_fns) )\n\t\tfor ftype in ftypes:\n\t\t\tif ftype in [\"compkmers.tmp\", \"ipdskmers.tmp\"]:\n\t\t\t\t# first_fn = glob.glob( os.path.join(self.opts.tmp, \"unitig_*_%s\" % ftype) )[0]\n\t\t\t\tfirst_fn = glob.glob( os.path.join(self.opts.tmp, \"*_%s\" % ftype) )[0]\n\t\t\t\tshutil.copy( first_fn, os.path.join(self.opts.tmp, \"control_%s\" % ftype) )\n\t\t\t\t\n\t\t\t\tftype_fns = glob.glob( os.path.join(self.opts.tmp, \"*_%s\" % ftype))\n\t\t\t\tto_rm = [fn for fn in ftype_fns if not os.path.basename(fn).startswith(\"control_\")]\n\t\t\t\tfor fn in to_rm:\n\t\t\t\t\tos.remove(fn)\n\t\t\telse:\n\t\t\t\tftype_fns = glob.glob( os.path.join(self.opts.tmp, \"*_%s\" % ftype) )\n\t\t\t\tto_cat = [fn for fn in ftype_fns if not os.path.basename(fn).startswith(\"control_\")]\n\t\t\t\tto_cat.sort()\n\t\t\t\toutname = os.path.join(self.opts.tmp, \"control_%s\" % ftype )\n\t\t\t\tmbin.cat_list_of_files(to_cat, outname)\n\t\t\n\tdef chunk_control_matrices( self, control_ipds_fn, control_ipds_N_fn, control_kmers_fn ):\n\t\t\"\"\"\n\n\t\t\"\"\"\n\t\tkmers = np.atleast_1d(np.loadtxt(control_kmers_fn, dtype=\"str\"))\n\t\tfns = [control_ipds_fn, control_ipds_N_fn]\n\t\tn_chunks = 99\n\t\tchunksize = int(math.ceil(float( len(kmers)/n_chunks )))\n\t\tcols_chunks = list(chunks( range(len(kmers)), chunksize ))\n\t\targs = []\n\t\tfor i,cols_chunk in enumerate(cols_chunks):\n\t\t\tcut_CMDs = []\n\t\t\tfor fn in fns:\n\t\t\t\tcut_cols = \"%s-%s\" % ((cols_chunk[0]+1), (cols_chunk[-1]+1))\n\t\t\t\tin_fn = fn\n\t\t\t\tout_fn = fn+\".sub.%s\" % i\n\t\t\t\tcut_CMD = \"cut -d$\\'\\\\t\\' -f%s %s > %s\" % (cut_cols, in_fn, out_fn)\n\t\t\t\tcut_CMDs.append(cut_CMD)\n\t\t\targs.append( (i, cut_CMDs, kmers, cols_chunk, n_chunks, self.opts.min_motif_count) )\n\t\t\n\t\tresults = mbin.launch_pool(self.opts.procs, process_contig_chunk, args)\n\t\t\n\t\tlogging.info(\"Combining motifs from all chunks of control data...\")\n\t\tnot_found = 0\n\t\tcontrol_means = {}\n\t\tfor i,result in enumerate(results):\n\t\t\tnot_found += result[1]\n\t\t\tfor motif in result[0].keys():\n\t\t\t\tcontrol_means[motif] = result[0][motif]\n\t\tlogging.info(\"Done.\")\n\n\t\treturn control_means,not_found\n\n\tdef combine_control_data_from_contigs( self ):\n\t\t\"\"\"\n\t\tIf control WGA data contains multiple contigs, this \n\t\twill combine them into one file for each data type\n\t\tso that the control IPD dictionary will be generated\n\t\tusing data from all contigs.\n\t\t\"\"\"\n\t\tcontigs_fns = glob.glob( os.path.join(self.opts.tmp, \"control_*.tmp\") )\n\t\tlabels_fns = []\n\t\tstrands_fns = []\n\t\tlengths_fns = []\n\t\treadnames_fns = []\n\t\tipds_fns = []\n\t\tipds_N_fns = []\n\t\tcomp_N_fns = []\n\t\tcomp_kmers_fns = []\n\t\tipds_kmers_fns = []\n\t\tfor fn in contigs_fns:\n\t\t\tif fn.find(\"_labels.\")>-1:\n\t\t\t\tlabels_fns.append(fn)\n\t\t\telif fn.find(\"_strand.\")>-1:\n\t\t\t\tstrands_fns.append(fn)\n\t\t\telif fn.find(\"_lengths.\")>-1:\n\t\t\t\tlengths_fns.append(fn)\n\t\t\telif fn.find(\"_readnames.\")>-1:\n\t\t\t\treadnames_fns.append(fn)\n\t\t\telif fn.find(\"_ipds.\")>-1:\n\t\t\t\tipds_fns.append(fn)\n\t\t\telif fn.find(\"_ipdsN.\")>-1:\n\t\t\t\tipds_N_fns.append(fn)\n\t\t\telif fn.find(\"_compN.\")>-1:\n\t\t\t\tcomp_N_fns.append(fn)\n\t\t\telif fn.find(\"_compkmers.\")>-1:\n\t\t\t\tcomp_kmers_fns.append(fn)\n\t\t\telif fn.find(\"_ipdskmers.\")>-1:\n\t\t\t\tipds_kmers_fns.append(fn)\n\n\t\tlabels_fns.sort()\n\t\tstrands_fns.sort()\n\t\tlengths_fns.sort()\n\t\treadnames_fns.sort()\n\t\tipds_fns.sort()\n\t\tipds_N_fns.sort()\n\t\tcomp_N_fns.sort()\n\n\t\tmbin.cat_list_of_files(labels_fns, \"control_labels.tmp\")\n\t\tmbin.cat_list_of_files(strands_fns, \"control_strands.tmp\")\n\t\tmbin.cat_list_of_files(lengths_fns, \"control_lengths.tmp\")\n\t\tmbin.cat_list_of_files(readnames_fns, \"control_names.tmp\")\n\t\tmbin.cat_list_of_files(ipds_fns, \"control_ipds.tmp\")\n\t\tmbin.cat_list_of_files(ipds_N_fns, \"control_ipdsN.tmp\")\n\t\tmbin.cat_list_of_files(comp_N_fns, \"control_compN.tmp\")\n\t\t\n\t\tshutil.copy(comp_kmers_fns[0], \"control_compkmers.tmp\")\n\t\tshutil.copy(ipds_kmers_fns[0], \"control_ipdskmers.tmp\")\n\t\tx = [os.remove(fn) for fn in comp_kmers_fns]\n\t\tx = [os.remove(fn) for fn in ipds_kmers_fns]\n\n\tdef build_control_IPD_dict( self, motifs, bi_motifs ):\n\t\t\"\"\"\n\n\t\t\"\"\"\n\t\tcontrol_ipds_fn = glob.glob( \"control_ipds.tmp\" )\n\t\tcontrol_ipds_N_fn = glob.glob( \"control_ipdsN.tmp\")\n\t\tcontrol_kmers_fn = glob.glob( \"control_ipdskmers.tmp\")\n\n\t\tif (len(control_ipds_fn)>1 or len(control_ipds_N_fn)>1 or len(control_kmers_fn)>1):\n\t\t\traise Exception(\"*** Double check the control files. There should not be multiples for a file type.\")\n\n\t\tcontrol_means,not_found = self.chunk_control_matrices(control_ipds_fn[0], control_ipds_N_fn[0], control_kmers_fn[0])\n\n\t\tif not_found > 0:\n\t\t\tlogging.info(\"\")\n\t\t\tlogging.warning(\"WARNING: could not find sufficient instances (>=%s) for %s motifs (out of %s total) in control data!\" % (self.opts.min_motif_count, not_found, (len(motifs)+len(bi_motifs))))\n\t\t\tlogging.warning(\" * If this is alarming, try reducing --min_motif_count or increasing --N_reads, although you just might not have those motifs in your reference sequence.\")\n\t\t\n\t\tlogging.info(\"\")\n\t\tlogging.info(\"Writing control data to a pickled file: %s\" % self.opts.control_pkl_name)\n\t\tpickle.dump( control_means, open( self.opts.control_pkl_name, \"wb\" ) )\n\n\t\treturn control_means\n\nif __name__ == \"__main__\":\n\tmain()" ]
[ [ "numpy.sum", "numpy.dot", "numpy.atleast_2d", "numpy.loadtxt" ] ]
kishorecbe/Tensorflow-Solutions
[ "a158766633bc20ca4289096e4a5454a9e0d04e51" ]
[ "research/MCNN/model/mcnn_model.py" ]
[ "import multiprocessing\n\nimport tensorflow as tf\nfrom tensorflow.contrib import estimator\nfrom tensorflow.contrib import lookup\nfrom model import commons\n\n__author__ = 'KKishore'\n\nhead = estimator.binary_classification_head()\n\n\ndef parse_csv_row(row):\n columns = tf.decode_csv(row, record_defaults=commons.HEADER_DEFAULTS, field_delim='\\t')\n features = dict(zip(commons.HEADERS, columns))\n target = features.pop(commons.LABEL_COL)\n return features, tf.string_to_number(target, out_type=tf.int32)\n\n\ndef input_fn(file_name, batch_size=32, shuffle=False, repeat_count=1):\n num_threads = multiprocessing.cpu_count()\n\n data_set = tf.data.TextLineDataset(filenames=file_name).skip(1)\n\n if shuffle:\n data_set = data_set.shuffle(buffer_size=1000)\n\n data_set = data_set.map(lambda row: parse_csv_row(row), num_parallel_calls=num_threads).batch(batch_size) \\\n .repeat(repeat_count).prefetch(1000)\n\n iterator = data_set.make_one_shot_iterator()\n features, target = iterator.get_next()\n return features, target\n\n\ndef model_fn(features, labels, mode, params):\n if mode == tf.estimator.ModeKeys.TRAIN:\n tf.keras.backend.set_learning_phase(True)\n else:\n tf.keras.backend.set_learning_phase(False)\n\n vocab_table = lookup.index_table_from_file(vocabulary_file='data/vocab.csv', num_oov_buckets=1, default_value=-1)\n text = features[commons.FEATURE_COL]\n words = tf.string_split(text)\n dense_words = tf.sparse_tensor_to_dense(words, default_value=commons.PAD_WORD)\n word_ids = vocab_table.lookup(dense_words)\n\n padding = tf.constant([[0, 0], [0, commons.MAX_DOCUMENT_LENGTH]])\n # Pad all the word_ids entries to the maximum document length\n word_ids_padded = tf.pad(word_ids, padding)\n word_id_vector = tf.slice(word_ids_padded, [0, 0], [-1, commons.MAX_DOCUMENT_LENGTH])\n\n f1 = tf.keras.layers.Embedding(params.N_WORDS, 100, input_length=commons.MAX_DOCUMENT_LENGTH)(word_id_vector)\n f2 = tf.keras.layers.Embedding(params.N_WORDS, 200, input_length=commons.MAX_DOCUMENT_LENGTH)(word_id_vector)\n f3 = tf.keras.layers.Embedding(params.N_WORDS, 300, input_length=commons.MAX_DOCUMENT_LENGTH)(word_id_vector)\n\n filter_sizes = [3, 5]\n\n conv_pools = []\n for text_embedding in [f1, f2, f3]:\n for filter_size in filter_sizes:\n l_zero = tf.keras.layers.ZeroPadding1D((filter_size - 1, filter_size - 1))(text_embedding)\n l_conv = tf.keras.layers.Conv1D(filters=32, kernel_size=filter_size, padding='same', activation='tanh')(l_zero)\n l_pool = tf.keras.layers.GlobalMaxPool1D()(l_conv)\n conv_pools.append(l_pool)\n merged = tf.keras.layers.Concatenate(axis=1)(conv_pools)\n dense1 = tf.keras.layers.Dense(128, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01))(merged)\n dense2 = tf.keras.layers.Dense(64, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01))(dense1)\n\n logits = tf.keras.layers.Dense(1, activation=None)(dense2)\n\n if labels is not None:\n labels = tf.reshape(labels, [-1, 1])\n\n optimizer = tf.train.AdamOptimizer()\n\n def _train_op_fn(loss):\n return optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())\n\n return head.create_estimator_spec(features=features, labels=labels, mode=mode, logits=logits,\n train_op_fn=_train_op_fn)\n\n\ndef serving_fn():\n receiver_tensor = {\n commons.FEATURE_COL: tf.placeholder(dtype=tf.string, shape=None)\n }\n\n features = {\n key: tensor\n for key, tensor in receiver_tensor.items()\n }\n\n return tf.estimator.export.ServingInputReceiver(features, receiver_tensor)\n" ]
[ [ "tensorflow.data.TextLineDataset", "tensorflow.sparse_tensor_to_dense", "tensorflow.keras.layers.Concatenate", "tensorflow.reshape", "tensorflow.keras.layers.GlobalMaxPool1D", "tensorflow.slice", "tensorflow.train.get_global_step", "tensorflow.estimator.export.ServingInputReceiver", "tensorflow.keras.layers.Embedding", "tensorflow.string_to_number", "tensorflow.keras.layers.Conv1D", "tensorflow.keras.layers.ZeroPadding1D", "tensorflow.keras.layers.Dense", "tensorflow.constant", "tensorflow.string_split", "tensorflow.keras.regularizers.l2", "tensorflow.contrib.lookup.index_table_from_file", "tensorflow.pad", "tensorflow.placeholder", "tensorflow.contrib.estimator.binary_classification_head", "tensorflow.train.AdamOptimizer", "tensorflow.keras.backend.set_learning_phase", "tensorflow.decode_csv" ] ]
serig/Jupyter-notebook-with-Flask
[ "f6cc37517e10fcd5de5229fe5264192c578faf5f" ]
[ "app.py" ]
[ "from flask import Flask, render_template\r\n# import os\r\n\r\napp = Flask(__name__)\r\n\r\n\r\[email protected]('/plot/')\r\ndef plot():\r\n from IPython.core.display import display, HTML\r\n from string import Template\r\n import pandas as pd\r\n import json\r\n\r\n # d3js = HTML('<script src=\"d3_jupyter/lib/d3/d3.min.js\"></script>')\r\n\r\n worldmap_data = json.loads(open('data/worldmap.json', 'r').read())\r\n sites_data_stations = pd.read_csv('data/stations.csv')\r\n sites_data_temps = pd.read_csv('data/monthly_temps.csv')\r\n sites_data_temps = sites_data_temps.sort_values(by='ID')\r\n\r\n temps_by_ID = []\r\n previous_ID = -1\r\n collected_temps = {}\r\n for i,row in sites_data_temps.iterrows():\r\n if (row['ID'] != previous_ID) and (previous_ID != -1):\r\n temps_by_ID.append(collected_temps)\r\n collected_temps = {}\r\n collected_temps[row['month']] = {'ave': row['ave'], \r\n 'max': row['max'], \r\n 'min': row['min']}\r\n previous_ID = row['ID']\r\n temps_by_ID.append(collected_temps)\r\n site_data_temps_2 = pd.DataFrame({'ID': sites_data_temps['ID'].unique(), \r\n 'temps': temps_by_ID})\r\n # site_data_temps_2.head()\r\n \r\n sites_data = pd.merge(sites_data_stations, site_data_temps_2, on='ID')\r\n sites_data_dict = sites_data.to_dict(orient='records')\r\n\r\n # html_template = Template('''\r\n # <style> $css_text </style>\r\n # <div><svg width=\"700\" height=\"500px\" id=\"graph-svg\"></svg></div>\r\n # <script> $js_text </script>\r\n # ''')\r\n\r\n css_text = open('static/temperature_histories.css','r').read()\r\n js_text_template = Template(open('static/temperature_histories.js','r').read())\r\n js_text = js_text_template.safe_substitute({'worldmapdata': json.dumps(worldmap_data), \r\n 'sitesdata': json.dumps(sites_data_dict) })\r\n # display(HTML(html_template.substitute({'css_text': css_text, 'js_text': js_text})))\r\n return render_template(\"plot.html\", \r\n css_text=css_text,\r\n js_text=js_text)\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n" ]
[ [ "pandas.read_csv", "pandas.merge" ] ]
dblyon/cmapPy
[ "abd4349f28af6d035f69fe8c399fde7bef8dd635" ]
[ "cmapPy/pandasGEXpress/tests/python2_tests/test_parse_gctx.py" ]
[ "import logging\nimport unittest\nimport os\nimport pandas as pd\nimport numpy as np\nimport h5py\n\nimport pandas.util.testing as pandas_testing\nimport cmapPy.pandasGEXpress.setup_GCToo_logger as setup_logger\nimport cmapPy.pandasGEXpress.GCToo as GCToo\nimport cmapPy.pandasGEXpress.parse_gctx as parse_gctx\nimport cmapPy.pandasGEXpress.mini_gctoo_for_testing as mini_gctoo_for_testing\nimport cmapPy.pandasGEXpress.subset_gctoo as subset_gctoo\nimport cmapPy.pandasGEXpress.write_gctx as write_gctx\n\n\n__author__ = \"Oana Enache\"\n__email__ = \"[email protected]\"\n\nFUNCTIONAL_TESTS_PATH = \"cmapPy/pandasGEXpress/tests/functional_tests/\"\n\nlogger = logging.getLogger(setup_logger.LOGGER_NAME)\n\nversion_node = \"version\"\nrid_node = \"/0/META/ROW/id\"\ncid_node = \"/0/META/COL/id\"\ndata_node = \"/0/DATA/0/matrix\"\nrow_meta_group_node = \"/0/META/ROW\"\ncol_meta_group_node = \"/0/META/COL\"\n\n\nclass MockHdf5Dset(object):\n def __init__(self, data_list, dtype):\n self.data_list = data_list\n self.shape = (len(data_list),)\n self.dtype = dtype\n\n def read_direct(self, dest):\n for i in range(len(dest)):\n dest[i] = self.data_list[i]\n\n\nclass TestParseGctx(unittest.TestCase):\n def test_parse(self):\n # parse whole thing\n mg1 = mini_gctoo_for_testing.make()\n mg2 = parse_gctx.parse(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctoo_for_testing.gctx\")\n\n pandas_testing.assert_frame_equal(mg1.data_df, mg2.data_df)\n pandas_testing.assert_frame_equal(mg1.row_metadata_df, mg2.row_metadata_df)\n pandas_testing.assert_frame_equal(mg1.col_metadata_df, mg2.col_metadata_df)\n\n # test with string rid/cid\n test_rids = ['LJP007_MCF10A_24H:TRT_CP:BRD-K93918653:3.33', 'LJP007_MCF7_24H:CTL_VEHICLE:DMSO:-666']\n test_cids = ['LJP007_MCF7_24H:TRT_POSCON:BRD-A61304759:10']\n mg3 = subset_gctoo.subset_gctoo(mg1, rid=test_rids, cid=test_cids)\n mg4 = parse_gctx.parse(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctoo_for_testing.gctx\",\n rid=test_rids, cid=test_cids)\n pandas_testing.assert_frame_equal(mg3.data_df, mg4.data_df)\n pandas_testing.assert_frame_equal(mg3.row_metadata_df, mg4.row_metadata_df)\n pandas_testing.assert_frame_equal(mg3.col_metadata_df, mg4.col_metadata_df)\n\n # first, make & write out temp version of mini_gctoo with int rids/cids\n new_mg = mini_gctoo_for_testing.make(convert_neg_666=False)\n int_indexed_data_df = new_mg.data_df.copy()\n int_indexed_data_df.index = [str(i) for i in range(0, 6)]\n int_indexed_data_df.columns = [str(i) for i in range(10, 16)]\n\n int_indexed_row_meta = new_mg.row_metadata_df.copy()\n int_indexed_row_meta.index = int_indexed_data_df.index\n\n int_indexed_col_meta = new_mg.col_metadata_df.copy()\n int_indexed_col_meta.index = int_indexed_data_df.columns\n\n int_indexed_gctoo = GCToo.GCToo(data_df=int_indexed_data_df, row_metadata_df=int_indexed_row_meta,\n col_metadata_df=int_indexed_col_meta)\n\n write_gctx.write(int_indexed_gctoo, \"int_indexed_mini_gctoo.gctx\")\n\n # test with numeric (repr as string) rid/cid\n mg5 = GCToo.GCToo(data_df=int_indexed_data_df, row_metadata_df=int_indexed_row_meta,\n col_metadata_df=int_indexed_col_meta)\n mg5 = subset_gctoo.subset_gctoo(mg5, row_bool=[True, False, True, False, True, False],\n col_bool=[True, False, False, True, True, True])\n\n mg5.data_df.index.name = \"rid\"\n mg5.data_df.columns.name = \"cid\"\n\n mg5.row_metadata_df.index.name = \"rid\"\n mg5.row_metadata_df.columns.name = \"rhd\"\n\n mg5.col_metadata_df.index.name = \"cid\"\n mg5.col_metadata_df.columns.name = \"chd\"\n\n mg6 = parse_gctx.parse(\"int_indexed_mini_gctoo.gctx\", rid=[\"0\", \"2\", \"4\"],\n cid=[\"10\", \"13\", \"14\", \"15\"], convert_neg_666=False)\n\n os.remove(\"int_indexed_mini_gctoo.gctx\")\n\n pandas_testing.assert_frame_equal(mg5.data_df, mg6.data_df)\n pandas_testing.assert_frame_equal(mg5.row_metadata_df, mg6.row_metadata_df)\n pandas_testing.assert_frame_equal(mg5.col_metadata_df, mg6.col_metadata_df)\n\n # test with ridx/cidx\n mg7 = subset_gctoo.subset_gctoo(mg1, rid=['LJP007_MCF7_24H:CTL_VEHICLE:DMSO:-666'],\n cid=['LJP007_MCF7_24H:CTL_VEHICLE:DMSO:-666'])\n mg8 = parse_gctx.parse(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctoo_for_testing.gctx\", ridx=[4], cidx=[4])\n\n pandas_testing.assert_frame_equal(mg7.data_df, mg8.data_df)\n pandas_testing.assert_frame_equal(mg7.row_metadata_df, mg8.row_metadata_df)\n pandas_testing.assert_frame_equal(mg7.col_metadata_df, mg8.col_metadata_df)\n\n # test with rid/cidx\n mg9 = parse_gctx.parse(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctoo_for_testing.gctx\",\n rid=['LJP007_MCF7_24H:CTL_VEHICLE:DMSO:-666'],\n cidx=[4])\n\n pandas_testing.assert_frame_equal(mg7.data_df, mg9.data_df)\n pandas_testing.assert_frame_equal(mg7.row_metadata_df, mg9.row_metadata_df)\n pandas_testing.assert_frame_equal(mg7.col_metadata_df, mg9.col_metadata_df)\n\n # test with ridx/cid\n mg10 = parse_gctx.parse(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctoo_for_testing.gctx\", ridx=[4],\n cid=['LJP007_MCF7_24H:CTL_VEHICLE:DMSO:-666'])\n\n pandas_testing.assert_frame_equal(mg7.data_df, mg10.data_df)\n pandas_testing.assert_frame_equal(mg7.row_metadata_df, mg10.row_metadata_df)\n pandas_testing.assert_frame_equal(mg7.col_metadata_df, mg10.col_metadata_df)\n\n # test with row_meta_only\n mg11 = parse_gctx.parse(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctoo_for_testing.gctx\", row_meta_only=True)\n pandas_testing.assert_frame_equal(mg11, mg1.row_metadata_df)\n\n # test with col_meta_only\n mg12 = parse_gctx.parse(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctoo_for_testing.gctx\", col_meta_only=True)\n pandas_testing.assert_frame_equal(mg12, mg1.col_metadata_df)\n\n # test with sort_col_meta False and cidx\n mg13 = parse_gctx.parse(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctoo_for_testing.gctx\", \n cidx = [4,1,3], sort_col_meta= False)\n\n pandas_testing.assert_frame_equal(mg13.data_df, mg1.data_df.iloc[:, [4,1,3]])\n pandas_testing.assert_frame_equal(mg13.col_metadata_df, mg1.col_metadata_df.iloc[[4,1,3],:])\n pandas_testing.assert_frame_equal(mg13.row_metadata_df, mg1.row_metadata_df)\n\n\n # test with sort_row_meta False and ridx\n mg14 = parse_gctx.parse(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctoo_for_testing.gctx\", \n ridx = [3,0,1], sort_row_meta= False)\n\n pandas_testing.assert_frame_equal(mg14.data_df, mg1.data_df.iloc[[3,0,1],:])\n pandas_testing.assert_frame_equal(mg14.col_metadata_df, mg1.col_metadata_df)\n pandas_testing.assert_frame_equal(mg14.row_metadata_df, mg1.row_metadata_df.iloc[[3,0,1],:])\n\n # test with sort_col_meta False and cidx and col_meta_only\n mg15 = parse_gctx.parse(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctoo_for_testing.gctx\", \n cidx = [4,1,3], sort_col_meta= False, col_meta_only=True)\n pandas_testing.assert_frame_equal(mg15, mg1.col_metadata_df.iloc[[4,1,3],:])\n\n # test with sort_row_meta False and ridx and row_meta_only\n mg16 = parse_gctx.parse(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctoo_for_testing.gctx\", \n ridx = [3,0,1], sort_row_meta= False, row_meta_only=True)\n pandas_testing.assert_frame_equal(mg16, mg1.row_metadata_df.iloc[[3,0,1],:])\n\n # test with sort_col_meta False and cid \n cid_unsorted = ['LJP007_MCF7_24H:TRT_POSCON:BRD-K81418486:10','LJP007_MCF10A_24H:TRT_CP:BRD-K93918653:3.33']\n mg17 = parse_gctx.parse(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctoo_for_testing.gctx\", \n cid = cid_unsorted, sort_col_meta= False)\n pandas_testing.assert_frame_equal(mg17.data_df, mg1.data_df.iloc[:, [2,0]])\n pandas_testing.assert_frame_equal(mg17.col_metadata_df, mg1.col_metadata_df.iloc[[2,0],:])\n pandas_testing.assert_frame_equal(mg17.row_metadata_df, mg1.row_metadata_df)\n\n # test with sort_row_meta False and rid\n rid_unsorted = ['LJP007_MCF7_24H:TRT_CP:BRD-K64857848:10', 'MISC003_A375_24H:TRT_CP:BRD-K93918653:3.33']\n mg18 = parse_gctx.parse(\"cmapPy/pandasGEXpress/tests/functional_tests/mini_gctoo_for_testing.gctx\",\n rid = rid_unsorted, sort_row_meta=False)\n pandas_testing.assert_frame_equal(mg18.data_df, mg1.data_df.iloc[[5,1], :])\n pandas_testing.assert_frame_equal(mg18.col_metadata_df, mg1.col_metadata_df)\n pandas_testing.assert_frame_equal(mg18.row_metadata_df, mg1.row_metadata_df.iloc[[5,1],:])\n\n def test_parse_rid_as_entrez_id(self):\n input_file = \"cmapPy/pandasGEXpress/tests/functional_tests//test_parse_gctx_rid_entrez_id.gctx\"\n g = parse_gctx.parse(input_file)\n self.assertEqual((5, 5), g.data_df.shape)\n logger.debug(\"g.data_df.index: {}\".format(g.data_df.index))\n\n my_rids = [\"5720\", \"55847\", \"7416\"]\n g = parse_gctx.parse(input_file, rid=my_rids)\n self.assertEqual((3, 5), g.data_df.shape)\n logger.debug(\"g.data_df.index: {}\".format(g.data_df.index))\n\n my_rids = [str(x) for x in my_rids]\n logger.debug(\"using rid as str (mismatched type) - my_rids: {}\".format(my_rids))\n g = parse_gctx.parse(input_file, rid=my_rids)\n self.assertEqual((3, 5), g.data_df.shape)\n logger.debug(\"g.data_df.index: {}\".format(g.data_df.index))\n\n def test_check_and_order_id_inputs(self):\n ridx = [0, 1]\n cidx = [2, 1]\n rid = [\"a\", \"b\", \"c\"]\n cid = [\"l\", \"m\", \"n\", \"o\"]\n row_meta = pd.DataFrame(index=[\"b\", \"c\", \"a\", \"d\"])\n col_meta = pd.DataFrame(index=[\"l\", \"m\", \"n\", \"o\", \"p\", \"q\"])\n\n # case 1: row and col lists are populated and same type\n self.assertEqual((sorted(ridx), sorted(cidx)),\n parse_gctx.check_and_order_id_inputs(None, ridx, None, cidx, row_meta, col_meta, sort_row_meta = True, sort_col_meta = True))\n\n # case 2: row & col lists are populated, but of different types\n self.assertEqual((sorted(ridx), [0, 1, 2, 3]),\n parse_gctx.check_and_order_id_inputs(None, ridx, cid, None, row_meta, col_meta, sort_row_meta = True, sort_col_meta = True))\n\n # case 3: row list and col lists are both None\n self.assertEqual(([0, 1, 2, 3], [0, 1, 2, 3, 4, 5]),\n parse_gctx.check_and_order_id_inputs(None, None, None, None, row_meta, col_meta, sort_row_meta = True, sort_col_meta = True))\n\n # case 4: row list is populated, col list is None\n self.assertEqual(([0, 1, 2], [0, 1, 2, 3, 4, 5]),\n parse_gctx.check_and_order_id_inputs(rid, None, None, None, row_meta, col_meta, sort_row_meta = True, sort_col_meta = True))\n\n def test_check_id_idx_exclusivity(self):\n ids = [\"a\", \"b\", \"c\"]\n idx = [0, 1, 2]\n\n # case 1: id != None and idx != None\n with self.assertRaises(Exception) as context:\n parse_gctx.check_id_idx_exclusivity(ids, idx)\n self.assertTrue(\"'id' and 'idx' fields can't both not be None\" in str(context.exception))\n\n # case 2: id != None\n self.assertEqual((\"id\", ids), parse_gctx.check_id_idx_exclusivity(ids, None))\n\n # case 3: idx != None\n self.assertEqual((\"idx\", idx), parse_gctx.check_id_idx_exclusivity(None, idx))\n\n # case 4: id == None & idx == None\n self.assertEqual((None, []), parse_gctx.check_id_idx_exclusivity(None, None))\n\n def test_parse_metadata_df(self):\n mini_gctoo = mini_gctoo_for_testing.make()\n # convert row_metadata to np.nan\n mini_row_meta = mini_gctoo.row_metadata_df.replace([-666, \"-666\", -666.0], [np.nan, np.nan, np.nan])\n logger.debug(\"mini_row_meta.shape: {}\".format(mini_row_meta.shape))\n logger.debug(\"mini_row_meta.index: {}\".format(mini_row_meta.index))\n logger.debug(\"mini_row_meta.columns: {}\".format(mini_row_meta.columns))\n logger.debug(\"mini_row_meta.dtypes: {}\".format(mini_row_meta.dtypes))\n\n gctx_file = h5py.File(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctoo_for_testing.gctx\", \"r\")\n row_dset = gctx_file[row_meta_group_node]\n col_dset = gctx_file[col_meta_group_node]\n\n # with convert_neg_666\n row_df = parse_gctx.parse_metadata_df(\"row\", row_dset, True)\n logger.debug(\"row_df.dtypes: {}\".format(row_df.dtypes))\n pandas_testing.assert_frame_equal(mini_row_meta, row_df)\n\n # no convert_neg_666\n mini_gctoo_with_neg_666 = mini_gctoo_for_testing.make(convert_neg_666=False)\n col_df = parse_gctx.parse_metadata_df(\"col\", col_dset, False)\n pandas_testing.assert_frame_equal(mini_gctoo_with_neg_666.col_metadata_df, col_df)\n\n # test that ID's are not converted to numeric\n expected_rids = [str(i) for i in range(3)]\n row_dset = {\"id\": MockHdf5Dset(expected_rids, str),\n \"other_meta\": MockHdf5Dset(range(3, 6), str)}\n r = parse_gctx.parse_metadata_df(\"row\", row_dset, True)\n logger.debug(\"test that ID's are not converted to numeric - r: {}\".format(r))\n logger.debug(\"r.index: {}\".format(r.index))\n self.assertEqual(set(expected_rids), set(r.index))\n\n def test_replace_666(self):\n # convert_neg_666 is True\n row_df = pd.DataFrame([[3, \"a\"], [-666, \"c\"], [\"-666\", -666.0]],\n index=[\"r1\", \"r2\", \"r3\"], columns=[\"rhd1\", \"rhd2\"])\n e_df = pd.DataFrame([[3, \"a\"], [np.nan, \"c\"], [np.nan, np.nan]],\n index=[\"r1\", \"r2\", \"r3\"], columns=[\"rhd1\", \"rhd2\"])\n out_df = parse_gctx.replace_666(row_df, convert_neg_666=True)\n self.assertTrue(e_df.equals(out_df))\n\n # convert_neg_666 is False\n e_df2 = pd.DataFrame([[3, \"a\"], [\"-666\", \"c\"], [\"-666\", \"-666\"]],\n index=[\"r1\", \"r2\", \"r3\"], columns=[\"rhd1\", \"rhd2\"])\n out_df2 = parse_gctx.replace_666(row_df, convert_neg_666=False)\n self.assertTrue(e_df2.equals(out_df2))\n\n # edge case: if row meta is 1 column of floats\n row_df3 = pd.DataFrame([[3], [-666], [-666.0]],\n index=[\"r1\", \"r2\", \"r3\"], columns=[\"rhd3\"])\n e_df3 = pd.DataFrame([[3], [np.nan], [np.nan]],\n index=[\"r1\", \"r2\", \"r3\"], columns=[\"rhd3\"])\n out_df3 = parse_gctx.replace_666(row_df3, convert_neg_666=True)\n self.assertTrue(e_df3.equals(out_df3))\n\n def test_set_metadata_index_and_column_names(self):\n mini_gctoo = mini_gctoo_for_testing.make()\n mini_gctoo.row_metadata_df.index.name = None\n mini_gctoo.row_metadata_df.columns.name = None\n mini_gctoo.col_metadata_df.index.name = None\n mini_gctoo.col_metadata_df.columns.name = None\n\n # case 1: dim == \"row\"\n parse_gctx.set_metadata_index_and_column_names(\"row\", mini_gctoo.row_metadata_df)\n self.assertEqual(mini_gctoo.row_metadata_df.index.name, \"rid\")\n self.assertEqual(mini_gctoo.row_metadata_df.columns.name, \"rhd\")\n\n # case 2: dim == \"col\"\n parse_gctx.set_metadata_index_and_column_names(\"col\", mini_gctoo.col_metadata_df)\n self.assertEqual(mini_gctoo.col_metadata_df.index.name, \"cid\")\n self.assertEqual(mini_gctoo.col_metadata_df.columns.name, \"chd\")\n\n def test_get_ordered_idx(self):\n mg = mini_gctoo_for_testing.make()\n\n # case 1: id_type == None\n case1 = parse_gctx.get_ordered_idx(None, [], mg.row_metadata_df, sort_idx = True)\n self.assertEqual(case1, list(range(0, 6)),\n \"Expected ordered idx to be {} but got {}\".format(list(range(0, 6)), case1))\n\n # case 2: id_type == \"id\"\n case2 = parse_gctx.get_ordered_idx(\"id\",\n ['LJP007_MCF7_24H:CTL_VEHICLE:DMSO:-666'], mg.col_metadata_df, sort_idx = True)\n self.assertEqual(case2, [4],\n \"Expected ordered idx to be {} but got {}\".format([4], case2))\n\n # case 3: id_type == ridx\n case3 = parse_gctx.get_ordered_idx(\"idx\",\n [5, 1, 3], mg.col_metadata_df, sort_idx = True)\n self.assertEqual(case3, [1, 3, 5],\n \"Expected ordered idx to be {} but got {}\".format([1, 3, 5], case3))\n\n def test_parse_data_df(self):\n mini_data_df = pd.DataFrame([[-0.283359, 0.011270], [0.304119, 1.921061], [0.398655, -0.144652]],\n index=[\"200814_at\", \"218597_s_at\", \"217140_s_at\"],\n columns=[\"LJP005_A375_24H:DMSO:-666\", \"LJP005_A375_24H:BRD-K76908866:10\"])\n mini_data_df = mini_data_df.astype(np.float32)\n mini_data_df.index.name = \"rid\"\n mini_data_df.columns.name = \"cid\"\n\n # create h5py File instance\n mini_gctx = h5py.File(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctx_with_metadata_n2x3.gctx\", \"r\")\n data_dset = mini_gctx[data_node]\n\n # get relevant metadata fields\n col_meta = parse_gctx.get_column_metadata(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctx_with_metadata_n2x3.gctx\")\n row_meta = parse_gctx.get_row_metadata(\"cmapPy/pandasGEXpress/tests/functional_tests//mini_gctx_with_metadata_n2x3.gctx\")\n\n # case 1: no subsetting\n data_df1 = parse_gctx.parse_data_df(data_dset, [0, 1, 2], [0, 1], row_meta, col_meta)\n # note: checks to 3 decimal places\n pandas_testing.assert_frame_equal(mini_data_df, data_df1,\n check_exact=False, check_less_precise=True)\n\n # case 2: subset; ridx < cidx\n data_df2 = parse_gctx.parse_data_df(data_dset, [0], [0, 1], row_meta, col_meta)\n pandas_testing.assert_frame_equal(mini_data_df.iloc[[0], [0, 1]], data_df2,\n check_exact=False, check_less_precise=True)\n\n # case 3: subset; ridx == cidx\n data_df3 = parse_gctx.parse_data_df(data_dset, [0], [0], row_meta, col_meta)\n pandas_testing.assert_frame_equal(mini_data_df.iloc[[0], [0]], data_df3,\n check_exact=False, check_less_precise=True)\n\n # case 4: subset; ridx > cidx\n data_df4 = parse_gctx.parse_data_df(data_dset, [0, 1, 2], [0], row_meta, col_meta)\n pandas_testing.assert_frame_equal(mini_data_df.iloc[[0, 1, 2], [0]], data_df4,\n check_exact=False, check_less_precise=True)\n\n mini_gctx.close()\n\n def test_convert_ids_to_meta_type(self):\n # happy path\n id_list = [0, 1, 2]\n self.assertEqual(int, type(id_list[0]))\n df = pd.DataFrame({}, index=pd.Series(range(1, 4)).astype(np.int64))\n r = parse_gctx.convert_ids_to_meta_type(id_list, df)\n logger.debug(\"conversion from regular int to numpy int64 - type(r[0]): {}\".format(type(r[0])))\n self.assertEqual(np.int64, type(r[0]))\n\n id_list = [str(i) for i in range(3)]\n r = parse_gctx.convert_ids_to_meta_type(id_list, df)\n logger.debug(\"conversion from str to numpy int64 - type(r[0]): {}\".format(type(r[0])))\n self.assertEqual(np.int64, type(r[0]))\n\n # unhappy path\n id_list[0] = \"a\"\n with self.assertRaises(Exception) as context:\n parse_gctx.convert_ids_to_meta_type(id_list, df)\n logger.debug(\"context.exception: {}\".format(context.exception))\n self.assertIn(\n \"The type of the id_list (rid or cid) being used to subset the data is not compatible with the metadata id's in the file\",\n str(context.exception))\n\n def test_check_idx_validity(self):\n id_list = [0,1,2]\n df = pd.DataFrame({}, index=range(5))\n logger.debug(\"df.shape: {}\".format(df.shape))\n parse_gctx.check_idx_validity(id_list, df, sort_id = True)\n\n id_list[0] = -1\n with self.assertRaises(Exception) as context:\n parse_gctx.check_idx_validity(id_list, df, sort_id = True)\n logger.debug(\"context.exception: {}\".format(context.exception))\n self.assertIn(\"some of indexes being used to subset the data are not valid\", str(context.exception))\n self.assertIn(\"[-1]\", str(context.exception))\n\n invalid_high = df.shape[0] + 1\n id_list[0] = invalid_high\n with self.assertRaises(Exception) as context:\n parse_gctx.check_idx_validity(id_list, df, sort_id = True)\n logger.debug(\"context.exception: {}\".format(context.exception))\n self.assertIn(\"some of indexes being used to subset the data are not valid\", str(context.exception))\n self.assertIn(\"[{}]\".format(invalid_high), str(context.exception))\n\n def test_check_id_validity(self):\n id_list = [\"a\", \"b\", \"c\"]\n df = pd.DataFrame({}, index=[\"a\", \"b\", \"c\", \"d\"])\n parse_gctx.check_id_validity(id_list, df)\n\n id_list[0] = \"z\"\n with self.assertRaises(Exception) as context:\n parse_gctx.check_id_validity(id_list, df)\n logger.debug(\"context.exception: {}\".format(context.exception))\n self.assertIn(\n \"some of the ids being used to subset the data are not present in the metadata for the file being parsed\",\n str(context.exception))\n\n\nif __name__ == \"__main__\":\n setup_logger.setup(verbose=True)\n\n unittest.main()\n" ]
[ [ "pandas.util.testing.assert_frame_equal", "pandas.DataFrame" ] ]
eifuentes/swae-pytorch
[ "763f771c1d4860f71819af48d4f21a8a29a689d5" ]
[ "examples/mnist.py" ]
[ "import argparse\nimport os\n\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.optim as optim\nimport torchvision.utils as vutils\nfrom swae.distributions import rand_cirlce2d, rand_ring2d, rand_uniform2d\nfrom swae.models.mnist import MNISTAutoencoder\nfrom swae.trainer import SWAEBatchTrainer\nfrom torchvision import datasets, transforms\n\n\ndef main():\n # train args\n parser = argparse.ArgumentParser(description='Sliced Wasserstein Autoencoder PyTorch MNIST Example')\n parser.add_argument('--datadir', default='/input/', help='path to dataset')\n parser.add_argument('--outdir', default='/output/', help='directory to output images and model checkpoints')\n parser.add_argument('--batch-size', type=int, default=500, metavar='N',\n help='input batch size for training (default: 500)')\n parser.add_argument('--epochs', type=int, default=30, metavar='N',\n help='number of epochs to train (default: 30)')\n parser.add_argument('--lr', type=float, default=0.001, metavar='LR',\n help='learning rate (default: 0.001)')\n parser.add_argument('--alpha', type=float, default=0.9, metavar='A',\n help='RMSprop alpha/rho (default: 0.9)')\n parser.add_argument('--distribution', type=str, default='circle', metavar='DIST',\n help='Latent Distribution (default: circle)')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n parser.add_argument('--num-workers', type=int, default=8, metavar='N',\n help='number of dataloader workers if device is CPU (default: 8)')\n parser.add_argument('--seed', type=int, default=7, metavar='S',\n help='random seed (default: 7)')\n parser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='number of batches to log training status (default: 10)')\n args = parser.parse_args()\n # create output directory\n imagesdir = os.path.join(args.outdir, 'images')\n chkptdir = os.path.join(args.outdir, 'models')\n os.makedirs(args.datadir, exist_ok=True)\n os.makedirs(imagesdir, exist_ok=True)\n os.makedirs(chkptdir, exist_ok=True)\n # determine device and device dep. args\n use_cuda = not args.no_cuda and torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n dataloader_kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {'num_workers': args.num_workers, 'pin_memory': False}\n # set random seed\n torch.manual_seed(args.seed)\n if use_cuda:\n torch.cuda.manual_seed(args.seed)\n # log args\n print('batch size {}\\nepochs {}\\nRMSprop lr {} alpha {}\\ndistribution {}\\nusing device {}\\nseed set to {}'.format(\n args.batch_size, args.epochs, args.lr, args.alpha, args.distribution, device.type, args.seed\n ))\n # build train and test set data loaders\n train_loader = torch.utils.data.DataLoader(\n datasets.MNIST(args.datadir, train=True, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=args.batch_size, shuffle=True, **dataloader_kwargs)\n test_loader = torch.utils.data.DataLoader(\n datasets.MNIST(args.datadir, train=False, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=64, shuffle=False, **dataloader_kwargs)\n # create encoder and decoder\n model = MNISTAutoencoder().to(device)\n print(model)\n # create optimizer\n # matching default Keras args for RMSprop\n optimizer = optim.RMSprop(model.parameters(), lr=args.lr, alpha=args.alpha)\n # determine latent distribution\n if args.distribution == 'circle':\n distribution_fn = rand_cirlce2d\n elif args.distribution == 'ring':\n distribution_fn = rand_ring2d\n else:\n distribution_fn = rand_uniform2d\n # create batch sliced_wasserstein autoencoder trainer\n trainer = SWAEBatchTrainer(model, optimizer, distribution_fn, device=device)\n # put networks in training mode\n model.train()\n # train networks for n epochs\n print('training...')\n for epoch in range(args.epochs):\n if epoch > 10:\n trainer.weight *= 1.1\n # train autoencoder on train dataset\n for batch_idx, (x, y) in enumerate(train_loader, start=0):\n batch = trainer.train_on_batch(x)\n if (batch_idx + 1) % args.log_interval == 0:\n print('Train Epoch: {} ({:.2f}%) [{}/{}]\\tLoss: {:.6f}'.format(\n epoch + 1, float(epoch + 1) / (args.epochs) * 100.,\n (batch_idx + 1), len(train_loader),\n batch['loss'].item()))\n # evaluate autoencoder on test dataset\n test_encode, test_targets, test_loss = list(), list(), 0.0\n with torch.no_grad():\n for test_batch_idx, (x_test, y_test) in enumerate(test_loader, start=0):\n test_evals = trainer.test_on_batch(x_test)\n test_encode.append(test_evals['encode'].detach())\n test_loss += test_evals['loss'].item()\n test_targets.append(y_test)\n test_encode, test_targets = torch.cat(test_encode).cpu().numpy(), torch.cat(test_targets).cpu().numpy()\n test_loss /= len(test_loader)\n print('Test Epoch: {} ({:.2f}%)\\tLoss: {:.6f}'.format(\n epoch + 1, float(epoch + 1) / (args.epochs) * 100.,\n test_loss))\n print('{{\"metric\": \"loss\", \"value\": {}}}'.format(test_loss))\n # save model\n torch.save(model.state_dict(), '{}/mnist_epoch_{}.pth'.format(chkptdir, epoch + 1))\n # save encoded samples plot\n plt.figure(figsize=(10, 10))\n plt.scatter(test_encode[:, 0], -test_encode[:, 1], c=(10 * test_targets), cmap=plt.cm.Spectral)\n plt.xlim([-1.5, 1.5])\n plt.ylim([-1.5, 1.5])\n plt.title('Test Latent Space\\nLoss: {:.5f}'.format(test_loss))\n plt.savefig('{}/test_latent_epoch_{}.png'.format(imagesdir, epoch + 1))\n plt.close()\n # save sample input and reconstruction\n vutils.save_image(x, '{}/test_samples_epoch_{}.png'.format(imagesdir, epoch + 1))\n vutils.save_image(batch['decode'].detach(),\n '{}/test_reconstructions_epoch_{}.png'.format(imagesdir, epoch + 1),\n normalize=True)\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.cuda.manual_seed", "matplotlib.pyplot.figure", "torch.manual_seed", "torch.no_grad", "matplotlib.pyplot.xlim", "torch.cuda.is_available", "matplotlib.pyplot.ylim", "matplotlib.pyplot.close", "matplotlib.use", "torch.device", "torch.cat", "matplotlib.pyplot.scatter" ] ]
aviadlazar/FLS
[ "03f1ec28adf3b15810ef2c2ac5e024697c3d0bff" ]
[ "tool/tv_reference/coco_eval.py" ]
[ "import json\r\nimport tempfile\r\n\r\nimport numpy as np\r\nimport copy\r\nimport time\r\nimport torch\r\nimport torch._six\r\n\r\nfrom pycocotools.cocoeval import COCOeval\r\nfrom pycocotools.coco import COCO\r\nimport pycocotools.mask as mask_util\r\n\r\nfrom collections import defaultdict\r\n\r\nfrom . import utils\r\n\r\n\r\nclass CocoEvaluator(object):\r\n def __init__(self, coco_gt, iou_types, bbox_fmt='coco'):\r\n assert isinstance(iou_types, (list, tuple))\r\n coco_gt = copy.deepcopy(coco_gt)\r\n self.coco_gt = coco_gt\r\n self.bbox_fmt = bbox_fmt.lower()\r\n assert self.bbox_fmt in ['voc', 'coco', 'yolo']\r\n\r\n self.iou_types = iou_types\r\n self.coco_eval = {}\r\n for iou_type in iou_types:\r\n self.coco_eval[iou_type] = COCOeval(coco_gt, iouType=iou_type)\r\n\r\n self.img_ids = []\r\n self.eval_imgs = {k: [] for k in iou_types}\r\n\r\n def update(self, predictions):\r\n img_ids = list(np.unique(list(predictions.keys())))\r\n self.img_ids.extend(img_ids)\r\n\r\n for iou_type in self.iou_types:\r\n results = self.prepare(predictions, iou_type)\r\n coco_dt = loadRes(self.coco_gt, results) if results else COCO()\r\n coco_eval = self.coco_eval[iou_type]\r\n\r\n coco_eval.cocoDt = coco_dt\r\n coco_eval.params.imgIds = list(img_ids)\r\n img_ids, eval_imgs = evaluate(coco_eval)\r\n\r\n self.eval_imgs[iou_type].append(eval_imgs)\r\n\r\n def synchronize_between_processes(self):\r\n for iou_type in self.iou_types:\r\n self.eval_imgs[iou_type] = np.concatenate(self.eval_imgs[iou_type], 2)\r\n create_common_coco_eval(self.coco_eval[iou_type], self.img_ids, self.eval_imgs[iou_type])\r\n\r\n def accumulate(self):\r\n for coco_eval in self.coco_eval.values():\r\n coco_eval.accumulate()\r\n\r\n def summarize(self):\r\n for iou_type, coco_eval in self.coco_eval.items():\r\n print(\"IoU metric: {}\".format(iou_type))\r\n coco_eval.summarize()\r\n\r\n def prepare(self, predictions, iou_type):\r\n if iou_type == \"bbox\":\r\n return self.prepare_for_coco_detection(predictions)\r\n elif iou_type == \"segm\":\r\n return self.prepare_for_coco_segmentation(predictions)\r\n elif iou_type == \"keypoints\":\r\n return self.prepare_for_coco_keypoint(predictions)\r\n else:\r\n raise ValueError(\"Unknown iou type {}\".format(iou_type))\r\n\r\n def prepare_for_coco_detection(self, predictions):\r\n coco_results = []\r\n for original_id, prediction in predictions.items():\r\n if len(prediction) == 0:\r\n continue\r\n \r\n if self.bbox_fmt == 'coco':\r\n boxes = prediction[\"boxes\"].tolist()\r\n else:\r\n boxes = prediction[\"boxes\"]\r\n boxes = convert_to_xywh(boxes, fmt=self.bbox_fmt).tolist()\r\n scores = prediction[\"scores\"].tolist()\r\n labels = prediction[\"labels\"].tolist()\r\n\r\n coco_results.extend(\r\n [\r\n {\r\n \"image_id\": original_id,\r\n \"category_id\": labels[k],\r\n \"bbox\": box,\r\n \"score\": scores[k],\r\n }\r\n for k, box in enumerate(boxes)\r\n ]\r\n )\r\n return coco_results\r\n\r\n def prepare_for_coco_segmentation(self, predictions):\r\n coco_results = []\r\n for original_id, prediction in predictions.items():\r\n if len(prediction) == 0:\r\n continue\r\n\r\n scores = prediction[\"scores\"]\r\n labels = prediction[\"labels\"]\r\n masks = prediction[\"masks\"]\r\n\r\n masks = masks > 0.5\r\n\r\n scores = prediction[\"scores\"].tolist()\r\n labels = prediction[\"labels\"].tolist()\r\n\r\n rles = [\r\n mask_util.encode(np.array(mask[0, :, :, np.newaxis], dtype=np.uint8, order=\"F\"))[0]\r\n for mask in masks\r\n ]\r\n for rle in rles:\r\n rle[\"counts\"] = rle[\"counts\"].decode(\"utf-8\")\r\n\r\n coco_results.extend(\r\n [\r\n {\r\n \"image_id\": original_id,\r\n \"category_id\": labels[k],\r\n \"segmentation\": rle,\r\n \"score\": scores[k],\r\n }\r\n for k, rle in enumerate(rles)\r\n ]\r\n )\r\n return coco_results\r\n\r\n def prepare_for_coco_keypoint(self, predictions):\r\n coco_results = []\r\n for original_id, prediction in predictions.items():\r\n if len(prediction) == 0:\r\n continue\r\n\r\n # boxes = prediction[\"boxes\"]\r\n # boxes = convert_to_xywh(boxes).tolist()\r\n scores = prediction[\"scores\"].tolist()\r\n labels = prediction[\"labels\"].tolist()\r\n keypoints = prediction[\"keypoints\"]\r\n keypoints = keypoints.flatten(start_dim=1).tolist()\r\n\r\n coco_results.extend(\r\n [\r\n {\r\n \"image_id\": original_id,\r\n \"category_id\": labels[k],\r\n 'keypoints': keypoint,\r\n \"score\": scores[k],\r\n }\r\n for k, keypoint in enumerate(keypoints)\r\n ]\r\n )\r\n return coco_results\r\n\r\n\r\ndef convert_to_xywh(boxes, fmt='voc'):\r\n if fmt.lower() == 'voc':\r\n xmin, ymin, xmax, ymax = boxes.unbind(1)\r\n return torch.stack((xmin, ymin, xmax - xmin, ymax - ymin), dim=1)\r\n elif fmt.lower() == 'yolo':\r\n xcen, ycen, w, h = boxes.unbind(1)\r\n return torch.stack((xcen-w/2, ycen-h/2, w, h), dim=1)\r\n\r\n\r\ndef merge(img_ids, eval_imgs):\r\n all_img_ids = utils.all_gather(img_ids)\r\n all_eval_imgs = utils.all_gather(eval_imgs)\r\n\r\n merged_img_ids = []\r\n for p in all_img_ids:\r\n merged_img_ids.extend(p)\r\n\r\n merged_eval_imgs = []\r\n for p in all_eval_imgs:\r\n merged_eval_imgs.append(p)\r\n\r\n merged_img_ids = np.array(merged_img_ids)\r\n merged_eval_imgs = np.concatenate(merged_eval_imgs, 2)\r\n\r\n # keep only unique (and in sorted order) images\r\n merged_img_ids, idx = np.unique(merged_img_ids, return_index=True)\r\n merged_eval_imgs = merged_eval_imgs[..., idx]\r\n\r\n return merged_img_ids, merged_eval_imgs\r\n\r\n\r\ndef create_common_coco_eval(coco_eval, img_ids, eval_imgs):\r\n img_ids, eval_imgs = merge(img_ids, eval_imgs)\r\n img_ids = list(img_ids)\r\n eval_imgs = list(eval_imgs.flatten())\r\n\r\n coco_eval.evalImgs = eval_imgs\r\n coco_eval.params.imgIds = img_ids\r\n coco_eval._paramsEval = copy.deepcopy(coco_eval.params)\r\n\r\n\r\n#################################################################\r\n# From pycocotools, just removed the prints and fixed\r\n# a Python3 bug about unicode not defined\r\n#################################################################\r\n\r\n# Ideally, pycocotools wouldn't have hard-coded prints\r\n# so that we could avoid copy-pasting those two functions\r\n\r\ndef createIndex(self):\r\n # create index\r\n # print('creating index...')\r\n anns, cats, imgs = {}, {}, {}\r\n imgToAnns, catToImgs = defaultdict(list), defaultdict(list)\r\n if 'annotations' in self.dataset:\r\n for ann in self.dataset['annotations']:\r\n imgToAnns[ann['image_id']].append(ann)\r\n anns[ann['id']] = ann\r\n\r\n if 'images' in self.dataset:\r\n for img in self.dataset['images']:\r\n imgs[img['id']] = img\r\n\r\n if 'categories' in self.dataset:\r\n for cat in self.dataset['categories']:\r\n cats[cat['id']] = cat\r\n\r\n if 'annotations' in self.dataset and 'categories' in self.dataset:\r\n for ann in self.dataset['annotations']:\r\n catToImgs[ann['category_id']].append(ann['image_id'])\r\n\r\n # print('index created!')\r\n\r\n # create class members\r\n self.anns = anns\r\n self.imgToAnns = imgToAnns\r\n self.catToImgs = catToImgs\r\n self.imgs = imgs\r\n self.cats = cats\r\n\r\n\r\nmaskUtils = mask_util\r\n\r\n\r\ndef loadRes(self, resFile):\r\n \"\"\"\r\n Load result file and return a result api object.\r\n :param resFile (str) : file name of result file\r\n :return: res (obj) : result api object\r\n \"\"\"\r\n res = COCO()\r\n res.dataset['images'] = [img for img in self.dataset['images']]\r\n\r\n # print('Loading and preparing results...')\r\n # tic = time.time()\r\n if isinstance(resFile, torch._six.string_classes):\r\n anns = json.load(open(resFile))\r\n elif type(resFile) == np.ndarray:\r\n anns = self.loadNumpyAnnotations(resFile)\r\n else:\r\n anns = resFile\r\n assert type(anns) == list, 'results in not an array of objects'\r\n annsImgIds = [ann['image_id'] for ann in anns]\r\n assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), \\\r\n 'Results do not correspond to current coco set'\r\n if 'caption' in anns[0]:\r\n imgIds = set([img['id'] for img in res.dataset['images']]) & set([ann['image_id'] for ann in anns])\r\n res.dataset['images'] = [img for img in res.dataset['images'] if img['id'] in imgIds]\r\n for id, ann in enumerate(anns):\r\n ann['id'] = id + 1\r\n elif 'bbox' in anns[0] and not anns[0]['bbox'] == []:\r\n res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])\r\n for id, ann in enumerate(anns):\r\n ann['bbox'] = ann['bbox'][0]\r\n bb = ann['bbox']\r\n x1, x2, y1, y2 = [bb[0], bb[0] + bb[2], bb[1], bb[1] + bb[3]]\r\n if 'segmentation' not in ann:\r\n ann['segmentation'] = [[x1, y1, x1, y2, x2, y2, x2, y1]]\r\n ann['area'] = bb[2] * bb[3]\r\n ann['id'] = id + 1\r\n ann['iscrowd'] = 0\r\n elif 'segmentation' in anns[0]:\r\n res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])\r\n for id, ann in enumerate(anns):\r\n # now only support compressed RLE format as segmentation results\r\n ann['area'] = maskUtils.area(ann['segmentation'])\r\n if 'bbox' not in ann:\r\n ann['bbox'] = maskUtils.toBbox(ann['segmentation'])\r\n ann['id'] = id + 1\r\n ann['iscrowd'] = 0\r\n elif 'keypoints' in anns[0]:\r\n res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])\r\n for id, ann in enumerate(anns):\r\n s = ann['keypoints']\r\n x = s[0::3]\r\n y = s[1::3]\r\n x1, x2, y1, y2 = np.min(x), np.max(x), np.min(y), np.max(y)\r\n ann['area'] = (x2 - x1) * (y2 - y1)\r\n ann['id'] = id + 1\r\n ann['bbox'] = [x1, y1, x2 - x1, y2 - y1]\r\n # print('DONE (t={:0.2f}s)'.format(time.time()- tic))\r\n\r\n res.dataset['annotations'] = anns\r\n createIndex(res)\r\n return res\r\n\r\n\r\ndef evaluate(self):\r\n '''\r\n Run per image evaluation on given images and store results (a list of dict) in self.evalImgs\r\n :return: None\r\n '''\r\n # tic = time.time()\r\n # print('Running per image evaluation...')\r\n p = self.params\r\n # add backward compatibility if useSegm is specified in params\r\n if p.useSegm is not None:\r\n p.iouType = 'segm' if p.useSegm == 1 else 'bbox'\r\n print('useSegm (deprecated) is not None. Running {} evaluation'.format(p.iouType))\r\n # print('Evaluate annotation type *{}*'.format(p.iouType))\r\n p.imgIds = list(np.unique(p.imgIds))\r\n if p.useCats:\r\n p.catIds = list(np.unique(p.catIds))\r\n p.maxDets = sorted(p.maxDets)\r\n self.params = p\r\n\r\n self._prepare()\r\n # loop through images, area range, max detection number\r\n catIds = p.catIds if p.useCats else [-1]\r\n\r\n if p.iouType == 'segm' or p.iouType == 'bbox':\r\n computeIoU = self.computeIoU\r\n elif p.iouType == 'keypoints':\r\n computeIoU = self.computeOks\r\n self.ious = {\r\n (imgId, catId): computeIoU(imgId, catId)\r\n for imgId in p.imgIds\r\n for catId in catIds}\r\n\r\n evaluateImg = self.evaluateImg\r\n maxDet = p.maxDets[-1]\r\n evalImgs = [\r\n evaluateImg(imgId, catId, areaRng, maxDet)\r\n for catId in catIds\r\n for areaRng in p.areaRng\r\n for imgId in p.imgIds\r\n ]\r\n # this is NOT in the pycocotools code, but could be done outside\r\n evalImgs = np.asarray(evalImgs).reshape(len(catIds), len(p.areaRng), len(p.imgIds))\r\n self._paramsEval = copy.deepcopy(self.params)\r\n # toc = time.time()\r\n # print('DONE (t={:0.2f}s).'.format(toc-tic))\r\n return p.imgIds, evalImgs\r\n\r\n#################################################################\r\n# end of straight copy from pycocotools, just removing the prints\r\n#################################################################\r\n" ]
[ [ "torch.stack", "numpy.asarray", "numpy.max", "numpy.min", "numpy.array", "numpy.concatenate", "numpy.unique" ] ]
bbw7561135/PlasmaEDU
[ "aba2a00c04413bdf26c74f9e5c515644a517b728" ]
[ "bfield/python/ex03_plot_loopxyz_magnitude.py" ]
[ "################################################################################\n#\n# BFIELD\n#\n# Simple example of plot of the magnitude of the magnetic field\n# produced by a current loop, using its Cartesian components\n#\n#\n################################################################################\n\nimport numpy as np\nimport bfield\nimport matplotlib.pyplot as plt\n\n# Current Loop\nRa = 0.05\nI0 = 100.\nNturns = 1\nCenter = np.array([0,0,0])\nAngles = np.array([90,0,0]) * np.pi/180.0\n\n# X,Y Grid\nX = np.linspace(-0.1, 0.1, 50 )\nY = np.linspace(-0.1, 0.1, 50 )\n\n# B-field magnitude\nBnorm = np.zeros((X.size,Y.size))\nfor i in range(0,X.size):\n for j in range(0,Y.size):\n Point = np.array([ X[i], Y[j], 0.0 ])\n Bx,By,Bz = bfield.loopxyz(Ra,I0,Nturns,Center,Angles,Point)\n Bnorm[i][j] = np.sqrt(Bx*Bx + By*By + Bz*Bz)\n\nplt.figure(1)\nXX,YY = np.meshgrid(X,Y)\nplt.contourf(np.transpose(XX),np.transpose(YY),Bnorm,30)\nplt.colorbar()\nplt.xlabel('X [m]')\nplt.ylabel('Y [m]')\nplt.title('B-field magnitude [T] of a Current Loop')\nplt.savefig('ex03_plot_loopxyz_magnitude.png',dpi=150)\nplt.show()\n" ]
[ [ "numpy.sqrt", "numpy.transpose", "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.pyplot.savefig", "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "numpy.array", "matplotlib.pyplot.colorbar", "numpy.meshgrid", "numpy.linspace", "matplotlib.pyplot.xlabel" ] ]
djoker07/facial_keipoint_detection
[ "112564b12330b0b18be8665a70c92c09e3434ce8" ]
[ "models.py" ]
[ "## TODO: define the convolutional neural network architecture\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n# can use the below import should you choose to initialize the weights of your Net\nimport torch.nn.init as I\n\n\nclass Net(nn.Module):\n\n def __init__(self):\n super(Net, self).__init__()\n \n ## TODO: Define all the layers of this CNN, the only requirements are:\n ## 1. This network takes in a square (same width and height), grayscale image as input\n ## 2. It ends with a linear layer that represents the keypoints\n ## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs\n \n # As an example, you've been given a convolutional layer, which you may (but don't have to) change:\n # 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel\n self.conv1 = nn.Conv2d(1, 32, 5, padding=2)\n self.pool1 = nn.MaxPool2d(4, 4)\n \n self.conv2 = nn.Conv2d(32, 64, 3, padding=1)\n self.pool2 = nn.MaxPool2d(2, 2)\n \n self.conv3 = nn.Conv2d(64, 128, 1)\n self.pool3 = nn.MaxPool2d(2, 2)\n \n# self.conv4 = nn.Conv2d(128, 256, 1)\n# self.pool4 = nn.MaxPool2d(2, 2)\n \n #calculate input size 32 * 52 * 52\n fc1_input_size = 128 * 14 * 14\n self.lin1 = nn.Linear(fc1_input_size, 1000)\n self.lin2 = nn.Linear(1000, (68 * 2))\n\n \n ## Note that among the layers to add, consider including:\n # maxpooling layers, multiple conv layers, fully-connected layers, and other layers (such as dropout or batch normalization) to avoid overfitting\n \n\n \n def forward(self, x):\n ## TODO: Define the feedforward behavior of this model\n ## x is the input image and, as an example, here you may choose to include a pool/conv step:\n# x = self.pool1(F.relu(self.conv1(x)))\n\n drop1 = nn.Dropout(0.1)\n drop2 = nn.Dropout(0.2)\n drop3 = nn.Dropout(0.3)\n drop4 = nn.Dropout(0.4)\n \n x = drop1(self.pool1(F.relu(self.conv1(x))))\n x = drop2(self.pool2(F.relu(self.conv2(x))))\n x = drop3(self.pool3(F.relu(self.conv3(x))))\n \n x = x.view(x.size(0), -1)\n x = drop4(F.relu(self.lin1(x)))\n x = self.lin2(x)\n \n # a modified x, having gone through all the layers of your model, should be returned\n return x\n" ]
[ [ "torch.nn.Linear", "torch.nn.MaxPool2d", "torch.nn.Conv2d", "torch.nn.Dropout" ] ]
BranYang/pandas
[ "1033e8b1195d4071253889ada60523832285354c" ]
[ "pandas/tests/extension/decimal/test_decimal.py" ]
[ "import decimal\n\nimport numpy as np\nimport pandas as pd\nimport pandas.util.testing as tm\nimport pytest\n\nfrom pandas.tests.extension import base\n\nfrom .array import DecimalDtype, DecimalArray, make_data\n\n\[email protected]\ndef dtype():\n return DecimalDtype()\n\n\[email protected]\ndef data():\n return DecimalArray(make_data())\n\n\[email protected]\ndef data_missing():\n return DecimalArray([decimal.Decimal('NaN'), decimal.Decimal(1)])\n\n\[email protected]\ndef data_repeated():\n def gen(count):\n for _ in range(count):\n yield DecimalArray(make_data())\n yield gen\n\n\[email protected]\ndef data_for_sorting():\n return DecimalArray([decimal.Decimal('1'),\n decimal.Decimal('2'),\n decimal.Decimal('0')])\n\n\[email protected]\ndef data_missing_for_sorting():\n return DecimalArray([decimal.Decimal('1'),\n decimal.Decimal('NaN'),\n decimal.Decimal('0')])\n\n\[email protected]\ndef na_cmp():\n return lambda x, y: x.is_nan() and y.is_nan()\n\n\[email protected]\ndef na_value():\n return decimal.Decimal(\"NaN\")\n\n\[email protected]\ndef data_for_grouping():\n b = decimal.Decimal('1.0')\n a = decimal.Decimal('0.0')\n c = decimal.Decimal('2.0')\n na = decimal.Decimal('NaN')\n return DecimalArray([b, b, na, na, a, a, b, c])\n\n\nclass BaseDecimal(object):\n\n def assert_series_equal(self, left, right, *args, **kwargs):\n\n left_na = left.isna()\n right_na = right.isna()\n\n tm.assert_series_equal(left_na, right_na)\n return tm.assert_series_equal(left[~left_na],\n right[~right_na],\n *args, **kwargs)\n\n def assert_frame_equal(self, left, right, *args, **kwargs):\n # TODO(EA): select_dtypes\n tm.assert_index_equal(\n left.columns, right.columns,\n exact=kwargs.get('check_column_type', 'equiv'),\n check_names=kwargs.get('check_names', True),\n check_exact=kwargs.get('check_exact', False),\n check_categorical=kwargs.get('check_categorical', True),\n obj='{obj}.columns'.format(obj=kwargs.get('obj', 'DataFrame')))\n\n decimals = (left.dtypes == 'decimal').index\n\n for col in decimals:\n self.assert_series_equal(left[col], right[col],\n *args, **kwargs)\n\n left = left.drop(columns=decimals)\n right = right.drop(columns=decimals)\n tm.assert_frame_equal(left, right, *args, **kwargs)\n\n\nclass TestDtype(BaseDecimal, base.BaseDtypeTests):\n pass\n\n\nclass TestInterface(BaseDecimal, base.BaseInterfaceTests):\n pass\n\n\nclass TestConstructors(BaseDecimal, base.BaseConstructorsTests):\n pass\n\n\nclass TestReshaping(BaseDecimal, base.BaseReshapingTests):\n pass\n\n\nclass TestGetitem(BaseDecimal, base.BaseGetitemTests):\n\n def test_take_na_value_other_decimal(self):\n arr = DecimalArray([decimal.Decimal('1.0'),\n decimal.Decimal('2.0')])\n result = arr.take([0, -1], allow_fill=True,\n fill_value=decimal.Decimal('-1.0'))\n expected = DecimalArray([decimal.Decimal('1.0'),\n decimal.Decimal('-1.0')])\n self.assert_extension_array_equal(result, expected)\n\n\nclass TestMissing(BaseDecimal, base.BaseMissingTests):\n pass\n\n\nclass TestMethods(BaseDecimal, base.BaseMethodsTests):\n @pytest.mark.parametrize('dropna', [True, False])\n @pytest.mark.xfail(reason=\"value_counts not implemented yet.\")\n def test_value_counts(self, all_data, dropna):\n all_data = all_data[:10]\n if dropna:\n other = np.array(all_data[~all_data.isna()])\n else:\n other = all_data\n\n result = pd.Series(all_data).value_counts(dropna=dropna).sort_index()\n expected = pd.Series(other).value_counts(dropna=dropna).sort_index()\n\n tm.assert_series_equal(result, expected)\n\n\nclass TestCasting(BaseDecimal, base.BaseCastingTests):\n pass\n\n\nclass TestGroupby(BaseDecimal, base.BaseGroupbyTests):\n pass\n\n\ndef test_series_constructor_coerce_data_to_extension_dtype_raises():\n xpr = (\"Cannot cast data to extension dtype 'decimal'. Pass the \"\n \"extension array directly.\")\n with tm.assert_raises_regex(ValueError, xpr):\n pd.Series([0, 1, 2], dtype=DecimalDtype())\n\n\ndef test_series_constructor_with_same_dtype_ok():\n arr = DecimalArray([decimal.Decimal('10.0')])\n result = pd.Series(arr, dtype=DecimalDtype())\n expected = pd.Series(arr)\n tm.assert_series_equal(result, expected)\n\n\ndef test_series_constructor_coerce_extension_array_to_dtype_raises():\n arr = DecimalArray([decimal.Decimal('10.0')])\n xpr = r\"Cannot specify a dtype 'int64' .* \\('decimal'\\).\"\n\n with tm.assert_raises_regex(ValueError, xpr):\n pd.Series(arr, dtype='int64')\n\n\ndef test_dataframe_constructor_with_same_dtype_ok():\n arr = DecimalArray([decimal.Decimal('10.0')])\n\n result = pd.DataFrame({\"A\": arr}, dtype=DecimalDtype())\n expected = pd.DataFrame({\"A\": arr})\n tm.assert_frame_equal(result, expected)\n\n\ndef test_dataframe_constructor_with_different_dtype_raises():\n arr = DecimalArray([decimal.Decimal('10.0')])\n\n xpr = \"Cannot coerce extension array to dtype 'int64'. \"\n with tm.assert_raises_regex(ValueError, xpr):\n pd.DataFrame({\"A\": arr}, dtype='int64')\n" ]
[ [ "pandas.Series", "pandas.util.testing.assert_raises_regex", "pandas.DataFrame", "pandas.util.testing.assert_series_equal", "pandas.util.testing.assert_frame_equal" ] ]
sethuiyer/mlhub
[ "6be271c0070a0c0bb90dd92aceb344e7415bb1db" ]
[ "Pokemon Identifier/poketype.py" ]
[ "import pickle\nimport pandas as pd \nfrom sklearn.utils import resample\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.svm import LinearSVC\nimport os \n\nclass PokemonTypeIdentifier():\n \"\"\"\n This class identifies the pokemon type of a user given pokemon name.\n \"\"\"\n def __init__(self):\n self.isModelLoaded = False\n self.isFileFound = False\n if os.path.isfile(\"models/tfidf.pickle\") and os.path.isfile(\"models/model.pickle\"):\n self.tfidf = pickle.load(open(\"models/tfidf.pickle\",\"rb\"))\n self.model = pickle.load(open(\"models/model.pickle\",\"rb\"))\n self.isModelLoaded = True\n if os.path.isfile('updated_pokemon.csv'):\n df = pd.read_csv('updated_pokemon.csv')\n category = list(dict(df['Type 1'].value_counts()).keys())\n df_majority = df[df['Type 1'] == 'Water']\n for i in range(1,len(category)):\n df_minority = df[df['Type 1'] == category[i]]\n df_minority_upsampled = resample(df_minority, \n replace=True, # sample with replacement\n n_samples=103, # to match majority class\n random_state=123) # reproducible results\n df_majority = pd.concat([df_majority, df_minority_upsampled])\n encoded_labels,decoded_labels = pd.factorize(df_majority['Type 1'])\n self.decoded_labels = decoded_labels\n self.isFileFound = True\n if not self.isModelLoaded and self.isFileFound:\n \n\n self.tfidf = TfidfVectorizer(min_df=2, max_features = None, strip_accents = 'unicode', norm='l2',\n analyzer = 'char', token_pattern = r'\\w{1,}',ngram_range=(1,5),\n use_idf = 1, smooth_idf = 1, sublinear_tf = 1, stop_words = 'english')\n\n features = self.tfidf.fit_transform(df_majority['Name']).toarray()\n encoded_labels,decoded_labels = pd.factorize(df_majority['Type 1'])\n self.model = LinearSVC().fit(features,encoded_labels)\n self.decoded_labels = decoded_labels\n if not self.isModelLoaded or not self.isFileFound:\n raise AttributeError(\"Required File Doesn't Exist.\")\n def predict_type(self,poke_str):\n \"\"\"\n Finds the probable Pokemon type given the user string.\n Input: A string, of which type is to be identified.\n Output: The Probable pokemon type \n \"\"\"\n return self.decoded_labels[self.model.predict(self.tfidf.transform([poke_str]))[0]]\n\n" ]
[ [ "pandas.read_csv", "sklearn.svm.LinearSVC", "sklearn.feature_extraction.text.TfidfVectorizer", "pandas.concat", "sklearn.utils.resample", "pandas.factorize" ] ]
feynmanliang/beanmachine
[ "5dea2b9f6387f2f7fd1e53b0915a1b8405f2b46b" ]
[ "src/beanmachine/ppl/legacy/inference/abstract_infer.py" ]
[ "# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport logging\nimport platform\nimport random\nfrom abc import ABCMeta, abstractmethod\nfrom typing import ClassVar, Dict, List\n\nimport torch\nimport torch.multiprocessing as mp\nfrom beanmachine.ppl.inference.monte_carlo_samples import MonteCarloSamples\nfrom beanmachine.ppl.inference.utils import (\n _verify_queries_and_observations,\n VerboseLevel,\n)\nfrom beanmachine.ppl.legacy.world import World\nfrom beanmachine.ppl.model.rv_identifier import RVIdentifier\nfrom beanmachine.ppl.model.utils import LogLevel\nfrom torch import Tensor\nfrom torch.multiprocessing import Queue\n\n\nLOGGER = logging.getLogger(\"beanmachine\")\n\n\nclass AbstractInference(object, metaclass=ABCMeta):\n \"\"\"\n Abstract inference object that all inference algorithms inherit from.\n \"\"\"\n\n world_: World\n _rand_int_max: ClassVar[int] = 2**62\n\n def __init__(self):\n self.initial_world_ = World()\n self.world_ = self.initial_world_\n self.queries_ = []\n self.observations_ = {}\n\n @staticmethod\n def set_seed(seed: int):\n torch.manual_seed(seed)\n random.seed(seed)\n\n def initialize_world(\n self,\n initialize_from_prior: bool = False,\n ):\n \"\"\"\n Initializes the world variables with queries and observation calls.\n\n :param initialize_from_prior: boolean to initialize samples from prior\n approximation.\n \"\"\"\n self.world_ = self.initial_world_.copy()\n self.world_.set_observations(self.observations_)\n self.world_.set_initialize_from_prior(initialize_from_prior)\n\n for node in self.observations_:\n # makes the call for the observation node, which will run sample(node())\n # that results in adding its corresponding Variable and its dependent\n # Variable to the world\n self.world_.call(node)\n for node in self.queries_:\n # makes the call for the query node, which will run sample(node())\n # that results in adding its corresponding Variable and its dependent\n # Variable to the world.\n self.world_.call(node)\n self.world_.accept_diff()\n\n def reset(self):\n \"\"\"\n Resets world, mode and observation\n \"\"\"\n self.world_ = self.initial_world_.copy()\n self.queries_ = []\n self.observations_ = {}\n\n\nclass AbstractMCInference(AbstractInference, metaclass=ABCMeta):\n \"\"\"\n Abstract inference object for Monte Carlo inference.\n \"\"\"\n\n _observations_must_be_rv: bool = True\n\n @staticmethod\n def set_seed_for_chain(random_seed: int, chain: int):\n AbstractInference.set_seed(random_seed + chain * 31)\n\n @abstractmethod\n def _infer(\n self,\n num_samples: int,\n num_adaptive_samples: int = 0,\n verbose: VerboseLevel = VerboseLevel.LOAD_BAR,\n initialize_from_prior: bool = False,\n ) -> Dict[RVIdentifier, Tensor]:\n \"\"\"\n Abstract method to be implemented by classes that inherit from\n AbstractInference.\n \"\"\"\n raise NotImplementedError(\"Inference algorithm must implement _infer.\")\n\n def _parallel_infer(\n self,\n queue: Queue,\n chain: int,\n num_samples: int,\n random_seed: int,\n num_adaptive_samples: int,\n verbose: VerboseLevel,\n ):\n try:\n AbstractMCInference.set_seed_for_chain(random_seed, chain)\n rv_dict = self._infer(num_samples, num_adaptive_samples, verbose)\n string_dict = {str(rv): tensor.detach() for rv, tensor in rv_dict.items()}\n queue.put((None, chain, string_dict))\n except BaseException as x:\n LOGGER.log(\n LogLevel.ERROR.value, \"Error: Parallel infererence chain failed.\"\n )\n queue.put((x, chain, {}))\n\n def infer(\n self,\n queries: List[RVIdentifier],\n observations: Dict[RVIdentifier, Tensor],\n num_samples: int,\n num_chains: int = 4,\n run_in_parallel: bool = False,\n num_adaptive_samples: int = 0,\n verbose: VerboseLevel = VerboseLevel.LOAD_BAR,\n initialize_from_prior: bool = False,\n ) -> MonteCarloSamples:\n \"\"\"\n Run inference algorithms and reset the world/mode at the end.\n\n All tensors in `queries` and `observations` must be allocated on the\n same `torch.device`. Inference algorithms will attempt to allocate\n intermediate tensors on the same device.\n\n :param queries: random variables to query\n :param observations: observed random variables with their values\n :param num_samples: number of samples excluding adaptation to collect.\n :param num_chains: number of chains to run\n :param num_adaptive_samples: number of steps to allow proposer adaptation.\n :param verbose: Integer indicating how much output to print to stdio\n :param initialize_from_prior: boolean to initialize samples from prior\n :returns: view of data for chains and samples for query\n \"\"\"\n\n _verify_queries_and_observations(\n queries, observations, self._observations_must_be_rv\n )\n random_seed = torch.randint(AbstractInference._rand_int_max, (1,)).int().item()\n self.queries_ = queries\n self.observations_ = observations\n if num_chains > 1 and run_in_parallel:\n if platform.system() == \"Windows\":\n raise RuntimeError(\n \"Running inference in parallel is not currently support on Windows\"\n )\n\n ctx = mp.get_context(\"fork\")\n manager = ctx.Manager()\n q = manager.Queue()\n for chain in range(num_chains):\n p = ctx.Process(\n target=self._parallel_infer,\n args=(\n q,\n chain,\n num_samples,\n random_seed,\n num_adaptive_samples,\n verbose,\n ),\n )\n p.start()\n\n chain_queries = [{}] * num_chains\n for _ in range(num_chains):\n (error, chain, string_dict) = q.get()\n if error is not None:\n raise error\n rv_dict = {rv: string_dict[str(rv)] for rv in queries}\n chain_queries[chain] = rv_dict\n else:\n chain_queries = []\n for chain in range(num_chains):\n AbstractMCInference.set_seed_for_chain(random_seed, chain)\n rv_dicts = self._infer(\n num_samples,\n num_adaptive_samples,\n verbose,\n initialize_from_prior,\n )\n chain_queries.append(rv_dicts)\n monte_carlo_samples = MonteCarloSamples(chain_queries, num_adaptive_samples)\n self.reset()\n return monte_carlo_samples\n" ]
[ [ "torch.multiprocessing.get_context", "torch.manual_seed", "torch.randint" ] ]
UWaterloo-ASL/LAS_Gym
[ "916043d59aeca3deb8875abb280dcecbdcd50f0f" ]
[ "ArchiveTestCode/Red Light Excited Visitor Simulator/LivingArchitectureEnv.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 8 16:12:32 2018\n\n@author: jack.lingheng.meng\n\"\"\"\ntry:\n import vrep\nexcept:\n print ('--------------------------------------------------------------')\n print ('\"vrep.py\" could not be imported. This means very probably that')\n print ('either \"vrep.py\" or the remoteApi library could not be found.')\n print ('Make sure both are in the same folder as this file,')\n print ('or appropriately adjust the file \"vrep.py\"')\n print ('--------------------------------------------------------------')\n print ('')\n\nimport gym\nfrom gym import spaces\nimport time\nimport numpy as np\nimport warnings\n\nclass LivingArchitectureEnv(gym.Env):\n def __init__(self):\n print ('Program started')\n # connect to V-REP server\n vrep.simxFinish(-1) # just in case, close all opened connections\n self.clientID = vrep.simxStart('127.0.0.1',19997,True,True,5000,5) # Connect to V-REP\n if self.clientID!=-1:\n print ('Connected to remote API server')\n else:\n print ('Failed connecting to remote API server')\n # start simulate\n self._def_op_mode = vrep.simx_opmode_blocking\n self._set_joint_op_mode = vrep.simx_opmode_oneshot\n self._set_light_op_mode = vrep.simx_opmode_oneshot\n self._set_visitor_op_mode = vrep.simx_opmode_oneshot\n \n # To get sensor data\n # vrep.simx_opmode_buffer: does not work, don't know why?\n # vrep.simx_opmode_blocking: too slow\n # vrep.simx_opmode_oneshot: works pretty good\n self._get_prox_op_mode = vrep.simx_opmode_oneshot \n self._get_light_op_mode = vrep.simx_opmode_oneshot\n \n \n \n vrep.simxStartSimulation(self.clientID, self._def_op_mode)\n \n # get object names and handles\n self._get_object_name_and_handle()\n \n # initialize action and observation space\n print(\"Initialize LAS action and observation space...\")\n self.prox_sensor_num = len(self.proxSensorHandles)\n self.smas_num = len(self.jointHandles)\n self.lights_num = len(self.lightHandles)\n self.sensors_dim = self.prox_sensor_num + self.lights_num * (1+3)\n self.actuators_dim = self.smas_num + self.lights_num * (1+3) # light state & color\n \n self.act_max = np.array([np.inf]*self.actuators_dim)\n self.act_min = - np.array([np.inf]*self.actuators_dim)\n self.obs_max = np.array([1.]*self.sensors_dim)\n self.obs_min = - np.array([1.]*self.sensors_dim)\n \n self.observation_space = spaces.Box(self.obs_min, self.obs_max)\n self.action_space = spaces.Box(self.act_min, self.act_max)\n print(\"Initialization of LAS done!\")\n \n # initialize Visitor action and observation space\n print(\"Initialize Visitor action and observation space...\")\n self.visitor_num = len(self.visitorHandles)\n self.visitor_action_dim = self.visitor_num * 2 # visitor's position (x,y,0)\n self.visitor_action_max = np.array([7,9]*self.visitor_num) # later we should find a way to automatic get this limit\n self.visitor_action_min = np.array([-7,-9]*self.visitor_num)\n self.visitor_action_space = spaces.Box(self.visitor_action_min, self.visitor_action_max)\n \n # initialize Single Visitor action and observation space\n print(\"Initialize Visitor action and observation space...\")\n self.single_visitor_action_dim = self.visitor_num * 2 # visitor's position (x,y,0)\n self.single_visitor_action_max = np.array([7,9]) # later we should find a way to automatic get this limit\n self.single_visitor_action_min = np.array([-7,-9])\n self.single_visitor_action_space = spaces.Box(self.single_visitor_action_min, self.single_visitor_action_max)\n \n print(\"Initialization of visitor done!\")\n \n self.reward = 0\n \n \n def _get_object_name_and_handle(self):\n \"\"\"\n # When call vrep.simxGetObjectGroupData to abstract object name and handle\n # choose appropriate objectType parameter:\n # joint: vrep.sim_object_joint_type\n # proximity sensor: vrep.sim_object_proximitysensor_type\n # light: vrep.sim_object_light_type\n # visitor target position: vrep.sim_object_dummy_type\n # visitor body: vrep.sim_object_shape_type\n \"\"\"\n dataType = 0 # 0: retrieves the object names (in stringData.)\n print(\"Get objects' names and handles ...\")\n\n # proximity sensor\n proxSensorIndex = []\n rc = vrep.simx_return_initialize_error_flag\n while rc != vrep.simx_return_ok:\n rc, proxSensorHandles, intData, floatData, proxSensorNames = vrep.simxGetObjectGroupData(self.clientID,vrep.sim_object_proximitysensor_type, dataType, self._def_op_mode)\n if rc==vrep.simx_return_ok:\n print ('Get Prox Sensor Success!!!!!') # display the reply from V-REP (in this case, just a string)\n for i, name in enumerate(proxSensorNames):\n if \"_node#\" in name:\n print(\"Proximity Sensor: {}, and handle: {}\".format(name, proxSensorHandles[i]))\n proxSensorIndex.append(i)\n break\n else:\n print ('Fail to get proximity sensors!!!')\n # light\n lightIndex = []\n rc = vrep.simx_return_initialize_error_flag\n while rc != vrep.simx_return_ok:\n rc, lightHandles, intData, floatData, lightNames = vrep.simxGetObjectGroupData(self.clientID,vrep.sim_object_light_type, dataType, self._def_op_mode)\n if rc==vrep.simx_return_ok:\n print ('Get Lihgt Success!!!!!') # display the reply from V-REP (in this case, just a string)\n for i, name in enumerate(lightNames):\n if \"_node#\" in name:\n print(\"Light: {}, and handle: {}\".format(name, lightHandles[i]))\n lightIndex.append(i)\n break\n else:\n print ('Fail to get lights!!!')\n # joint\n jointIndex = []\n rc = vrep.simx_return_initialize_error_flag\n while rc != vrep.simx_return_ok:\n rc, jointHandles, intData, floatData, jointNames = vrep.simxGetObjectGroupData(self.clientID,vrep.sim_object_joint_type, dataType, self._def_op_mode)\n if rc==vrep.simx_return_ok:\n print ('Get Joint Success!!!!!') # display the reply from V-REP (in this case, just a string)\n for i, name in enumerate(jointNames):\n if \"_node#\" in name:\n print(\"Joint: {}, and handle: {}\".format(name, jointHandles[i]))\n jointIndex.append(i)\n break\n else:\n print ('Fail to get joints!!!')\n \n # visitor targetPosition\n visitorIndex = []\n rc = vrep.simx_return_initialize_error_flag\n while rc != vrep.simx_return_ok:\n rc, visitorHandles, intData, floatData, visitorNames = vrep.simxGetObjectGroupData(self.clientID,vrep.sim_object_dummy_type, dataType, self._def_op_mode)\n if rc==vrep.simx_return_ok:\n print ('Get Visitor Success!!!!!') # display the reply from V-REP (in this case, just a string)\n for i, name in enumerate(visitorNames):\n if \"TargetPosition_Visitor#\" in name:\n print(\"Visitor: {}, and handle: {}\".format(name, visitorHandles[i]))\n visitorIndex.append(i)\n break\n else:\n print ('Fail to get visitors!!!')\n # visitor body\n visitorBodyIndex = []\n rc = vrep.simx_return_initialize_error_flag\n while rc != vrep.simx_return_ok:\n rc, visitorBodyHandles, intData, floatData, visitorBodyNames = vrep.simxGetObjectGroupData(self.clientID,vrep.sim_object_shape_type, dataType, self._def_op_mode)\n if rc==vrep.simx_return_ok:\n print ('Get Visitor Body Success!!!!!') # display the reply from V-REP (in this case, just a string)\n for i, name in enumerate(visitorBodyNames):\n if \"Body_Visitor#\" in name:\n print(\"Visitor body: {}, and handle: {}\".format(name, visitorBodyHandles[i]))\n visitorBodyIndex.append(i)\n break\n else:\n print ('Fail to get visitors body!!!')\n \n proxSensorHandles = np.array(proxSensorHandles)\n proxSensorNames = np.array(proxSensorNames)\n lightHandles = np.array(lightHandles)\n lightNames = np.array(lightNames)\n jointHandles = np.array(jointHandles)\n jointNames = np.array(jointNames)\n visitorHandles = np.array(visitorHandles)\n visitorNames = np.array(visitorNames)\n visitorBodyHandles = np.array(visitorBodyHandles)\n visitorBodyNames = np.array(visitorBodyNames)\n # All objects handels and names\n self.proxSensorHandles = proxSensorHandles[proxSensorIndex]\n self.proxSensorNames = proxSensorNames[proxSensorIndex]\n self.lightHandles = lightHandles[lightIndex]\n self.lightNames = lightNames[lightIndex]\n self.jointHandles = jointHandles[jointIndex]\n self.jointNames = jointNames[jointIndex]\n self.visitorNames = visitorNames[visitorIndex]\n self.visitorHandles = visitorHandles[visitorIndex]\n self.visitorBodyNames = visitorBodyNames[visitorBodyIndex]\n self.visitorBodyHandles = visitorBodyHandles[visitorBodyIndex]\n\n def step_LAS(self, action):\n \"\"\"\n Take one step of action\n Input: action\n Output: observation, reward, done, info\n \"\"\"\n #\n action = np.clip(action, self.act_min, self.act_max)\n # split action for light and sma\n action_smas = action[:self.smas_num]\n action_lights_state = action[self.smas_num:self.smas_num+self.lights_num]\n action_lights_state = action_lights_state.astype(int)\n action_lights_color = action[self.smas_num+self.lights_num:]\n # taking action\n #start = time.time()\n vrep.simxPauseCommunication(self.clientID,True) #temporarily halting the communication thread \n self._set_all_joint_position(action_smas)\n self._set_all_light_state(action_lights_state,action_lights_color)\n vrep.simxPauseCommunication(self.clientID,False) #and evaluated at the same time\n #print(\"Action running time: {}\".format(time.time()-start))\n \n # observe\n #start = time.time()\n self._self_observe()\n #print(\"Observation running time: {}\".format(time.time()-start))\n # caculate reward\n self._reward()\n \n done = False\n \n return self.observation, self.reward, done, []\n \n def step_visitor(self, position):\n \"\"\"\n This interface is for change visitor's position.\n Input: position\n Output: observation, reward, done, info\n \"\"\"\n #\n position = np.clip(position,self.visitor_action_min, self.visitor_action_max)\n vrep.simxPauseCommunication(self.clientID,True)\n self._set_all_visitor_position(position)\n vrep.simxPauseCommunication(self.clientID,False)\n \n self._self_observe()\n self._reward_visitor()\n done = False\n return self.observation, self.reward_visitor, done, [] \n\n def step_single_visitor(self, name, position):\n \"\"\"\n This interface is for change visitor's position.\n Input: position\n Output: observation, reward, done, info\n \"\"\"\n #\n position = np.clip(position,self.single_visitor_action_min, self.single_visitor_action_max)\n #vrep.simxPauseCommunication(self.clientID,True)\n self._set_single_visitor_position(name, position)\n #vrep.simxPauseCommunication(self.clientID,False)\n \n self._self_observe()\n self._reward_visitor()\n done = False\n return self.observation, self.reward_visitor, done, [] \n \n def step_red_light_excited_visitor(self, targetPositionName, bodyName, action):\n \"\"\"\n A specific interface for red excited visitor:\n return observation:\n light state: observation[:lightNum]\n light color: observation[lightNum:lightNum * 4]\n light position: observation[lightNum * 4:lightNum * 5]\n visitor position: observation[lightNum*5:]\n \"\"\"\n move = action[0]\n position = action[1:3] # we can leave z coordinate\n #print(\"Set position:{}\".format(position))\n position = np.clip(position,self.single_visitor_action_min, self.single_visitor_action_max)\n # if move == 1, move; otherwise don't move.\n if move == 1:\n #vrep.simxPauseCommunication(self.clientID,True)\n #print(\"Set Position in Vrep: {}\".format(position))\n self._set_single_visitor_position(targetPositionName, position)\n #vrep.simxPauseCommunication(self.clientID,False)\n \n observation = self._self_observe_for_red_excited_visitor(bodyName)\n #print(\"len(observation):{}\".format(len(observation)))\n reward = 0\n done = False\n return observation, reward, done, []\n \n def _set_single_visitor_position(self, targetPositionName, position):\n visitorIndex = np.where(self.visitorNames == targetPositionName)\n if len(visitorIndex[0]) == 0:\n print(\"Not found visitor: {}\".format(targetPositionName))\n else:\n vrep.simxSetObjectPosition(self.clientID, self.visitorHandles[visitorIndex], -1, [position[0],position[1],0], self._set_visitor_op_mode)\n def _get_single_visitor_body_position(self, bodyName):\n \"\"\"\n Give bodyName, return bodyPosition\n \"\"\"\n bodyPosition = np.zeros(3)\n visitorBodyIndex = np.where(self.visitorBodyNames == bodyName)\n if len(visitorBodyIndex[0]) == 0:\n print(\"Not found visitor: {}\".format(bodyName))\n else:\n res, bodyPosition = vrep.simxGetObjectPosition(self.clientID, self.visitorBodyHandles[visitorBodyIndex], -1, self._get_light_op_mode)\n #print(\"Visitor position: {}\".format(position))\n return np.array(bodyPosition)\n \n def _set_all_visitor_position(self, position):\n visitorNum = len(self.visitorHandles)\n for i in range(visitorNum):\n vrep.simxSetObjectPosition(self.clientID, self.visitorHandles[i], -1, [position[i*2],position[i*2+1],0], self._set_visitor_op_mode)\n \n def _set_all_joint_position(self, targetPosition):\n jointNum = len(self.jointHandles)\n for i in range(jointNum):\n vrep.simxSetJointTargetPosition(self.clientID, self.jointHandles[i], targetPosition[i], self._set_joint_op_mode)\n \n def _set_all_light_state(self, targetState, targetColor):\n lightNum = len(self.lightHandles)\n if len(targetState) != lightNum:\n print(\"len(targetState) != lightNum\")\n \n # inner function: remote function call to set light state\n def _set_light_state(clientID, name, handle, targetState, targetColor, opMode):\n\n emptyBuff = bytearray()\n res,retInts,retFloats,retStrings,retBuffer = vrep.simxCallScriptFunction(clientID,\n name,\n vrep.sim_scripttype_childscript,\n 'setLightStateAndColor',\n [handle, targetState],targetColor,[],emptyBuff,\n opMode)\n if res != vrep.simx_return_ok:\n warnings.warn(\"Remote function call: setLightStateAndColor fail in Class AnyLight.\")\n # inner function end\n for i in range(lightNum):\n _set_light_state(self.clientID, str(self.lightNames[i]), self.lightHandles[i], targetState[i], targetColor[i*3:(i+1)*3], self._set_light_op_mode)\n\n def _reward(self):\n \"\"\" calculate reward based on observation of prximity sensor\"\"\"\n self.reward = np.mean(self.observation[:self.prox_sensor_num])\n return self.reward\n \n def _reward_visitor(self):\n \"\"\"\n Calculate reward for visitor\n \"\"\"\n self.reward_visitor = 0\n return self.reward_visitor\n \n def _self_observe(self):\n \"\"\"\n This observe function is for LAS:\n proximity sensors\n light state\n light color\n \"\"\"\n proxStates, proxPosition = self._get_all_prox_data()\n lightStates, lightDiffsePart, lightSpecularPart = self._get_all_light_data()\n self.observation = np.concatenate((proxStates, lightStates, lightDiffsePart.flatten()))\n return self.observation\n \n def _self_observe_for_red_excited_visitor(self,bodyName):\n \"\"\"\n This obervave function is for visitors:\n light state: observation[:lightNum]\n light color: observation[lightNum:lightNum * 4]\n light position: observation[lightNum * 4:lightNum * 5]\n visitor position: observation[lightNum*5:]\n \"\"\"\n lightStates, lightDiffsePart, lightSpecularPart = self._get_all_light_data()\n lightPositions = self._get_all_light_position()\n visitorBodyPosition = self._get_single_visitor_body_position(bodyName)\n self.obser_for_red_light_excited_visitor = np.concatenate((lightStates,\n lightDiffsePart.flatten(),\n lightPositions.flatten(),\n visitorBodyPosition.flatten()))\n #print(\"length self.obser_for_red_light_excited_visitor:{}\".format(len(self.obser_for_red_light_excited_visitor)))\n return self.obser_for_red_light_excited_visitor\n \n def _get_all_prox_data(self):\n \"\"\"\n Get all proximity sensory data\n \"\"\"\n proxSensorNum = len(self.proxSensorHandles)\n proxStates = np.zeros(proxSensorNum)\n proxPosition = np.zeros([proxSensorNum, 3])\n for i in range(proxSensorNum):\n code, proxStates[i], proxPosition[i,:], handle, snv = vrep.simxReadProximitySensor(self.clientID, self.proxSensorHandles[i], self._get_prox_op_mode)\n return proxStates, proxPosition\n \n def _get_all_light_data(self):\n \"\"\"\n Get all light data:\n return:\n lightStates, lightDiffsePart, lightSpecularPart\n \"\"\"\n lightNum = len(self.lightHandles)\n #print(\"lightNum:{}\".format(lightNum))\n lightStates = np.zeros(lightNum)\n lightDiffsePart = np.zeros([lightNum,3])\n lightSpecularPart = np.zeros([lightNum,3])\n \n # inner function to get light state and color\n def _get_light_state_and_color(clientID, name , handle, op_mode):\n emptyBuff = bytearray()\n res,retInts,retFloats,retStrings,retBuffer=vrep.simxCallScriptFunction(clientID,\n name,\n vrep.sim_scripttype_childscript,\n 'getLightStateAndColor',\n [handle],[],[],emptyBuff,\n op_mode)\n if res==vrep.simx_return_ok:\n #print ('getLightStateAndColor works! ',retStrings[0]) # display the reply from V-REP (in this case, just a string)\n lightState = retInts[0]\n diffusePart = [retFloats[0],retFloats[1],retFloats[2]]\n specularPart = retFloats[3],retFloats[4],retFloats[5]\n return lightState, diffusePart, specularPart\n else:\n warnings.warn(\"Remote function call: getLightStateAndColor fail in Class AnyLight.\")\n return -1, [0,0,0], [0,0,0]\n # inner function end\n \n for i in range(lightNum):\n lightStates[i], lightDiffsePart[i,:], lightSpecularPart[i,:] = _get_light_state_and_color(self.clientID, str(self.lightNames[i]), self.lightHandles[i], self._get_light_op_mode)\n \n return lightStates, lightDiffsePart, lightSpecularPart\n \n def _get_all_light_position(self):\n \"\"\"\n Get all lights position:\n return:\n lightPositions\n \"\"\"\n lightNum = self.lights_num\n #print(\"_get_all_light_position lightNum:{}\".format(lightNum))\n lightPositions = np.zeros([lightNum, 3]) # 3: (x, y, z)\n for i in range(lightNum):\n res, lightPositions[i,:] = vrep.simxGetObjectPosition(self.clientID, self.lightHandles[i], -1, self._get_light_op_mode)\n return lightPositions\n \n def reset_env_for_LAS_red_light_excited_visitor(self, bodyName):\n vrep.simxStartSimulation(self.clientID, self._def_op_mode)\n observationForLAS = self._self_observe()\n observationForRedLightExcitedVisitor = self._self_observe_for_red_excited_visitor(bodyName)\n \n done = False\n rewardLAS = 0\n rewardVisitor = 0\n info = []\n return observationForLAS, observationForRedLightExcitedVisitor, rewardLAS, rewardVisitor, done, info\n \n def reset(self):\n #vrep.simxStopSimulation(self.clientID, self._def_op_mode)\n vrep.simxStartSimulation(self.clientID, self._def_op_mode)\n \n self._self_observe()\n self._reward()\n self._reward_visitor()\n done = False\n return self.observation, self.reward, self.reward_visitor, done\n \n def destroy(self):\n \"\"\"\n Finish simulation and release connection to server.\n \"\"\"\n vrep.simxStopSimulation(self.clientID, self._def_op_mode)\n vrep.simxFinish(self.clientID)" ]
[ [ "numpy.zeros", "numpy.clip", "numpy.array", "numpy.where", "numpy.mean" ] ]
Keck-DataReductionPipelines/KCWI_DRP
[ "5073a137a8edddf9ff894aef445f877d7186a355" ]
[ "kcwidrp/primitives/FluxCalibrate.py" ]
[ "from keckdrpframework.primitives.base_primitive import BasePrimitive\nfrom kcwidrp.primitives.kcwi_file_primitives import kcwi_fits_writer, \\\n kcwi_fits_reader, get_master_name, strip_fname\nfrom kcwidrp.core.kcwi_correct_extin import kcwi_correct_extin\n\nimport os\nimport numpy as np\nfrom scipy.interpolate import interp1d\n\nfrom astropy.io import fits as pf\nfrom astropy import units as u\nfrom astropy.nddata import CCDData\n\n\nclass FluxCalibrate(BasePrimitive):\n\n def __init__(self, action, context):\n BasePrimitive.__init__(self, action, context)\n self.logger = context.pipeline_logger\n\n def _pre_condition(self):\n \"\"\"\n Checks if we can calibrate flux based on the processing table\n :return:\n \"\"\"\n self.logger.info(\"Checking precondition for FluxCalibrate\")\n target_type = 'INVSENS'\n tab = self.context.proctab.search_proctab(frame=self.action.args.ccddata,\n target_type=target_type,\n nearest=True)\n self.logger.info(\"pre condition got %d invsens files, expected >= 1\"\n % len(tab))\n if len(tab) <= 0:\n self.action.args.invsname = None\n return False\n else:\n self.action.args.invsname = get_master_name(tab, target_type)\n return True\n\n def _perform(self):\n # Header keyword to update\n key = 'STDCOR'\n keycom = 'std corrected?'\n target_type = 'INVSENS'\n obj = None\n sky = None\n\n self.logger.info(\"Calibrating object flux\")\n tab = self.context.proctab.search_proctab(frame=self.action.args.ccddata,\n target_type=target_type,\n nearest=True)\n self.logger.info(\"%d invsens files found\" % len(tab))\n\n if self.action.args.invsname is not None:\n\n # read in master calibration (inverse sensitivity)\n invsname = self.action.args.invsname\n self.logger.info(\"Reading invsens: %s\" % invsname)\n hdul = pf.open(os.path.join(self.config.instrument.cwd,\n 'redux', invsname))\n mcal = hdul[0].data[1, :]\n mchdr = hdul[0].header\n hdul.close()\n # get dimensions\n mcsz = mcal.shape\n # get master std waves\n mcw0 = mchdr['CRVAL1']\n mcdw = mchdr['CDELT1']\n mcwav = mcw0 + np.arange(mcsz[0]) * mcdw\n # get master std image number\n msimgno = mchdr['FRAMENO']\n # get input object image dimensions\n sz = self.action.args.ccddata.data.shape\n # get object waves\n w0 = self.action.args.ccddata.header['CRVAL3']\n dw = self.action.args.ccddata.header['CD3_3']\n wav = w0 + np.arange(sz[0]) * dw\n # get exposure time\n expt = self.action.args.ccddata.header['XPOSURE']\n # resample onto object waves, if needed\n if w0 != mcw0 or dw != mcdw or wav[-1] != mcwav[-1] or \\\n sz[0] != mcsz[0]:\n self.logger.warning(\"wavelength scales not identical, \"\n \"resampling standard\")\n print(w0, mcw0, dw, mcdw, wav[-1], mcwav[-1], sz[0], mcsz[0])\n mcint = interp1d(mcwav, mcal, kind='cubic',\n fill_value='extrapolate')\n mscal = mcint(wav) * 1.e16 / expt\n else:\n mscal = mcal * 1.e16 / expt\n\n # extinction correct calibration\n kcwi_correct_extin(mscal, self.action.args.ccddata.header,\n logger=self.logger)\n # do calibration\n for isl in range(sz[2]):\n for ix in range(sz[1]):\n self.action.args.ccddata.data[:, ix, isl] *= mscal\n self.action.args.ccddata.uncertainty.array[:, ix, isl] *= \\\n mscal ** 2\n\n # check for obj, sky cubes\n if self.action.args.nasmask and self.action.args.numopen > 1:\n ofn = self.action.args.name\n # obj cube\n objfn = strip_fname(ofn) + '_ocubed.fits'\n full_path = os.path.join(\n self.config.instrument.cwd,\n self.config.instrument.output_directory, objfn)\n if os.path.exists(full_path):\n obj = kcwi_fits_reader(full_path)[0]\n # do calibration\n for isl in range(sz[2]):\n for ix in range(sz[1]):\n obj.data[:, ix, isl] *= mscal\n # sky cube\n skyfn = strip_fname(ofn) + '_scubed.fits'\n full_path = os.path.join(\n self.config.instrument.cwd,\n self.config.instrument.output_directory, skyfn)\n if os.path.exists(full_path):\n sky = kcwi_fits_reader(full_path)[0]\n # do calibration\n for isl in range(sz[2]):\n for ix in range(sz[1]):\n sky.data[:, ix, isl] *= mscal\n\n # units\n flam16_u = 1.e16 * u.erg / (u.angstrom * u.cm ** 2 * u.s)\n self.action.args.ccddata.unit = flam16_u\n self.action.args.ccddata.uncertainty.unit = flam16_u\n if obj is not None:\n obj.unit = flam16_u\n if sky is not None:\n sky.unit = flam16_u\n # update header keywords\n self.action.args.ccddata.header[key] = (True, keycom)\n self.action.args.ccddata.header['MSFILE'] = (invsname,\n \"Master std filename\")\n self.action.args.ccddata.header['MSIMNO'] = (\n msimgno, 'master std image number')\n else:\n\n self.action.args.ccddata.header[key] = (False, keycom)\n\n log_string = FluxCalibrate.__module__\n self.action.args.ccddata.header['HISTORY'] = log_string\n\n # write out icubes image\n kcwi_fits_writer(self.action.args.ccddata,\n table=self.action.args.table,\n output_file=self.action.args.name,\n output_dir=self.config.instrument.output_directory,\n suffix=\"icubes\")\n self.context.proctab.update_proctab(frame=self.action.args.ccddata,\n suffix=\"icubes\",\n filename=self.action.args.name)\n self.context.proctab.write_proctab()\n\n # check for sky, obj cube\n if obj is not None:\n out_obj = CCDData(obj, meta=self.action.args.ccddata.header,\n unit=self.action.args.ccddata.unit)\n kcwi_fits_writer(\n out_obj, output_file=self.action.args.name,\n output_dir=self.config.instrument.output_directory,\n suffix=\"ocubes\")\n\n if sky is not None:\n out_sky = CCDData(sky, meta=self.action.args.ccddata.header,\n unit=self.action.args.ccddata.unit)\n kcwi_fits_writer(\n out_sky, output_file=self.action.args.name,\n output_dir=self.config.instrument.output_directory,\n suffix=\"scubes\")\n\n self.logger.info(log_string)\n\n return self.action.args\n # END: class FluxCalibrate()\n" ]
[ [ "numpy.arange", "scipy.interpolate.interp1d" ] ]
shmouses/EELSpecNet
[ "a9aa085782a08e903e718012d5ce5979c18f7d23" ]
[ "main.py" ]
[ "import EELSpecNet\nimport GenerateData as gene\nimport tensorflow as tf\nimport numpy as np\nimport tensorflow.experimental.numpy as tnp\ntnp.experimental_enable_numpy_behavior()\n\ndef main():\n\n model = EELSpecNet.EELSpecNetModel_CNN_10D(2048)\n op = tf.keras.optimizers.Adam(learning_rate=5e-5)\n model.compile(optimizer=op, loss='BinaryCrossentropy', metrics=['mape', 'mse'])\n\n train_target, train_initial = gene.training_signal_set(6000, -2, 0.005, 0.015, 2048, 0.05)\n print(\"---------------- Training signal generation done !!! ----------------------\")\n\n tnp_convolved_loaded = tnp.asarray(train_initial)\n tnp_original_loaded = tnp.asarray(train_target)\n x_dim, e_dim = np.shape(train_initial)\n tnp_original_loaded += 0.001\n tnp_convolved_loaded += 0.001\n tnp_data_original = tnp_original_loaded.reshape((x_dim, 1, e_dim, 1))\n tnp_data_convolved = tnp_convolved_loaded.reshape((x_dim, 1, e_dim, 1))\n tnp_train_original = tnp_data_original[:, :, :, :]\n tnp_train_convolved = tnp_data_convolved[:, :, :, :]\n\n model.fit(tnp_train_convolved, tnp_train_original, validation_split=0.16, batch_size=16, epochs=1000)\n print(\"------------------------ Training done !!! ------------------------\")\n\n eval_target, eval_initial, eval_peaks, eval_psf, eval_metadata = gene.eval_signal_set(2000, -2, 0.005, 0.015, 2048,\n 0.05)\n print(\"---------------- Evaluation signal generation done !!! ----------------------\")\n\n eval_target += 0.001\n eval_initial += 0.001\n eval_target = eval_target.reshape((2000, 1, 2048, 1))\n eval_initial = eval_initial.reshape((2000, 1, 2048, 1))\n\n model.evaluate(eval_initial, eval_target)\n prediction = model.predict(eval_initial)\n prediction = prediction.reshape((2000, 2048))\n np.save(\"deconv_evaluation_signal.npy\", prediction)\n\nif __name__ == \"__main__\":\n main()" ]
[ [ "numpy.save", "tensorflow.keras.optimizers.Adam", "tensorflow.experimental.numpy.asarray", "numpy.shape", "tensorflow.experimental.numpy.experimental_enable_numpy_behavior" ] ]
MarcoGorelli/pymc
[ "75ea2a80cb27773e93b7b207043077953940e6ff" ]
[ "pymc/distributions/shape_utils.py" ]
[ "# Copyright 2021 The PyMC Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# -*- coding: utf-8 -*-\n\"\"\"\nA collection of common shape operations needed for broadcasting\nsamples from probability distributions for stochastic nodes in PyMC.\n\"\"\"\n\nimport warnings\n\nfrom typing import Optional, Sequence, Tuple, Union\n\nimport numpy as np\n\nfrom aesara.graph.basic import Constant, Variable\nfrom aesara.tensor.var import TensorVariable\n\nfrom pymc.aesaraf import change_rv_size, pandas_to_array\nfrom pymc.exceptions import ShapeError, ShapeWarning\n\n__all__ = [\n \"to_tuple\",\n \"shapes_broadcasting\",\n \"broadcast_dist_samples_shape\",\n \"get_broadcastable_dist_samples\",\n \"broadcast_distribution_samples\",\n \"broadcast_dist_samples_to\",\n \"rv_size_is_none\",\n]\n\n\ndef to_tuple(shape):\n \"\"\"Convert ints, arrays, and Nones to tuples\n\n Parameters\n ----------\n shape: None, int or array-like\n Represents the shape to convert to tuple.\n\n Returns\n -------\n If `shape` is None, returns an empty tuple. If it's an int, (shape,) is\n returned. If it is array-like, tuple(shape) is returned.\n \"\"\"\n if shape is None:\n return tuple()\n temp = np.atleast_1d(shape)\n if temp.size == 0:\n return tuple()\n else:\n return tuple(temp)\n\n\ndef _check_shape_type(shape):\n out = []\n try:\n shape = np.atleast_1d(shape)\n for s in shape:\n if isinstance(s, np.ndarray) and s.ndim > 0:\n raise TypeError(f\"Value {s} is not a valid integer\")\n o = int(s)\n if o != s:\n raise TypeError(f\"Value {s} is not a valid integer\")\n out.append(o)\n except Exception:\n raise TypeError(f\"Supplied value {shape} does not represent a valid shape\")\n return tuple(out)\n\n\ndef shapes_broadcasting(*args, raise_exception=False):\n \"\"\"Return the shape resulting from broadcasting multiple shapes.\n Represents numpy's broadcasting rules.\n\n Parameters\n ----------\n *args: array-like of int\n Tuples or arrays or lists representing the shapes of arrays to be\n broadcast.\n raise_exception: bool (optional)\n Controls whether to raise an exception or simply return `None` if\n the broadcasting fails.\n\n Returns\n -------\n Resulting shape. If broadcasting is not possible and `raise_exception` is\n False, then `None` is returned. If `raise_exception` is `True`, a\n `ValueError` is raised.\n \"\"\"\n x = list(_check_shape_type(args[0])) if args else ()\n for arg in args[1:]:\n y = list(_check_shape_type(arg))\n if len(x) < len(y):\n x, y = y, x\n if len(y) > 0:\n x[-len(y) :] = [\n j if i == 1 else i if j == 1 else i if i == j else 0\n for i, j in zip(x[-len(y) :], y)\n ]\n if not all(x):\n if raise_exception:\n raise ValueError(\n \"Supplied shapes {} do not broadcast together\".format(\n \", \".join([f\"{a}\" for a in args])\n )\n )\n else:\n return None\n return tuple(x)\n\n\ndef broadcast_dist_samples_shape(shapes, size=None):\n \"\"\"Apply shape broadcasting to shape tuples but assuming that the shapes\n correspond to draws from random variables, with the `size` tuple possibly\n prepended to it. The `size` prepend is ignored to consider if the supplied\n `shapes` can broadcast or not. It is prepended to the resulting broadcasted\n `shapes`, if any of the shape tuples had the `size` prepend.\n\n Parameters\n ----------\n shapes: Iterable of tuples holding the distribution samples shapes\n size: None, int or tuple (optional)\n size of the sample set requested.\n\n Returns\n -------\n tuple of the resulting shape\n\n Examples\n --------\n .. code-block:: python\n\n size = 100\n shape0 = (size,)\n shape1 = (size, 5)\n shape2 = (size, 4, 5)\n out = broadcast_dist_samples_shape([shape0, shape1, shape2],\n size=size)\n assert out == (size, 4, 5)\n\n .. code-block:: python\n\n size = 100\n shape0 = (size,)\n shape1 = (5,)\n shape2 = (4, 5)\n out = broadcast_dist_samples_shape([shape0, shape1, shape2],\n size=size)\n assert out == (size, 4, 5)\n\n .. code-block:: python\n\n size = 100\n shape0 = (1,)\n shape1 = (5,)\n shape2 = (4, 5)\n out = broadcast_dist_samples_shape([shape0, shape1, shape2],\n size=size)\n assert out == (4, 5)\n \"\"\"\n if size is None:\n broadcasted_shape = shapes_broadcasting(*shapes)\n if broadcasted_shape is None:\n raise ValueError(\n \"Cannot broadcast provided shapes {} given size: {}\".format(\n \", \".join([f\"{s}\" for s in shapes]), size\n )\n )\n return broadcasted_shape\n shapes = [_check_shape_type(s) for s in shapes]\n _size = to_tuple(size)\n # samples shapes without the size prepend\n sp_shapes = [s[len(_size) :] if _size == s[: min([len(_size), len(s)])] else s for s in shapes]\n try:\n broadcast_shape = shapes_broadcasting(*sp_shapes, raise_exception=True)\n except ValueError:\n raise ValueError(\n \"Cannot broadcast provided shapes {} given size: {}\".format(\n \", \".join([f\"{s}\" for s in shapes]), size\n )\n )\n broadcastable_shapes = []\n for shape, sp_shape in zip(shapes, sp_shapes):\n if _size == shape[: len(_size)]:\n # If size prepends the shape, then we have to add broadcasting axis\n # in the middle\n p_shape = (\n shape[: len(_size)]\n + (1,) * (len(broadcast_shape) - len(sp_shape))\n + shape[len(_size) :]\n )\n else:\n p_shape = shape\n broadcastable_shapes.append(p_shape)\n return shapes_broadcasting(*broadcastable_shapes, raise_exception=True)\n\n\ndef get_broadcastable_dist_samples(\n samples, size=None, must_bcast_with=None, return_out_shape=False\n):\n \"\"\"Get a view of the samples drawn from distributions which adds new axises\n in between the `size` prepend and the distribution's `shape`. These views\n should be able to broadcast the samples from the distrubtions taking into\n account the `size` (i.e. the number of samples) of the draw, which is\n prepended to the sample's `shape`. Optionally, one can supply an extra\n `must_bcast_with` to try to force samples to be able to broadcast with a\n given shape. A `ValueError` is raised if it is not possible to broadcast\n the provided samples.\n\n Parameters\n ----------\n samples: Iterable of ndarrays holding the sampled values\n size: None, int or tuple (optional)\n size of the sample set requested.\n must_bcast_with: None, int or tuple (optional)\n Tuple shape to which the samples must be able to broadcast\n return_out_shape: bool (optional)\n If `True`, this function also returns the output's shape and not only\n samples views.\n\n Returns\n -------\n broadcastable_samples: List of the broadcasted sample arrays\n broadcast_shape: If `return_out_shape` is `True`, the resulting broadcast\n shape is returned.\n\n Examples\n --------\n .. code-block:: python\n\n must_bcast_with = (3, 1, 5)\n size = 100\n sample0 = np.random.randn(size)\n sample1 = np.random.randn(size, 5)\n sample2 = np.random.randn(size, 4, 5)\n out = broadcast_dist_samples_to(\n [sample0, sample1, sample2],\n size=size,\n must_bcast_with=must_bcast_with,\n )\n assert out[0].shape == (size, 1, 1, 1)\n assert out[1].shape == (size, 1, 1, 5)\n assert out[2].shape == (size, 1, 4, 5)\n assert np.all(sample0[:, None, None, None] == out[0])\n assert np.all(sample1[:, None, None] == out[1])\n assert np.all(sample2[:, None] == out[2])\n\n .. code-block:: python\n\n size = 100\n must_bcast_with = (3, 1, 5)\n sample0 = np.random.randn(size)\n sample1 = np.random.randn(5)\n sample2 = np.random.randn(4, 5)\n out = broadcast_dist_samples_to(\n [sample0, sample1, sample2],\n size=size,\n must_bcast_with=must_bcast_with,\n )\n assert out[0].shape == (size, 1, 1, 1)\n assert out[1].shape == (5,)\n assert out[2].shape == (4, 5)\n assert np.all(sample0[:, None, None, None] == out[0])\n assert np.all(sample1 == out[1])\n assert np.all(sample2 == out[2])\n \"\"\"\n samples = [np.asarray(p) for p in samples]\n _size = to_tuple(size)\n must_bcast_with = to_tuple(must_bcast_with)\n # Raw samples shapes\n p_shapes = [p.shape for p in samples] + [_check_shape_type(must_bcast_with)]\n out_shape = broadcast_dist_samples_shape(p_shapes, size=size)\n # samples shapes without the size prepend\n sp_shapes = [\n s[len(_size) :] if _size == s[: min([len(_size), len(s)])] else s for s in p_shapes\n ]\n broadcast_shape = shapes_broadcasting(*sp_shapes, raise_exception=True)\n broadcastable_samples = []\n for param, p_shape, sp_shape in zip(samples, p_shapes, sp_shapes):\n if _size == p_shape[: min([len(_size), len(p_shape)])]:\n # If size prepends the shape, then we have to add broadcasting axis\n # in the middle\n slicer_head = [slice(None)] * len(_size)\n slicer_tail = [np.newaxis] * (len(broadcast_shape) - len(sp_shape)) + [\n slice(None)\n ] * len(sp_shape)\n else:\n # If size does not prepend the shape, then we have leave the\n # parameter as is\n slicer_head = []\n slicer_tail = [slice(None)] * len(sp_shape)\n broadcastable_samples.append(param[tuple(slicer_head + slicer_tail)])\n if return_out_shape:\n return broadcastable_samples, out_shape\n else:\n return broadcastable_samples\n\n\ndef broadcast_distribution_samples(samples, size=None):\n \"\"\"Broadcast samples drawn from distributions taking into account the\n size (i.e. the number of samples) of the draw, which is prepended to\n the sample's shape.\n\n Parameters\n ----------\n samples: Iterable of ndarrays holding the sampled values\n size: None, int or tuple (optional)\n size of the sample set requested.\n\n Returns\n -------\n List of broadcasted sample arrays\n\n Examples\n --------\n .. code-block:: python\n\n size = 100\n sample0 = np.random.randn(size)\n sample1 = np.random.randn(size, 5)\n sample2 = np.random.randn(size, 4, 5)\n out = broadcast_distribution_samples([sample0, sample1, sample2],\n size=size)\n assert all((o.shape == (size, 4, 5) for o in out))\n assert np.all(sample0[:, None, None] == out[0])\n assert np.all(sample1[:, None, :] == out[1])\n assert np.all(sample2 == out[2])\n\n .. code-block:: python\n\n size = 100\n sample0 = np.random.randn(size)\n sample1 = np.random.randn(5)\n sample2 = np.random.randn(4, 5)\n out = broadcast_distribution_samples([sample0, sample1, sample2],\n size=size)\n assert all((o.shape == (size, 4, 5) for o in out))\n assert np.all(sample0[:, None, None] == out[0])\n assert np.all(sample1 == out[1])\n assert np.all(sample2 == out[2])\n \"\"\"\n return np.broadcast_arrays(*get_broadcastable_dist_samples(samples, size=size))\n\n\ndef broadcast_dist_samples_to(to_shape, samples, size=None):\n \"\"\"Broadcast samples drawn from distributions to a given shape, taking into\n account the size (i.e. the number of samples) of the draw, which is\n prepended to the sample's shape.\n\n Parameters\n ----------\n to_shape: Tuple shape onto which the samples must be able to broadcast\n samples: Iterable of ndarrays holding the sampled values\n size: None, int or tuple (optional)\n size of the sample set requested.\n\n Returns\n -------\n List of the broadcasted sample arrays\n\n Examples\n --------\n .. code-block:: python\n\n to_shape = (3, 1, 5)\n size = 100\n sample0 = np.random.randn(size)\n sample1 = np.random.randn(size, 5)\n sample2 = np.random.randn(size, 4, 5)\n out = broadcast_dist_samples_to(\n to_shape,\n [sample0, sample1, sample2],\n size=size\n )\n assert np.all((o.shape == (size, 3, 4, 5) for o in out))\n assert np.all(sample0[:, None, None, None] == out[0])\n assert np.all(sample1[:, None, None] == out[1])\n assert np.all(sample2[:, None] == out[2])\n\n .. code-block:: python\n\n size = 100\n to_shape = (3, 1, 5)\n sample0 = np.random.randn(size)\n sample1 = np.random.randn(5)\n sample2 = np.random.randn(4, 5)\n out = broadcast_dist_samples_to(\n to_shape,\n [sample0, sample1, sample2],\n size=size\n )\n assert np.all((o.shape == (size, 3, 4, 5) for o in out))\n assert np.all(sample0[:, None, None, None] == out[0])\n assert np.all(sample1 == out[1])\n assert np.all(sample2 == out[2])\n \"\"\"\n samples, to_shape = get_broadcastable_dist_samples(\n samples, size=size, must_bcast_with=to_shape, return_out_shape=True\n )\n return [np.broadcast_to(o, to_shape) for o in samples]\n\n\n# User-provided can be lazily specified as scalars\nShape = Union[int, TensorVariable, Sequence[Union[int, TensorVariable, type(Ellipsis)]]]\nDims = Union[str, Sequence[Union[str, None, type(Ellipsis)]]]\nSize = Union[int, TensorVariable, Sequence[Union[int, TensorVariable]]]\n\n# After conversion to vectors\nWeakShape = Union[TensorVariable, Tuple[Union[int, TensorVariable, type(Ellipsis)], ...]]\nWeakDims = Tuple[Union[str, None, type(Ellipsis)], ...]\n\n# After Ellipsis were substituted\nStrongShape = Union[TensorVariable, Tuple[Union[int, TensorVariable], ...]]\nStrongDims = Sequence[Union[str, None]]\nStrongSize = Union[TensorVariable, Tuple[Union[int, TensorVariable], ...]]\n\n\ndef convert_dims(dims: Dims) -> Optional[WeakDims]:\n \"\"\"Process a user-provided dims variable into None or a valid dims tuple.\"\"\"\n if dims is None:\n return None\n\n if isinstance(dims, str):\n dims = (dims,)\n elif isinstance(dims, (list, tuple)):\n dims = tuple(dims)\n else:\n raise ValueError(f\"The `dims` parameter must be a tuple, str or list. Actual: {type(dims)}\")\n\n if any(d == Ellipsis for d in dims[:-1]):\n raise ValueError(f\"Ellipsis in `dims` may only appear in the last position. Actual: {dims}\")\n\n return dims\n\n\ndef convert_shape(shape: Shape) -> Optional[WeakShape]:\n \"\"\"Process a user-provided shape variable into None or a valid shape object.\"\"\"\n if shape is None:\n return None\n\n if isinstance(shape, int) or (isinstance(shape, TensorVariable) and shape.ndim == 0):\n shape = (shape,)\n elif isinstance(shape, (list, tuple)):\n shape = tuple(shape)\n else:\n raise ValueError(\n f\"The `shape` parameter must be a tuple, TensorVariable, int or list. Actual: {type(shape)}\"\n )\n\n if isinstance(shape, tuple) and any(s == Ellipsis for s in shape[:-1]):\n raise ValueError(\n f\"Ellipsis in `shape` may only appear in the last position. Actual: {shape}\"\n )\n\n return shape\n\n\ndef convert_size(size: Size) -> Optional[StrongSize]:\n \"\"\"Process a user-provided size variable into None or a valid size object.\"\"\"\n if size is None:\n return None\n\n if isinstance(size, int) or (isinstance(size, TensorVariable) and size.ndim == 0):\n size = (size,)\n elif isinstance(size, (list, tuple)):\n size = tuple(size)\n else:\n raise ValueError(\n f\"The `size` parameter must be a tuple, TensorVariable, int or list. Actual: {type(size)}\"\n )\n\n if isinstance(size, tuple) and Ellipsis in size:\n raise ValueError(f\"The `size` parameter cannot contain an Ellipsis. Actual: {size}\")\n\n return size\n\n\ndef resize_from_dims(\n dims: WeakDims, ndim_implied: int, model\n) -> Tuple[int, StrongSize, StrongDims]:\n \"\"\"Determines a potential resize shape from a `dims` tuple.\n\n Parameters\n ----------\n dims : array-like\n A vector of dimension names, None or Ellipsis.\n ndim_implied : int\n Number of RV dimensions that were implied from its inputs alone.\n model : pm.Model\n The current model on stack.\n\n Returns\n -------\n ndim_resize : int\n Number of dimensions that should be added through resizing.\n resize_shape : array-like\n The shape of the new dimensions.\n \"\"\"\n if Ellipsis in dims:\n # Auto-complete the dims tuple to the full length.\n # We don't have a way to know the names of implied\n # dimensions, so they will be `None`.\n dims = (*dims[:-1], *[None] * ndim_implied)\n\n ndim_resize = len(dims) - ndim_implied\n\n # All resize dims must be known already (numerically or symbolically).\n unknowndim_resize_dims = set(dims[:ndim_resize]) - set(model.dim_lengths)\n if unknowndim_resize_dims:\n raise KeyError(\n f\"Dimensions {unknowndim_resize_dims} are unknown to the model and cannot be used to specify a `size`.\"\n )\n\n # The numeric/symbolic resize tuple can be created using model.RV_dim_lengths\n resize_shape = tuple(model.dim_lengths[dname] for dname in dims[:ndim_resize])\n return ndim_resize, resize_shape, dims\n\n\ndef resize_from_observed(\n observed, ndim_implied: int\n) -> Tuple[int, StrongSize, Union[np.ndarray, Variable]]:\n \"\"\"Determines a potential resize shape from observations.\n\n Parameters\n ----------\n observed : scalar, array-like\n The value of the `observed` kwarg to the RV creation.\n ndim_implied : int\n Number of RV dimensions that were implied from its inputs alone.\n\n Returns\n -------\n ndim_resize : int\n Number of dimensions that should be added through resizing.\n resize_shape : array-like\n The shape of the new dimensions.\n observed : scalar, array-like\n Observations as numpy array or `Variable`.\n \"\"\"\n if not hasattr(observed, \"shape\"):\n observed = pandas_to_array(observed)\n ndim_resize = observed.ndim - ndim_implied\n resize_shape = tuple(observed.shape[d] for d in range(ndim_resize))\n return ndim_resize, resize_shape, observed\n\n\ndef find_size(shape=None, size=None, ndim_supp=None):\n \"\"\"Determines the size keyword argument for creating a Distribution.\n\n Parameters\n ----------\n shape : tuple\n A tuple specifying the final shape of a distribution\n size : tuple\n A tuple specifying the size of a distribution\n ndim_supp : int\n The support dimension of the distribution.\n 0 if a univariate distribution, 1 if a multivariate distribution.\n\n Returns\n -------\n create_size : int\n The size argument to be passed to the distribution\n ndim_expected : int\n Number of dimensions expected after distribution was created\n ndim_batch : int\n Number of batch dimensions\n ndim_supp : int\n Number of support dimensions\n \"\"\"\n\n ndim_expected = None\n ndim_batch = None\n create_size = None\n\n if shape is not None:\n if Ellipsis in shape:\n # Ellipsis short-hands all implied dimensions. Therefore\n # we don't know how many dimensions to expect.\n ndim_expected = ndim_batch = None\n # Create the RV with its implied shape and resize later\n create_size = None\n else:\n ndim_expected = len(tuple(shape))\n ndim_batch = ndim_expected - ndim_supp\n create_size = tuple(shape)[:ndim_batch]\n elif size is not None:\n ndim_expected = ndim_supp + len(tuple(size))\n ndim_batch = ndim_expected - ndim_supp\n create_size = size\n\n return create_size, ndim_expected, ndim_batch, ndim_supp\n\n\ndef maybe_resize(\n rv_out,\n rv_op,\n dist_params,\n ndim_expected,\n ndim_batch,\n ndim_supp,\n shape,\n size,\n **kwargs,\n):\n \"\"\"Resize a distribution if necessary.\n\n Parameters\n ----------\n rv_out : RandomVariable\n The RandomVariable to be resized if necessary\n rv_op : RandomVariable.__class__\n The RandomVariable class to recreate it\n dist_params : dict\n Input parameters to recreate the RandomVariable\n ndim_expected : int\n Number of dimensions expected after distribution was created\n ndim_batch : int\n Number of batch dimensions\n ndim_supp : int\n The support dimension of the distribution.\n 0 if a univariate distribution, 1 if a multivariate distribution.\n shape : tuple\n A tuple specifying the final shape of a distribution\n size : tuple\n A tuple specifying the size of a distribution\n\n Returns\n -------\n rv_out : int\n The size argument to be passed to the distribution\n \"\"\"\n ndim_actual = rv_out.ndim\n ndims_unexpected = ndim_actual != ndim_expected\n\n if shape is not None and ndims_unexpected:\n if Ellipsis in shape:\n # Resize and we're done!\n rv_out = change_rv_size(rv_var=rv_out, new_size=shape[:-1], expand=True)\n else:\n # This is rare, but happens, for example, with MvNormal(np.ones((2, 3)), np.eye(3), shape=(2, 3)).\n # Recreate the RV without passing `size` to created it with just the implied dimensions.\n rv_out = rv_op(*dist_params, size=None, **kwargs)\n\n # Now resize by any remaining \"extra\" dimensions that were not implied from support and parameters\n if rv_out.ndim < ndim_expected:\n expand_shape = shape[: ndim_expected - rv_out.ndim]\n rv_out = change_rv_size(rv_var=rv_out, new_size=expand_shape, expand=True)\n if not rv_out.ndim == ndim_expected:\n raise ShapeError(\n f\"Failed to create the RV with the expected dimensionality. \"\n f\"This indicates a severe problem. Please open an issue.\",\n actual=ndim_actual,\n expected=ndim_batch + ndim_supp,\n )\n\n # Warn about the edge cases where the RV Op creates more dimensions than\n # it should based on `size` and `RVOp.ndim_supp`.\n if size is not None and ndims_unexpected:\n warnings.warn(\n f\"You may have expected a ({len(tuple(size))}+{ndim_supp})-dimensional RV, but the resulting RV will be {ndim_actual}-dimensional.\"\n ' To silence this warning use `warnings.simplefilter(\"ignore\", pm.ShapeWarning)`.',\n ShapeWarning,\n )\n\n return rv_out\n\n\ndef rv_size_is_none(size: Variable) -> bool:\n \"\"\"Check wether an rv size is None (ie., at.Constant([]))\"\"\"\n return isinstance(size, Constant) and size.data.size == 0\n" ]
[ [ "numpy.broadcast_to", "numpy.asarray", "numpy.atleast_1d" ] ]
zouguojian/FDN-Learning
[ "ef89cb7d6654d5ac2425621ec6b330652a281f16" ]
[ "data_/data_save.py" ]
[ "# -- coding: utf-8 --\n\nimport os\nimport csv\n\ndef go_though(open_file):\n for root, dirs, files in os.walk(r''+str(open_file)):\n for file in files:\n # # 获取文件所属目录\n # print(root)\n # 获取文件路径\n print(os.path.join(root, file))\n\ndef re_hour(hour):\n if len(str(hour))<2:return '0'+str(hour)\n else:return str(hour)\n\ndef re_month(month):\n if len(str(month))<2:return '0'+str(month)\n else:return str(month)\n\ndef re_day(day):\n if len(str(day))<2:return '0'+str(day)\n else:return str(day)\n\nfrom datetime import datetime\ndef re_time(time_list): #[year,month,day,hour]\n time =''.join([time_list[i]+'-' for i in range(len(time_list))]).strip('-')\n time = datetime.strptime(time, '%Y-%m-%d-%H')\n return time\n\nimport numpy as np\ndef witer_(open_file,day,month,year,format,writer):\n for d in range(day, 32):\n if os.path.exists(open_file + year + re_month(month) + re_day(d) + format):\n read = pd.read_csv(open_file + year + re_month(month) + re_day(d) + format)\n print(list(np.reshape(sites[:,0],newshape=(-1))))\n data=read[list(sites[:,0])]\n # return read.loc[read['城市'] == '上海'].values\n # print(open_file + year + re_month(month) + re_day(d) + format)\n\ndef go_though(open_file,day,month,year,format,write_file,write_name):\n file = open(write_file+write_name, 'w', encoding='utf-8')\n writer=csv.writer(file)\n writer.writerow(data_colum)\n for m in range(month,13):\n if day!=1:\n witer_(open_file, day, m, year, format, writer)\n day=1\n else:\n witer_(open_file, day, m, year, format, writer)\n file.close()\n return\n\nimport pandas as pd\ndef read_site(file):\n read=pd.read_excel(file)\n print(list(read.keys()))\n return read.loc[read['城市']=='上海'].values\n\ndata_colum=['time','site','AQI','PM2.5','PM2.5_24h','PM10','PM10_24h','SO2','SO2_24h','NO2','NO2_24h','O3','O3_24h','O3_8h','O3_8h_24h','CO','CO_24h']\nopen_file='/Users/guojianzou/Downloads/站点_20200101-20201231/china_sites_'\nopen_site='/Users/guojianzou/Downloads/站点列表-2021.01.01起.xlsx'\nwrite_file='/Users/guojianzou/Downloads/'\nwrite_name='2020.csv'\nday=5\nmonth=1\nyear='2020'\n\n#读取站点信息,包括:['监测点编码', '监测点名称', '城市', '经度', '纬度', '对照点']\nsites=read_site(open_site)\nprint(sites)\n\n# 遍历数据源,并开始存储\ngo_though(open_file,day,month,year,'.csv',write_file,write_name)\n" ]
[ [ "pandas.read_excel", "numpy.reshape" ] ]
rcaneill/xgcm-1
[ "b68a4c70fdb8ade2e7462a958c810a07b0fbcfdb" ]
[ "xgcm/test/test_metrics_ops_single_axis.py" ]
[ "from __future__ import print_function\nimport pytest\nimport xarray as xr\nimport numpy as np\n\nfrom xgcm.grid import Grid, Axis\nfrom xgcm.test.datasets import datasets_grid_metric\n\n\[email protected](\"funcname\", [\"interp\", \"diff\", \"min\", \"max\", \"cumsum\"])\[email protected](\"grid_type\", [\"B\", \"C\"])\[email protected](\"variable\", [\"tracer\", \"u\", \"v\"])\nclass TestParametrized:\n @pytest.mark.parametrize(\"axis\", [\"X\", \"Y\"])\n @pytest.mark.parametrize(\"metric_weighted\", [\"X\", (\"Y\",), (\"X\", \"Y\"), [\"X\", \"Y\"]])\n @pytest.mark.parametrize(\n \"periodic\", [\"True\", \"False\", {\"X\": True, \"Y\": False}, {\"X\": False, \"Y\": True}]\n )\n @pytest.mark.parametrize(\"boundary\", [\"fill\", \"extend\"])\n def test_weighted_metric(\n self, funcname, grid_type, variable, axis, metric_weighted, periodic, boundary\n ):\n \"\"\"tests the correct execution of weighted ops along a single axis\"\"\"\n # metric_weighted allows the interpolation of e.g. a surface flux to be conservative\n # It multiplies the values with a metric like the area, then performs interpolation\n # and divides by the same metric (area) for the new grid position\n ds, coords, metrics = datasets_grid_metric(grid_type)\n grid = Grid(ds, coords=coords, metrics=metrics, periodic=periodic)\n func = getattr(grid, funcname)\n\n metric = grid.get_metric(ds[variable], metric_weighted)\n expected_raw = func(ds[variable] * metric, axis, boundary=boundary)\n metric_new = grid.get_metric(expected_raw, metric_weighted)\n expected = expected_raw / metric_new\n new = func(\n ds[variable], axis, metric_weighted=metric_weighted, boundary=boundary\n )\n assert new.equals(expected)\n\n @pytest.mark.parametrize(\n \"multi_axis\", [\"X\", [\"X\"], (\"Y\"), [\"X\", \"Y\"], (\"Y\", \"X\")]\n )\n def test_weighted_metric_multi_axis(\n self, funcname, grid_type, variable, multi_axis, metric_weighted, boundary\n ):\n \"\"\"tests if the output for multiple axis is the same as when\n executing the single axis ops in serial\"\"\"\n ds, coords, metrics = datasets_grid_metric(grid_type)\n grid = Grid(ds, coords=coords, metrics=metrics)\n\n func = getattr(grid, funcname)\n expected = ds[variable]\n for ax in multi_axis:\n if isinstance(metric_weighted, dict):\n metric_weighted_axis = metric_weighted[ax]\n else:\n metric_weighted_axis = metric_weighted\n expected = func(\n expected,\n ax,\n metric_weighted=metric_weighted_axis,\n boundary=boundary,\n )\n\n new = func(\n ds[variable],\n multi_axis,\n metric_weighted=metric_weighted,\n boundary=boundary,\n )\n assert new.equals(expected)\n\n\[email protected](\n \"funcname\",\n [\"interp\", \"diff\", \"min\", \"max\", \"cumsum\", \"derivative\", \"cumint\"],\n)\[email protected](\"boundary\", [\"fill\", \"extend\"])\[email protected](\"fill_value\", [0, 10, None])\ndef test_boundary_global_input(funcname, boundary, fill_value):\n \"\"\"Test that globally defined boundary values result in\n the same output as when the parameters are defined on either\n the grid or axis methods\n \"\"\"\n ds, coords, metrics = datasets_grid_metric(\"C\")\n axis = \"X\"\n\n # Test results by globally specifying fill value/boundary on grid object\n grid_global = Grid(\n ds,\n coords=coords,\n metrics=metrics,\n periodic=False,\n boundary=boundary,\n fill_value=fill_value,\n )\n func_global = getattr(grid_global, funcname)\n global_result = func_global(ds.tracer, axis)\n\n # Test results by manually specifying fill value/boundary on grid method\n grid_manual = Grid(\n ds, coords=coords, metrics=metrics, periodic=False, boundary=boundary\n )\n func_manual = getattr(grid_manual, funcname)\n manual_result = func_manual(\n ds.tracer, axis, boundary=boundary, fill_value=fill_value\n )\n xr.testing.assert_allclose(global_result, manual_result)\n\n\ndef test_average_unmatched_missing():\n # Tests the behavior of grid.average on an array which has missing values, not present in the metric\n x = np.arange(10)\n data = xr.DataArray(np.ones(10), dims=\"x\", coords={\"x\": x})\n weights = data * 30\n ds = xr.Dataset({\"data\": data})\n ds = ds.assign_coords(weights=weights)\n # create an xgcm grid\n grid = Grid(ds, coords={\"X\": {\"center\": \"x\"}}, metrics={\"X\": [\"weights\"]})\n\n # average the unmasked array\n expected = grid.average(ds.data, \"X\")\n\n # now lets introduce a missing value in the data\n ds.data[6:8] = np.nan\n\n # assert that the result for both the full and the masked array is equal,\n # since both only have ones in them.\n xr.testing.assert_allclose(expected, grid.average(ds.data, \"X\"))\n\n\ndef test_derivative_uniform_grid():\n # this is a uniform grid\n # a non-uniform grid would provide a more rigorous test\n dx = 10.0\n dy = 10.0\n arr = [\n [1.0, 2.0, 4.0, 3.0],\n [4.0, 7.0, 1.0, 2.0],\n [3.0, 1.0, 0.0, 9.0],\n [8.0, 5.0, 2.0, 1.0],\n ]\n ds = xr.Dataset(\n {\"foo\": ((\"XC\", \"YC\"), arr)},\n coords={\n \"XC\": ((\"XC\",), [0.5, 1.5, 2.5, 3.5]),\n \"XG\": ((\"XG\",), [0, 1.0, 2.0, 3.0]),\n \"dXC\": ((\"XC\",), [dx, dx, dx, dx]),\n \"dXG\": ((\"XG\",), [dx, dx, dx, dx]),\n \"YC\": ((\"YC\",), [0.5, 1.5, 2.5, 3.5]),\n \"YG\": ((\"YG\",), [0, 1.0, 2.0, 3.0]),\n \"dYC\": ((\"YC\",), [dy, dy, dy, dy]),\n \"dYG\": ((\"YG\",), [dy, dy, dy, dy]),\n },\n )\n\n grid = Grid(\n ds,\n coords={\n \"X\": {\"center\": \"XC\", \"left\": \"XG\"},\n \"Y\": {\"center\": \"YC\", \"left\": \"YG\"},\n },\n metrics={(\"X\",): [\"dXC\", \"dXG\"], (\"Y\",): [\"dYC\", \"dYG\"]},\n periodic=True,\n )\n\n # Test x direction\n dfoo_dx = grid.derivative(ds.foo, \"X\")\n expected = grid.diff(ds.foo, \"X\") / dx\n assert dfoo_dx.equals(expected)\n\n # Test y direction\n dfoo_dy = grid.derivative(ds.foo, \"Y\")\n expected = grid.diff(ds.foo, \"Y\") / dy\n assert dfoo_dy.equals(expected)\n\n\ndef test_derivative_c_grid():\n # test derivatives with synthetic C grid data\n\n ds, coords, metrics = datasets_grid_metric(\"C\")\n grid = Grid(ds, coords=coords, metrics=metrics)\n\n # tracer point\n var = \"tracer\"\n test_axes = [\"X\", \"Y\", \"Z\"]\n test_dx = [\"dx_e\", \"dy_n\", \"dz_w\"]\n for ax, dx in zip(test_axes, test_dx):\n _run_single_derivative_test(grid, ax, ds[var], ds[dx])\n\n # zonal velocity point\n var = \"u\"\n test_dx = [\"dx_t\", \"dy_ne\", \"dz_w_e\"]\n for ax, dx in zip(test_axes, test_dx):\n _run_single_derivative_test(grid, ax, ds[var], ds[dx])\n\n # meridional velocity point\n var = \"v\"\n test_dx = [\"dx_ne\", \"dy_t\", \"dz_w_n\"]\n for ax, dx in zip(test_axes, test_dx):\n _run_single_derivative_test(grid, ax, ds[var], ds[dx])\n\n # vertical velocity point\n var = \"wt\"\n test_dx = [\"dx_e\", \"dy_n\", \"dz_t\"]\n for ax, dx in zip(test_axes, test_dx):\n _run_single_derivative_test(grid, ax, ds[var], ds[dx])\n\n\ndef test_derivative_b_grid():\n # test derivatives with synthetic B grid data\n\n ds, coords, metrics = datasets_grid_metric(\"B\")\n grid = Grid(ds, coords=coords, metrics=metrics)\n\n # tracer point\n var = \"tracer\"\n test_axes = [\"X\", \"Y\", \"Z\"]\n test_dx = [\"dx_e\", \"dy_n\", \"dz_w\"]\n for ax, dx in zip(test_axes, test_dx):\n _run_single_derivative_test(grid, ax, ds[var], ds[dx])\n\n # zonal velocity point\n var = \"u\"\n test_dx = [\"dx_n\", \"dy_e\", \"dz_w_ne\"]\n for ax, dx in zip(test_axes, test_dx):\n _run_single_derivative_test(grid, ax, ds[var], ds[dx])\n\n # meridional velocity point\n var = \"v\"\n test_dx = [\"dx_n\", \"dy_e\", \"dz_w_ne\"]\n for ax, dx in zip(test_axes, test_dx):\n _run_single_derivative_test(grid, ax, ds[var], ds[dx])\n\n # vertical velocity point\n var = \"wt\"\n test_dx = [\"dx_e\", \"dy_n\", \"dz_t\"]\n for ax, dx in zip(test_axes, test_dx):\n _run_single_derivative_test(grid, ax, ds[var], ds[dx])\n\n\n# run this for each axis and each field in dataset\ndef _run_single_derivative_test(grid, axis, fld, dx):\n\n dvar_dx = grid.derivative(fld, axis)\n expected = grid.diff(fld, axis) / dx\n\n assert dvar_dx.equals(expected.reset_coords(drop=True))\n" ]
[ [ "numpy.arange", "numpy.ones" ] ]
syth0le/mat_mod_labs
[ "9c87e771beb75566bb824e34f4520e8b2ca0a4ce" ]
[ "lab_2/graphics.py" ]
[ "import numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy import interpolate\nfrom abc import ABCMeta, abstractmethod\n\nfrom utils.sorting import bubble_sort\n\n\nclass ABSMethods(metaclass=ABCMeta):\n def __init__(self, function):\n self.function = function\n\n @abstractmethod\n def drawGraphic(self, vectors):\n pass\n\n\nclass Lagranz(ABSMethods):\n\n def __call__(self, *args, **kwargs):\n call = self.function()\n self.drawGraphic(call)\n return call\n\n def counter(self, x, y, xl):\n z = 0\n for j in range(len(y)):\n p1 = 1\n p2 = 1\n for i in range(len(x)):\n if i == j:\n p1 = p1 * 1\n p2 = p2 * 1\n else:\n p1 = p1 * (xl - x[i])\n p2 = p2 * (x[j] - x[i])\n z = z + y[j] * p1 / p2\n return z\n\n def drawGraphic(self, vectors):\n\n for vector in vectors:\n vector = bubble_sort(vector)\n x = vector[0]\n y = vector[1]\n xl = np.linspace(np.min(x), np.max(x))\n yl = self.counter(x, y, xl)\n plt.scatter(x, y)\n plt.plot(xl, yl)\n\n plt.xlabel('x')\n plt.ylabel('y')\n plt.title(\"Lagranz Method\")\n plt.show()\n\n\nclass InterpolationLinear(ABSMethods):\n\n def __call__(self, *args, **kwargs):\n call = self.function()\n self.drawGraphic(call)\n return call\n\n def counter(self, x, y, xl):\n yx = 0\n for i in range(len(x)):\n if x[i - 1] <= xl <= x[i]:\n yp = y[i] - y[i - 1]\n xp = x[i] - x[i - 1]\n yx = y[i] + ((yp / xp) * (xl - x[i]))\n break\n return yx\n\n def drawGraphic(self, vectors):\n for vector in vectors:\n vector = bubble_sort(vector)\n x = vector[0]\n y = vector[1]\n yl = [self.counter(x, y, i) for i in x]\n plt.scatter(x, y)\n plt.plot(x, yl)\n\n plt.xlabel('x')\n plt.ylabel('y')\n plt.title(\"Piecewise linear interpolation Method\")\n plt.show()\n\n\nclass InterpolationParabolic(ABSMethods):\n\n def __call__(self, *args, **kwargs):\n call = self.function()\n self.drawGraphic(call)\n return call\n\n def counter(self, x, y, t):\n z = 0\n for i in range(len(x) - 1):\n if x[i] <= t <= x[i + 1]:\n M = np.array(\n [[x[i - 1] ** 2, x[i - 1], 1], [x[i] ** 2, x[i], 1], [x[i + 1] ** 2, x[i + 1], 1]])\n v = np.array([y[i - 1], y[i], y[i + 1]])\n solve = np.linalg.solve(M, v)\n z = solve[0] * t ** 2 + solve[1] * t + solve[2]\n i += 1\n return z\n\n def drawGraphic(self, vectors):\n for vector in vectors:\n vector = bubble_sort(vector)\n x = vector[0]\n y = vector[1]\n plt.scatter(x, y)\n xnew = np.linspace(np.min(x), np.max(x), 10000)\n ynew = [self.counter(x, y, i) for i in xnew]\n plt.plot(xnew, ynew)\n plt.xlabel('x')\n plt.ylabel('y')\n plt.title(\"Piecewise parabolic interpolation Method\")\n plt.show()\n\n\nclass InterpolationSpline(ABSMethods):\n\n def __call__(self, *args, **kwargs):\n call = self.function()\n self.drawGraphic(call)\n return call\n\n def counter(self, x, y):\n tck = interpolate.splrep(x, y, s=0)\n xl = np.linspace(np.min(x), np.max(x))\n yl = interpolate.splev(xl, tck, der=0)\n return xl, yl\n\n def drawGraphic(self, vectors):\n for vector in vectors:\n vector = bubble_sort(vector)\n x = vector[0]\n y = vector[1]\n xl, yl = self.counter(x, y)\n plt.scatter(x, y)\n plt.plot(xl, yl)\n\n plt.xlabel('x')\n plt.ylabel('y')\n plt.title(\"Spline interpolation Method\")\n plt.show()\n\n\nclass Graphics(ABSMethods):\n\n def __call__(self, *args, **kwargs):\n # call = self.function()\n # print(call)\n call = 0\n self.drawGraphic(call)\n return call\n\n def drawGraphic(self, call):\n print(\"\\n1 - Lagranz\\n2 - Linear\\n3 - Parabolic\\n4 - Spline\")\n command = int(input(\"Введите номер задания (из методички):\"))\n if command == 1:\n meth = Lagranz(self.function)\n meth()\n elif command == 2:\n meth = InterpolationLinear(self.function)\n meth()\n elif command == 3:\n meth = InterpolationParabolic(self.function)\n meth()\n elif command == 4:\n meth = InterpolationSpline(self.function)\n meth()\n else:\n print(\"Invalid command\")\n" ]
[ [ "numpy.linalg.solve", "matplotlib.pyplot.title", "scipy.interpolate.splev", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "scipy.interpolate.splrep", "numpy.min", "numpy.max", "numpy.array", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.scatter" ] ]
w86763777/Pytorch-Unified-FID-IS-Score
[ "6a2620d6da0faa66bb798aa47c7e0e49ef2032b6" ]
[ "pytorch_gan_metrics/calc_fid_stats.py" ]
[ "import argparse\nimport os\n\nimport numpy as np\nfrom torch.utils.data import DataLoader\n\nfrom . import ImageDataset\nfrom .core import get_inception_feature\n\n\ndef calc_and_save_stats(path, output, batch_size):\n dataset = ImageDataset(path, exts=['png', 'jpg'])\n loader = DataLoader(dataset, batch_size=batch_size, num_workers=4)\n acts, = get_inception_feature(loader, dims=[2048], verbose=True)\n\n mu = np.mean(acts, axis=0)\n sigma = np.cov(acts, rowvar=False)\n\n if os.path.dirname(output) != \"\":\n os.makedirs(os.path.dirname(output), exist_ok=True)\n np.savez_compressed(output, mu=mu, sigma=sigma)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\"Pre-calculate statistics of images\")\n parser.add_argument(\"--path\", type=str, required=True,\n help='path to image directory')\n parser.add_argument(\"--output\", type=str, required=True,\n help=\"output path\")\n parser.add_argument(\"--batch_size\", type=int, default=50,\n help=\"batch size (default=50)\")\n args = parser.parse_args()\n\n calc_and_save_stats(args.path, args.output, args.batch_size)\n" ]
[ [ "torch.utils.data.DataLoader", "numpy.cov", "numpy.mean", "numpy.savez_compressed" ] ]
NeelGhoshal/probability
[ "df96f3d56eff92c6b06fbac68dc58e095e28fed6" ]
[ "tensorflow_probability/python/math/psd_kernels/exponentiated_quadratic.py" ]
[ "# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"The ExponentiatedQuadratic kernel.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.internal import assert_util\nfrom tensorflow_probability.python.internal import tensor_util\nfrom tensorflow_probability.python.math.psd_kernels import positive_semidefinite_kernel as psd_kernel\nfrom tensorflow_probability.python.math.psd_kernels.internal import util\n\n\n__all__ = ['ExponentiatedQuadratic']\n\n\nclass ExponentiatedQuadratic(psd_kernel.AutoCompositeTensorPsdKernel):\n \"\"\"The ExponentiatedQuadratic kernel.\n\n Sometimes called the \"squared exponential\", \"Gaussian\" or \"radial basis\n function\", this kernel function has the form\n\n ```none\n k(x, y) = amplitude**2 * exp(-||x - y||**2 / (2 * length_scale**2))\n ```\n\n where the double-bars represent vector length (ie, Euclidean, or L2 norm).\n \"\"\"\n\n def __init__(self,\n amplitude=None,\n length_scale=None,\n feature_ndims=1,\n validate_args=False,\n name='ExponentiatedQuadratic'):\n \"\"\"Construct an ExponentiatedQuadratic kernel instance.\n\n Args:\n amplitude: floating point `Tensor` that controls the maximum value\n of the kernel. Must be broadcastable with `length_scale` and inputs to\n `apply` and `matrix` methods. Must be greater than zero. A value of\n `None` is treated like 1.\n Default value: None\n length_scale: floating point `Tensor` that controls how sharp or wide the\n kernel shape is. This provides a characteristic \"unit\" of length against\n which `||x - y||` can be compared for scale. Must be broadcastable with\n `amplitude` and inputs to `apply` and `matrix` methods. A value of\n `None` is treated like 1.\n Default value: None\n feature_ndims: Python `int` number of rightmost dims to include in the\n squared difference norm in the exponential.\n validate_args: If `True`, parameters are checked for validity despite\n possibly degrading runtime performance\n name: Python `str` name prefixed to Ops created by this class.\n \"\"\"\n parameters = dict(locals())\n with tf.name_scope(name):\n dtype = util.maybe_get_common_dtype(\n [amplitude, length_scale])\n self._amplitude = tensor_util.convert_nonref_to_tensor(\n amplitude, name='amplitude', dtype=dtype)\n self._length_scale = tensor_util.convert_nonref_to_tensor(\n length_scale, name='length_scale', dtype=dtype)\n super(ExponentiatedQuadratic, self).__init__(\n feature_ndims,\n dtype=dtype,\n name=name,\n validate_args=validate_args,\n parameters=parameters)\n\n @property\n def amplitude(self):\n \"\"\"Amplitude parameter.\"\"\"\n return self._amplitude\n\n @property\n def length_scale(self):\n \"\"\"Length scale parameter.\"\"\"\n return self._length_scale\n\n def _batch_shape(self):\n scalar_shape = tf.TensorShape([])\n return tf.broadcast_static_shape(\n scalar_shape if self.amplitude is None else self.amplitude.shape,\n scalar_shape if self.length_scale is None else self.length_scale.shape)\n\n def _batch_shape_tensor(self):\n return tf.broadcast_dynamic_shape(\n [] if self.amplitude is None else tf.shape(self.amplitude),\n [] if self.length_scale is None else tf.shape(self.length_scale))\n\n def _apply_with_distance(\n self, x1, x2, pairwise_square_distance, example_ndims=0):\n exponent = -0.5 * pairwise_square_distance\n if self.length_scale is not None:\n length_scale = tf.convert_to_tensor(self.length_scale)\n length_scale = util.pad_shape_with_ones(\n length_scale, example_ndims)\n exponent = exponent / length_scale**2\n\n if self.amplitude is not None:\n amplitude = tf.convert_to_tensor(self.amplitude)\n amplitude = util.pad_shape_with_ones(amplitude, example_ndims)\n exponent = exponent + 2. * tf.math.log(amplitude)\n\n return tf.exp(exponent)\n\n def _apply(self, x1, x2, example_ndims=0):\n pairwise_square_distance = util.sum_rightmost_ndims_preserving_shape(\n tf.math.squared_difference(x1, x2), self.feature_ndims)\n return self._apply_with_distance(\n x1, x2, pairwise_square_distance, example_ndims=example_ndims)\n\n def _matrix(self, x1, x2):\n pairwise_square_distance = util.pairwise_square_distance_matrix(\n x1, x2, self.feature_ndims)\n return self._apply_with_distance(\n x1, x2, pairwise_square_distance, example_ndims=2)\n\n def _tensor(self, x1, x2, x1_example_ndims, x2_example_ndims):\n pairwise_square_distance = util.pairwise_square_distance_tensor(\n x1, x2, self.feature_ndims, x1_example_ndims, x2_example_ndims)\n return self._apply_with_distance(\n x1, x2, pairwise_square_distance,\n example_ndims=(x1_example_ndims + x2_example_ndims))\n\n def _parameter_control_dependencies(self, is_init):\n if not self.validate_args:\n return []\n assertions = []\n for arg_name, arg in dict(amplitude=self.amplitude,\n length_scale=self.length_scale).items():\n if arg is not None and is_init != tensor_util.is_ref(arg):\n assertions.append(assert_util.assert_positive(\n arg,\n message='{} must be positive.'.format(arg_name)))\n return assertions\n" ]
[ [ "tensorflow.compat.v2.exp", "tensorflow.compat.v2.shape", "tensorflow.compat.v2.convert_to_tensor", "tensorflow.compat.v2.math.squared_difference", "tensorflow.compat.v2.TensorShape", "tensorflow.compat.v2.name_scope", "tensorflow.compat.v2.broadcast_static_shape", "tensorflow.compat.v2.math.log" ] ]
jonaswagner2826/MECH6327
[ "2b55aaf6f9e1bcf5cc684f5c853cadec26acf9d2" ]
[ "InClass&Examples/InClass_20210303.py" ]
[ "\n\n\n\"\"\"\nIn Class Ex:\nConstrained \\infty-norm minimization\n\nProblem:\n minimize:\n \\norm{x}_\\infty\n subject to:\n A x \\leq b\n\nNotes:\n \\norm{x}_\\infty = \\max_i \\abs{x_i}\n = \\max_i \\{x_i, -x_i\\}\n = \\max_i \\{x_1, \\dots, x_n, -x_1, \\dots, -x_n\\}\n\nEpigraph Form:\n minimize:\n t\n subject to:\n \\max_i \\{x_1, \\dots, x_n, -x_1, \\dots, -x_n\\} \\leq t\n Ax \\leq b\n\nEquivelent Form:\n minimize:\n t\n subject to:\n x_i \\leq t, i = 1, \\dots, n\n -x_i \\leq t, i = 1, \\dots, n\n Ax \\leq b\n\nEquivelent Form:\n minimize:\n t\n subject to:\n - 1 t \\leq x \\leq 1 t\n Ax \\leq b\n\"\"\"\n\n\nimport cvxpy as cp\nimport numpy as np\n\n\nn = 10\nm = 100\n\nA = np.random.rand(m, n)\nb = np.random.rand(m, 1) - 1\n\n\nX = cp.Variable((n, n))\nprob = cp.Problem(cp.Minimize(cp.max(cp.sum(cp.abs(X)))),\n [A @ X <= b])\n\n\n# Print result.\nprint(\"The optimal value is\", prob.value)\nprint(\"A solution X is\")\nprint(X.value)\n\n\n# doesn't work..... don't really feel like troubleshooting though\n" ]
[ [ "numpy.random.rand" ] ]
yotamitai/Agent-Disagreements
[ "858583db448c5621273824527f1f4181ebf55a2b" ]
[ "disagreements/disagreement.py" ]
[ "from copy import deepcopy\n\nimport cv2\nimport imageio\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom os.path import join\nfrom PIL import ImageFont, ImageDraw, Image\n\nfrom disagreements.common.utils import make_clean_dirs, save_image, create_video\nfrom disagreements.logging_info import log\nfrom disagreements.get_trajectories import trajectory_importance_max_min\n\n\ndef get_trajectories(trace):\n \"\"\"for each trajectory of agent 2 - find corresponding trajectory of agent 1\"\"\"\n for i, a2_traj in enumerate(trace.a2_trajectories):\n start_idx, end_idx = a2_traj[0].id[1], a2_traj[-1].id[1]\n a1_traj = trace.states[start_idx:end_idx + 1]\n a1_traj_q_values = [x.action_values for x in a1_traj]\n a2_traj_q_values = [x.action_values for x in a2_traj]\n a1_traj_indexes = [x.id[1] for x in a1_traj]\n a2_traj_indexes = list(range(start_idx, end_idx + 1))\n dt = DisagreementTrajectory(trace.disagreement_indexes[i], a1_traj_indexes,\n a2_traj_indexes, trace.trajectory_length, trace.episode, i,\n a1_traj_q_values, a2_traj_q_values,\n trace.a1_values_for_a2_states[i],\n trace.a2_values_for_a1_states[start_idx:end_idx + 1],\n trace.agent_ratio)\n trace.a1_trajectory_indexes.append(a1_traj_indexes)\n trace.disagreement_trajectories.append(dt)\n\n\ndef get_frames(trace, s1_indexes, s2_indexes, s2_traj, mark_position=None):\n a1_frames = [trace.states[x].image for x in s1_indexes]\n a2_frames = [trace.a2_trajectories[s2_traj][x - min(s2_indexes)].image for x in s2_indexes]\n assert len(a1_frames) == trace.trajectory_length, 'Error in highlight frame length'\n assert len(a2_frames) == trace.trajectory_length, 'Error in highlight frame length'\n da_index = trace.trajectory_length // 2 - 1\n if mark_position:\n \"\"\"mark disagreement state\"\"\"\n a1_frames[da_index] = mark_agent(a1_frames[da_index], text='Disagreement',\n position=mark_position)\n a2_frames[da_index] = a1_frames[da_index]\n return a1_frames, a2_frames\n\n\nclass State(object):\n def __init__(self, idx, episode, obs, state, action_values, img, features, **kwargs):\n self.observation = obs\n self.image = img\n self.state = state\n self.action_values = action_values\n self.features = features\n self.kwargs = kwargs\n self.id = (episode, idx)\n\n def plot_image(self):\n plt.imshow(self.image)\n plt.show()\n\n def save_image(self, path, name):\n imageio.imwrite(path + '/' + name + '.png', self.image)\n\n\nclass DisagreementTrajectory(object):\n def __init__(self, da_index, a1_states, a2_states, horizon, episode, i, a1_s_a_values,\n a2_s_a_values, a1_values_for_a2_states, a2_values_for_a1_states, agent_ratio):\n self.a1_states = a1_states\n self.a2_states = a2_states\n self.episode = episode\n self.trajectory_index = i\n self.horizon = horizon\n self.da_index = da_index\n self.disagreement_score = None\n self.importance = None\n self.state_importance_list = []\n self.agent_ratio = agent_ratio\n self.a1_s_a_values = a1_s_a_values\n self.a2_s_a_values = a2_s_a_values\n self.a1_values_for_a2_states = a1_values_for_a2_states\n self.a2_values_for_a1_states = a2_values_for_a1_states\n self.importance_funcs = {\n \"max_min\": trajectory_importance_max_min,\n \"max_avg\": trajectory_importance_max_min,\n \"avg\": trajectory_importance_max_min,\n \"avg_delta\": trajectory_importance_max_min,\n }\n\n def calculate_state_disagreement_extent(self, importance):\n self.state_importance = importance\n da_idx = self.da_index\n traj_da_idx = self.a1_states.index(da_idx)\n s1_vals, s2_vals = self.a1_s_a_values[traj_da_idx], self.a2_s_a_values[traj_da_idx]\n if importance == 'sb':\n return self.second_best_confidence(s1_vals, s2_vals)\n elif importance == 'bety':\n return self.better_than_you_confidence(s1_vals, s2_vals)\n\n def calculate_trajectory_importance(self, trace, i, importance):\n \"\"\"calculate trajectory score\"\"\"\n s_i, e_i = self.a1_states[0], self.a1_states[-1]\n self.trajectory_importance = importance\n rel_idx = e_i - s_i\n if importance == \"last_state\":\n s1, s2 = trace.states[e_i], trace.a2_trajectories[i][rel_idx]\n return self.trajectory_importance_last_state(s1, s2, rel_idx)\n else:\n return self.get_trajectory_importance(importance, rel_idx)\n\n def get_trajectory_importance(self, importance, end):\n \"\"\"state values\"\"\"\n s1_a1_vals = self.a1_s_a_values\n s1_a2_vals = self.a2_values_for_a1_states\n s2_a1_vals = self.a1_values_for_a2_states[:end + 1]\n s2_a2_vals = self.a2_s_a_values[:end + 1]\n \"\"\"calculate value of all individual states in both trajectories,\n as ranked by both agents\"\"\"\n traj1_states_importance, traj2_states_importance = [], []\n for i in range(len(s1_a1_vals)):\n traj1_states_importance.append(self.get_state_value(s1_a1_vals[i], s1_a2_vals[i]))\n traj2_states_importance.append(self.get_state_value(s2_a1_vals[i], s2_a2_vals[i]))\n \"\"\"calculate score of trajectories\"\"\"\n traj1_score = self.importance_funcs[importance](traj1_states_importance)\n traj2_score = self.importance_funcs[importance](traj2_states_importance)\n \"\"\"return the difference between them. bigger == greater disagreement\"\"\"\n return abs(traj1_score - traj2_score)\n\n def trajectory_importance_last_state(self, s1, s2, idx):\n if s1.image.tolist() == s2.image.tolist(): return 0\n \"\"\"state values\"\"\"\n s1_a1_vals = self.a1_s_a_values[-1]\n s1_a2_vals = self.a2_values_for_a1_states[-1]\n s2_a1_vals = self.a1_values_for_a2_states[idx]\n s2_a2_vals = self.a2_s_a_values[idx]\n \"\"\"the value of the state is defined by the best available action from it\"\"\"\n s1_score = max(s1_a1_vals) * self.agent_ratio + max(s1_a2_vals)\n s2_score = max(s2_a1_vals) * self.agent_ratio + max(s2_a2_vals)\n return abs(s1_score - s2_score)\n\n def second_best_confidence(self, a1_vals, a2_vals):\n \"\"\"compare best action to second-best action\"\"\"\n sorted_1 = sorted(a1_vals, reverse=True)\n sorted_2 = sorted(a2_vals, reverse=True)\n a1_diff = sorted_1[0] - sorted_1[1] * self.agent_ratio\n a2_diff = sorted_2[0] - sorted_2[1]\n return a1_diff + a2_diff\n\n def better_than_you_confidence(self, a1_vals, a2_vals):\n a1_diff = (max(a1_vals) - a1_vals[np.argmax(a2_vals)]) * self.agent_ratio\n a2_diff = max(a2_vals) - a2_vals[np.argmax(a1_vals)]\n return a1_diff + a2_diff\n\n def get_state_value(self, a1_vals, a2_vals):\n \"\"\"\n the value of the state is defined by the best available action from it, as this is\n calculated by estimated future returns\n \"\"\"\n return max(a1_vals) * self.agent_ratio + max(a2_vals)\n\n def normalize_q_values(self, a1_max, a1_min, a2_max, a2_min):\n self.a1_s_a_values = (np.array(self.a1_s_a_values) - a1_min) / (a1_max - a1_min)\n self.a2_s_a_values = (np.array(self.a2_s_a_values) - a2_min) / (a2_max - a2_min)\n self.a1_values_for_a2_states = (np.array(self.a1_values_for_a2_states) - a1_min) / (\n a1_max - a1_min)\n self.a2_values_for_a1_states = (np.array(self.a2_values_for_a1_states) - a2_min) / (\n a2_max - a2_min)\n\n\ndef disagreement(timestep, trace, env2, a1, a2, obs, s):\n trajectory_states, trajectory_scores = \\\n disagreement_states(trace, env2, a2, timestep, obs, s)\n a1.interface.update_trace(trace, a1, timestep, trajectory_states, trajectory_scores )\n\n\ndef save_disagreements(a1_DAs, a2_DAs, output_dir, fps):\n highlight_frames_dir = join(output_dir, \"highlight_frames\")\n video_dir = join(output_dir, \"videos\")\n make_clean_dirs(video_dir)\n make_clean_dirs(join(video_dir, 'temp'))\n make_clean_dirs(highlight_frames_dir)\n dir = join(video_dir, 'temp')\n\n height, width, layers = a1_DAs[0][0].shape\n size = (width, height)\n trajectory_length = len(a1_DAs[0])\n da_idx = trajectory_length // 2\n for hl_i in range(len(a1_DAs)):\n for img_i in range(len(a1_DAs[hl_i])):\n save_image(highlight_frames_dir, \"a1_DA{}_Frame{}\".format(str(hl_i), str(img_i)),\n a1_DAs[hl_i][img_i])\n save_image(highlight_frames_dir, \"a2_DA{}_Frame{}\".format(str(hl_i), str(img_i)),\n a2_DAs[hl_i][img_i])\n\n \"\"\"up to disagreement\"\"\"\n create_video('together' + str(hl_i), highlight_frames_dir, dir, \"a1_DA\" + str(hl_i), size,\n da_idx, fps, add_pause=[0,0])\n \"\"\"from disagreement\"\"\"\n name1, name2 = \"a1_DA\" + str(hl_i), \"a2_DA\" + str(hl_i)\n create_video(name1, highlight_frames_dir, dir, name1, size,\n trajectory_length, fps, start=da_idx, add_pause=[0, 0])\n create_video(name2, highlight_frames_dir, dir, name2, size,\n trajectory_length, fps, start=da_idx, add_pause=[0, 0])\n return video_dir\n\n\n# def get_pre_disagreement_states(t, horizon, states):\n# start = t - (horizon // 2) + 1\n# pre_disagreement_states = []\n# if start < 0:\n# pre_disagreement_states = [states[0] for _ in range(abs(start))]\n# start = 0\n# pre_disagreement_states = pre_disagreement_states + states[start:]\n# return pre_disagreement_states\n\n\ndef disagreement_states(trace, env, agent, timestep, obs, s):\n horizon, da_rewards = env.args.horizon, []\n start = timestep - (horizon // 2) + 1\n if start < 0: start = 0\n trajectory_states = trace.states[start:]\n da_state = deepcopy(trajectory_states[-1])\n da_state.action_values = agent.interface.get_state_action_values(agent, s)\n trajectory_states[-1] = da_state\n done = False\n next_timestep = timestep + 1\n for step in range(next_timestep, next_timestep + (horizon // 2)):\n if done: break\n a = agent.interface.get_next_action(agent, obs, s)\n obs, r, done, info = env.step(a)\n s = agent.interface.get_state_from_obs(agent, obs)\n s_a_values = agent.interface.get_state_action_values(agent, s)\n frame = env.render(mode='rgb_array')\n features = agent.interface.get_features(env)\n state_obj = State(step, trace.episode, obs, s, s_a_values, frame, features)\n trajectory_states.append(state_obj)\n da_rewards.append(r)\n agent.interface.da_states_functionality(trace, params=s_a_values)\n return trajectory_states, da_rewards\n\n\ndef get_top_k_disagreements(traces, args):\n \"\"\"obtain the N-most important trajectories\"\"\"\n top_k_diverse_trajectories, discarded_context = [], []\n \"\"\"get all trajectories\"\"\"\n all_trajectories = []\n for trace in traces:\n all_trajectories += [t for t in trace.disagreement_trajectories]\n sorted_trajectories = sorted(all_trajectories, key=lambda x: x.importance, reverse=True)\n \"\"\"select trajectories\"\"\"\n seen_indexes = {i: [] for i in range(len(traces))}\n for d in sorted_trajectories:\n t_indexes = d.a1_states\n intersecting_indexes = set(seen_indexes[d.episode]).intersection(set(t_indexes))\n if len(intersecting_indexes) > args.similarity_limit:\n discarded_context.append(d)\n continue\n seen_indexes[d.episode] += t_indexes\n top_k_diverse_trajectories.append(d)\n if len(top_k_diverse_trajectories) == args.n_disagreements:\n break\n\n if not len(top_k_diverse_trajectories) == args.n_disagreements:\n top_k_diverse_trajectories += discarded_context\n top_k_diverse_trajectories = top_k_diverse_trajectories[:args.n_disagreements]\n\n log(f'Chosen disagreements:')\n for d in top_k_diverse_trajectories:\n log(f'Name: ({d.episode},{d.da_index})')\n\n return top_k_diverse_trajectories\n\n\ndef make_same_length(trajectories, horizon, traces):\n \"\"\"make all trajectories the same length\"\"\"\n for d in trajectories:\n if len(d.a1_states) < horizon:\n \"\"\"insert to start of video\"\"\"\n da_traj_idx = d.a1_states.index(d.da_index)\n for _ in range((horizon // 2) - da_traj_idx - 1):\n d.a1_states.insert(0, d.a1_states[0])\n d.a2_states.insert(0, d.a1_states[0])\n \"\"\"insert to end of video\"\"\"\n while len(d.a1_states) < horizon:\n last_idx = d.a1_states[-1]\n if last_idx < len(traces[d.episode].states) - 1:\n last_idx += 1\n d.a1_states.append(last_idx)\n else:\n d.a1_states.append(last_idx)\n\n for _ in range(horizon - len(d.a2_states)):\n d.a2_states.append(d.a2_states[-1])\n return trajectories\n\n\ndef mark_agent(img, action=None, text=None, position=None, color=255, thickness=2):\n assert position, 'Error - No position provided for marking agent'\n img2 = img.copy()\n top_left = (position[0], position[1])\n bottom_right = (position[0] + 30, position[1] + 15)\n cv2.rectangle(img2, top_left, bottom_right, color, thickness)\n\n \"\"\"add action text\"\"\"\n if action or text:\n font = ImageFont.truetype('Roboto-Regular.ttf', 20)\n text = text or f'Chosen action: {ACTION_DICT[action]}'\n image = Image.fromarray(img2, 'RGB')\n draw = ImageDraw.Draw(image)\n draw.text((40, 40), text, (255, 255, 255), font=font)\n img_array = np.asarray(image)\n return img_array\n\n return img2\n" ]
[ [ "numpy.asarray", "numpy.argmax", "matplotlib.pyplot.imshow", "matplotlib.pyplot.show", "numpy.array" ] ]
mumingpo/590op-final-project
[ "95851d2f430cdc24b9d834c6a50b069fc637a8ed" ]
[ "src/data_utils.py" ]
[ "import numpy as np\n\ndef read_data(path, M, N, offset=0):\n \"\"\"\n Read u.data in the default format.\n The memory cost associated with a [943, 1682] matrix of floats are not big,\n so we can still do this.\n \"Might\" run into trouble for larger datasets,\n where we will need to handle things in batches.\n \n Params:\n M: number of users\n N: number of movies\n offset: center of ratings (to assist in regularization.\n \n Return:\n arr: [M, N] matrix of user ratings of movies\n omega: [M, N] matrix indicating where user rating is valid\n \"\"\"\n\n arr = np.zeros([M, N], dtype=np.float)\n omega = np.full([M, N], False, dtype=np.bool)\n\n with open(path, \"rt\") as f:\n for line in f:\n if line == \"\":\n continue\n # fields are \"user\", \"movie\", \"rating\", and \"timestamp\" respectively in order,\n # delimited by '\\t'\n fields = line.split('\\t')\n if len(fields) != 4:\n raise ValueError(\"Data corruption: line contains {}\".format(fields))\n\n user, movie = [int(field) - 1 for field in fields[:2]]\n rating = int(fields[2])\n arr[user][movie] = rating - offset\n omega[user][movie] = True\n \n return arr, omega" ]
[ [ "numpy.full", "numpy.zeros" ] ]
Alessi0X/GraKeL
[ "222fcdde4071afebeb3d7bd724b1f979ede8df7f" ]
[ "grakel/kernels/kernel.py" ]
[ "\"\"\"The main class file representing a kernel.\"\"\"\n# Author: Ioannis Siglidis <[email protected]>\n# License: BSD 3 clause\nimport collections\nimport warnings\nimport copy\n\nimport numpy as np\n\nfrom sklearn.base import BaseEstimator\nfrom sklearn.base import TransformerMixin\nfrom sklearn.exceptions import NotFittedError\nfrom sklearn.utils.validation import check_is_fitted\nfrom sklearn.externals import joblib\n\nfrom grakel.graph import Graph\nfrom grakel.kernels._c_functions import k_to_ij_triangular\nfrom grakel.kernels._c_functions import k_to_ij_rectangular\n\n# Python 2/3 cross-compatibility import\nfrom six import iteritems\ntry:\n import itertools.imap as map\nexcept ImportError:\n pass\n\n\nclass Kernel(BaseEstimator, TransformerMixin):\n \"\"\"A general class for graph kernels.\n\n At default a kernel is considered as pairwise. Doing so the coder that\n adds a new kernel, possibly only needs to overwrite the attributes:\n `parse_input` and `pairwise_operation` on the new kernel object.\n\n Parameters\n ----------\n n_jobs : int or None, optional\n Defines the number of jobs of a joblib.Parallel objects needed for parallelization\n or None for direct execution.\n\n normalize : bool, optional\n Normalize the output of the graph kernel.\n\n verbose : bool, optional\n Define if messages will be printed on stdout.\n\n Attributes\n ----------\n X : list\n Stores the input that occurs from parse input, on fit input data.\n Default format of the list objects is `grakel.graph.graph`.\n\n _graph_format : str\n Stores in which type the graphs will need to be stored.\n\n _verbose : bool\n Defines if two print arguments on stdout.\n\n _normalize : bool\n Defines if normalization will be applied on the kernel matrix.\n\n _valid_parameters : set\n Holds the default valid parameters names for initialization.\n\n _method_calling : int\n An inside enumeration defines which method calls another method.\n - 1 stands for fit\n - 2 stands for fit_transform\n - 3 stands for transform\n\n _parallel : sklearn.external.joblib.Parallel or None\n A Parallel initialized object to imply parallelization to kernel execution.\n The use of this object depends on the implementation of each base kernel.\n\n \"\"\"\n\n X = None\n _graph_format = \"dictionary\"\n _method_calling = 0\n\n def __init__(self,\n n_jobs=None,\n normalize=False,\n verbose=False):\n \"\"\"`__init__` for `kernel` object.\"\"\"\n self.verbose = verbose\n self.n_jobs = n_jobs\n self.normalize = normalize\n self._initialized = dict(n_jobs=False)\n\n def fit(self, X, y=None):\n \"\"\"Fit a dataset, for a transformer.\n\n Parameters\n ----------\n X : iterable\n Each element must be an iterable with at most three features and at\n least one. The first that is obligatory is a valid graph structure\n (adjacency matrix or edge_dictionary) while the second is\n node_labels and the third edge_labels (that fitting the given graph\n format). The train samples.\n\n y : None\n There is no need of a target in a transformer, yet the pipeline API\n requires this parameter.\n\n Returns\n -------\n self : object\n Returns self.\n\n \"\"\"\n self._is_transformed = False\n self._method_calling = 1\n\n # Parameter initialization\n self.initialize()\n\n # Input validation and parsing\n if X is None:\n raise ValueError('`fit` input cannot be None')\n else:\n self.X = self.parse_input(X)\n\n # Return the transformer\n return self\n\n def transform(self, X):\n \"\"\"Calculate the kernel matrix, between given and fitted dataset.\n\n Parameters\n ----------\n X : iterable\n Each element must be an iterable with at most three features and at\n least one. The first that is obligatory is a valid graph structure\n (adjacency matrix or edge_dictionary) while the second is\n node_labels and the third edge_labels (that fitting the given graph\n format). If None the kernel matrix is calculated upon fit data.\n The test samples.\n\n Returns\n -------\n K : numpy array, shape = [n_targets, n_input_graphs]\n corresponding to the kernel matrix, a calculation between\n all pairs of graphs between target an features\n\n \"\"\"\n self._method_calling = 3\n # Check is fit had been called\n check_is_fitted(self, ['X'])\n\n # Input validation and parsing\n if X is None:\n raise ValueError('`transform` input cannot be None')\n else:\n Y = self.parse_input(X)\n\n # Transform - calculate kernel matrix\n km = self._calculate_kernel_matrix(Y)\n self._Y = Y\n\n # Self transform must appear before the diagonal call on normilization\n self._is_transformed = True\n if self.normalize:\n X_diag, Y_diag = self.diagonal()\n km /= np.sqrt(np.outer(Y_diag, X_diag))\n return km\n\n def fit_transform(self, X):\n \"\"\"Fit and transform, on the same dataset.\n\n Parameters\n ----------\n X : iterable\n Each element must be an iterable with at most three features and at\n least one. The first that is obligatory is a valid graph structure\n (adjacency matrix or edge_dictionary) while the second is\n node_labels and the third edge_labels (that fitting the given graph\n format). If None the kernel matrix is calculated upon fit data.\n The test samples.\n\n y : None\n There is no need of a target in a transformer, yet the pipeline API\n requires this parameter.\n\n Returns\n -------\n K : numpy array, shape = [n_targets, n_input_graphs]\n corresponding to the kernel matrix, a calculation between\n all pairs of graphs between target an features\n\n \"\"\"\n self._method_calling = 2\n self.fit(X)\n\n # Transform - calculate kernel matrix\n km = self._calculate_kernel_matrix()\n\n self._X_diag = np.diagonal(km)\n if self.normalize:\n return km / np.sqrt(np.outer(self._X_diag, self._X_diag))\n else:\n return km\n\n def _calculate_kernel_matrix(self, Y=None):\n \"\"\"Calculate the kernel matrix given a target_graph and a kernel.\n\n Each a matrix is calculated between all elements of Y on the rows and\n all elements of X on the columns.\n\n Parameters\n ----------\n Y : list, default=None\n A list of graph type objects. If None kernel is calculated between\n X and itself.\n\n Returns\n -------\n K : numpy array, shape = [n_targets, n_inputs]\n The kernel matrix: a calculation between all pairs of graphs\n between targets and inputs. If Y is None targets and inputs\n are the taken from self.X. Otherwise Y corresponds to targets\n and self.X to inputs.\n\n \"\"\"\n if Y is None:\n K = np.zeros(shape=(len(self.X), len(self.X)))\n if self._parallel is None:\n cache = list()\n for (i, x) in enumerate(self.X):\n K[i, i] = self.pairwise_operation(x, x)\n for (j, y) in enumerate(cache):\n K[j, i] = self.pairwise_operation(y, x)\n cache.append(x)\n else:\n dim = len(self.X)\n n_jobs, nsamples = self._n_jobs, ((dim+1)*(dim))//2\n\n def kij(k):\n return k_to_ij_triangular(k, dim)\n\n split = [iter(((i, j), (self.X[i], self.X[j])) for i, j in\n map(kij, range(*rg))) for rg in indexes(n_jobs, nsamples)]\n\n self._parallel(joblib.delayed(assign)(s, K, self.pairwise_operation) for s in split)\n K = np.triu(K) + np.triu(K, 1).T\n\n else:\n K = np.zeros(shape=(len(Y), len(self.X)))\n if self._parallel is None:\n for (j, y) in enumerate(Y):\n for (i, x) in enumerate(self.X):\n K[j, i] = self.pairwise_operation(y, x)\n else:\n dim_X, dim_Y = len(self.X), len(Y)\n n_jobs, nsamples = self._n_jobs, (dim_X * dim_Y)\n\n def kij(k):\n return k_to_ij_rectangular(k, dim_X)\n\n split = [iter(((j, i), (Y[j], self.X[i])) for i, j in\n map(kij, range(*rg))) for rg in indexes(n_jobs, nsamples)]\n\n self._parallel(joblib.delayed(assign)(s, K, self.pairwise_operation) for s in split)\n return K\n\n def diagonal(self):\n \"\"\"Calculate the kernel matrix diagonal of the fit/transformed data.\n\n Parameters\n ----------\n None.\n\n Returns\n -------\n X_diag : np.array\n The diagonal of the kernel matrix between the fitted data.\n This consists of each element calculated with itself.\n\n Y_diag : np.array\n The diagonal of the kernel matrix, of the transform.\n This consists of each element calculated with itself.\n\n \"\"\"\n # Check is fit had been called\n check_is_fitted(self, ['X'])\n try:\n check_is_fitted(self, ['_X_diag'])\n except NotFittedError:\n # Calculate diagonal of X\n self._X_diag = np.empty(shape=(len(self.X),))\n for (i, x) in enumerate(self.X):\n self._X_diag[i] = self.pairwise_operation(x, x)\n\n try:\n # If transform has happened return both diagonals\n check_is_fitted(self, ['_Y'])\n Y_diag = np.empty(shape=(len(self._Y),))\n for (i, y) in enumerate(self._Y):\n Y_diag[i] = self.pairwise_operation(y, y)\n\n return self._X_diag, Y_diag\n except NotFittedError:\n # Else just return both X_diag\n return self._X_diag\n\n def parse_input(self, X):\n \"\"\"Parse the given input and raise errors if it is invalid.\n\n Parameters\n ----------\n X : iterable\n For the input to pass the test, we must have:\n Each element must be an iterable with at most three features and at\n least one. The first that is obligatory is a valid graph structure\n (adjacency matrix or edge_dictionary) while the second is\n node_labels and the third edge_labels (that correspond to the given\n graph format). A valid input also consists of graph type objects.\n\n Returns\n -------\n Xp : list\n List of graph type objects.\n\n \"\"\"\n if not isinstance(X, collections.Iterable):\n raise TypeError('input must be an iterable\\n')\n else:\n Xp = list()\n for (i, x) in enumerate(iter(X)):\n is_iter = isinstance(x, collections.Iterable)\n if is_iter:\n x = list(x)\n if is_iter and len(x) in [0, 1, 2, 3]:\n if len(x) == 0:\n warnings.warn('Ignoring empty element' +\n 'on index: '+str(i)+'..')\n continue\n elif len(x) == 1:\n Xp.append(Graph(x[0], {}, {},\n self._graph_format))\n elif len(x) == 2:\n Xp.append(Graph(x[0], x[1], {}, self._graph_format))\n else:\n Xp.append(Graph(x[0], x[1], x[2], self._graph_format))\n elif type(x) is Graph:\n Xp.append(x)\n else:\n raise TypeError('Each element of X must have at least ' +\n 'one and at most 3 elements.\\n')\n if len(Xp) == 0:\n raise ValueError('Parsed input is empty.')\n return Xp\n\n def initialize(self):\n \"\"\"Initialize all transformer arguments, needing initialisation.\"\"\"\n if not self._initialized[\"n_jobs\"]:\n if type(self.n_jobs) is not int and self.n_jobs is not None:\n raise ValueError('n_jobs parameter must be an int '\n 'indicating the number of jobs as in joblib or None')\n elif self.n_jobs is None:\n self._parallel = None\n else:\n self._parallel = joblib.Parallel(n_jobs=self.n_jobs,\n backend=\"threading\",\n pre_dispatch='all')\n self._n_jobs = self._parallel._effective_n_jobs()\n self._initialized[\"n_jobs\"] = True\n\n def pairwise_operation(self, x, y):\n \"\"\"Calculate a pairwise kernel between two elements.\n\n Parameters\n ----------\n x, y : Object\n Objects as occur from parse_input.\n\n Returns\n -------\n kernel : number\n The kernel value.\n\n \"\"\"\n raise NotImplementedError('Pairwise operation is not implemented!')\n\n def set_params(self, **params):\n \"\"\"Call the parent method.\"\"\"\n if len(self._initialized):\n # Copy the parameters\n params = copy.deepcopy(params)\n\n # Iterate over the parameters\n for key, value in iteritems(params):\n key, delim, sub_key = key.partition('__')\n if delim:\n if sub_key in self._initialized:\n self._initialized[sub_key] = False\n elif key in self._initialized:\n self._initialized[key] = False\n\n # Set parameters\n super(Kernel, self).set_params(**params)\n\n\ndef indexes(n_jobs, nsamples):\n \"\"\"Distribute samples accross n_jobs.\"\"\"\n n_jobs = n_jobs\n\n if n_jobs >= nsamples:\n for i in range(nsamples):\n yield (i, i+1)\n else:\n ns = nsamples/n_jobs\n start = 0\n for i in range(n_jobs-1):\n end = start + ns\n yield (int(start), int(end))\n start = end\n yield (int(start), nsamples)\n\n\ndef assign(data, K, pairwise_operation):\n \"\"\"Assign list values of an iterable to a numpy array while calculating a pairwise operation.\"\"\"\n for d in data:\n K[d[0][0], d[0][1]] = pairwise_operation(d[1][0], d[1][1])\n" ]
[ [ "sklearn.utils.validation.check_is_fitted", "sklearn.externals.joblib.delayed", "sklearn.externals.joblib.Parallel", "numpy.diagonal", "numpy.outer", "numpy.triu" ] ]
atharvamh/Predicting-IDC-in-Breast-Cancer
[ "b9b4dff53256042947749c0ad0ba0536e9984a5a" ]
[ "data_preprocess.py" ]
[ "import os\nimport numpy as np\nimport pandas as pd\nimport cv2\nimport matplotlib.pyplot as plt\nimport fnmatch\n\nfrom sklearn.model_selection import train_test_split\nfrom glob import glob\n\nimagePatches = glob('./IDC_regular_ps50_idx5/**/*.png',recursive = True)\n\ndef multiplot():\n plt.rcParams['figure.figsize'] = (10.0, 10.0)\n plt.subplots_adjust(wspace=0, hspace=0)\n count = 0\n for i in imagePatches[0:20]:\n im = cv2.imread(i)\n im = cv2.resize(im,(50,50))\n plt.subplot(5,4,count+1)\n plt.imshow(cv2.cvtColor(im,cv2.COLOR_BGR2RGB));plt.axis('off')\n count += 1\n \nimages_zero = '*class0.png'\nimages_one = '*class1.png'\nclass_zero = fnmatch.filter(imagePatches,images_zero)\nclass_one = fnmatch.filter(imagePatches,images_one)\n\ndef process_images(lower,upper):\n X = []\n Y = []\n\n WIDTH = 224\n HEIGHT = 224\n for img in imagePatches[lower:upper]:\n fullim = cv2.imread(img)\n X.append(cv2.resize((fullim),(WIDTH,HEIGHT),interpolation = cv2.INTER_CUBIC))\n\n if img in class_zero:\n Y.append(0)\n elif img in class_one:\n Y.append(1)\n else:\n return\n \n return X,Y\n \nX,Y = process_images(0,5000)\ndf = pd.DataFrame()\ndf['images'] = X\ndf['labels'] = Y\nX2=df[\"images\"]\nY2=df[\"labels\"]\nX2=np.array(X2)\nimgs0=[]\nimgs1=[]\nimgs0 = X2[Y2==0]\nimgs1 = X2[Y2==1]\n\ndef Datainfo(a,b):\n print('Total number of images: {}'.format(len(a)))\n print('Number of IDC(-) Images: {}'.format(np.sum(b==0)))\n print('Number of IDC(+) Images: {}'.format(np.sum(b==1)))\n print('Percentage of positive images: {:.2f}%'.format(100*np.mean(b)))\n print('Image shape (Width, Height, Channels): {}'.format(a[0].shape))\n \nX = np.array(X)\nX = X/255.0\n\nX_train, X_test, Y_train, Y_test = train_test_split(X,Y,test_size=0.2)\nY_trainHot = tf.keras.utils.to_categorical(Y_train,num_classes=2)\nY_testHot = tf.keras.utils.to_categorical(Y_test,num_classes=2)\n" ]
[ [ "numpy.sum", "matplotlib.pyplot.axis", "pandas.DataFrame", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.subplot", "numpy.array", "sklearn.model_selection.train_test_split", "numpy.mean" ] ]
BBarrow31500/molssi-best-practices
[ "737d46aaab087bb9d5c45d2d76bc6f2e879fa060" ]
[ "molecool/io/xyz.py" ]
[ "\"\"\"\nThis module reads and writes xyz files.\n\"\"\"\n\nimport os\nimport numpy as np\n\ndef open_xyz(file_location):\n \n # Open an xyz file and return symbols and coordinates.\n xyz_file = np.genfromtxt(fname=file_location, skip_header=2, dtype='unicode')\n symbols = xyz_file[:,0]\n coords = (xyz_file[:,1:])\n coords = coords.astype(np.float)\n return symbols, coords\n\ndef write_xyz(file_location, symbols, coordinates):\n \n # Write an xyz file given a file location, symbols, and coordinates.\n num_atoms = len(symbols)\n \n with open(file_location, 'w+') as f:\n f.write('{}\\n'.format(num_atoms))\n f.write('XYZ file\\n')\n \n for i in range(num_atoms):\n f.write('{}\\t{}\\t{}\\t{}\\n'.format(symbols[i], \n coordinates[i,0], coordinates[i,1], coordinates[i,2]))\n" ]
[ [ "numpy.genfromtxt" ] ]
paroj/async-ev-cnn
[ "f7e70e75b07f43afef8ffd7eaf6f43ddefab0ae0" ]
[ "cython_setup.py" ]
[ "from sys import platform\nfrom distutils.core import setup\nfrom distutils.extension import Extension\nfrom Cython.Build import cythonize\nimport numpy\n\n\next_modules = [\n Extension(\n \"src.libs.cutils\",\n [\"src/libs/cutils.pyx\"],\n extra_compile_args=['/openmp' if platform == \"win32\" else '-fopenmp']\n )\n]\n\nsetup(\n ext_modules=cythonize(ext_modules),\n include_dirs=[numpy.get_include()],\n)" ]
[ [ "numpy.get_include" ] ]
ryanpdwyer/sigutils
[ "341513f403dee0b2c49e9630c86f0483c0d2d359" ]
[ "sigutils/plot.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\n\n- We should have plotting functions\n\n bode_ba(ba, ...)\n Takes an analog transfer function in ba form\n bode_z(b, a=1, fs, ...)\n Takes a digital transfer function in z form. Is fs, nyq, or dt preferred?\n bode_zpk(zpk, fs?, ...)\n Use zpk form (or state space?)\n bode_s(sympy_expression, var, ...)\n Takes a sympy expression, var, evaulates it at 2*pi*f...\n bode_f(func, ...)\n Takes a function, which will be evaluated to determine the response\n\n\n\n\"\"\"\nfrom __future__ import division, print_function, absolute_import\n\nfrom collections import Counter\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import signal\n\nfrom sigutils._util import (freqresp, freqz, mag_phase)\n\n\ndef adjust_y_ticks(ax, delta):\n \"\"\"Adjust the y-axis tick marks on ax to the spacing delta.\"\"\"\n ylim = np.array(ax.get_ylim()) / delta\n ymin = ylim[0] // 1 # Round towards - infinity\n ymax = -(-ylim[1] // 1) # Trick to round towards + infinity\n # Note: this rounds away from zero so we never make the axis limits smaller\n ax_new_lim = np.array([ymin, ymax]) * delta\n ax_new_ticks = np.arange(ax_new_lim[0], ax_new_lim[1] + 1, delta)\n ax.set_ybound(*ax_new_lim)\n ax.set_yticks(ax_new_ticks)\n\n\ndef adjust_ylim_ticks(ax, ylim):\n if ylim is not None:\n ax.set_ylim(ylim[0], ylim[1])\n if len(ylim) == 3:\n adjust_y_ticks(ax, ylim[2])\n\n\n# def adjust_x_ticks(ax, delta):\n# xlim = np.array(ax.get_xlim()) / delta\n# xmin = xlim[0] // 1\n# xmax = -(-xlim[1] // 1)\n# ax_new_ticks = np.arange(xmin, xmax + delta*0.5, delta)\n# ax_new_ticks[]\n\n\ndef find_crossings(x, a=0):\n \"\"\"Return array indices where x - a changes sign.\n\n See http://stackoverflow.com/a/29674950/2823213\"\"\"\n x = np.atleast_1d(x)\n return np.where(np.diff(np.signbit(x - a).astype(int)))[0]\n\n\ndef find_repeated_roots(x):\n \"\"\"\"\"\"\n cnt = Counter()\n x_iterable = list(x)\n while x_iterable != []:\n xi = x_iterable[0]\n compared_equal = np.isclose(xi, x_iterable)\n equal_indices = np.nonzero(compared_equal)[0]\n for i in equal_indices[::-1]:\n x_iterable.pop(i)\n\n cnt[xi] = np.sum(compared_equal)\n\n return {key: val for key, val in cnt.items() if val > 1}\n\n\ndef _x_per_inch(ax):\n \"\"\"Conversion factor between the plot x variable and the figure width.\n\n For example, \"\"\"\n xlim = ax.get_xlim()\n return (xlim[1] - xlim[0]) / ax.get_figure().get_figwidth()\n\n\ndef _y_per_inch(ax):\n ylim = ax.get_ylim()\n return (ylim[1] - ylim[0]) / ax.get_figure().get_figheight()\n\n\ndef _font_pt_to_inches(x):\n \"\"\"Convert points to inches (1 inch = 72 points).\"\"\"\n return x / 72.\n\n\ndef magtime(freq, resp, t, impulse, freq_lim=None, freq_log=False, dB=True,\n mag_lim=None, step=False, stem=False, figax=None, rcParams={}):\n \"\"\"\"\"\"\n mag, _ = mag_phase(resp, dB=dB)\n\n rcParamsDefault = {'figure.figsize' : (8,6),\n 'lines.linewidth': 1.5,\n 'figure.dpi' : 300,\n 'savefig.dpi' : 300,\n 'axes.labelsize' : 12,}\n rcParamsDefault.update(rcParams)\n\n if figax is None:\n with mpl.rc_context(rcParamsDefault):\n fig, (ax1, ax2) = plt.subplots(nrows=2)\n else:\n fig, (ax1, ax2) = figax\n\n ax1.yaxis.grid(True, linestyle='-', color='.8', zorder=0)\n\n if freq_log:\n ax1.semilogx(freq, mag)\n else:\n ax1.plot(freq, mag)\n\n if dB:\n ax1.set_ylabel('Magnitude [dB]')\n else:\n ax1.set_ylabel('Magnitude')\n\n ax1.set_xlim(freq[0], freq[-1])\n\n if step:\n y = np.cumsum(impulse)\n h_lines = [0, 1]\n else:\n y = impulse\n h_lines = [0]\n\n if stem:\n ax2.stem(t, y, linestyle='-', markerfmt='.', basefmt='k-')\n else:\n ax2.plot(t, y)\n\n ax2.set_xlim(t.min(), t.max())\n ax2.hlines(h_lines, t.min(), t.max(), color='0.8', zorder=0)\n ax1.set_xlabel(\"Frequency\")\n ax2.set_xlabel(\"Time / Samples\")\n\n return fig, (ax1, ax2)\n\n\ndef iir_impulse(b, a, N=1000, prob=0.005):\n freq, resp = freqz(b, a, fs=1, xlim=None, N=N, xlog=False)\n bandwidth = np.sum(np.abs(resp)) * (freq[1] - freq[0])\n\n n = int(1/(6*bandwidth))\n difference = 1\n i1 = 0\n\n while difference >= prob:\n impulse = i1\n n *= 1.5\n x = np.zeros(2*n+1)\n x[0] = 1\n i1 = signal.lfilter(b, a, x)\n difference = 1 - np.sum(abs(impulse)) / np.sum(abs(i1))\n\n return impulse\n\n\ndef impulse_z(b, a, fs=1, N=1000, prob=0.005):\n a = np.atleast_1d(a)\n\n if a.size == 1:\n impulse = b/a\n else:\n impulse = iir_impulse(b, a, N=N, prob=prob)\n\n t = np.arange(impulse.size) / fs\n\n return t, impulse\n\n\ndef magtime_z(b, a=1, fs=1, freq_lim=None, N=1000, freq_log=False, dB=True,\n mag_lim=None, prob=0.005, step=False, centered=False, stem=False,\n figax=None, rcParams={}):\n \"\"\"Plot the frequency domain (magnitude vs. frequency) and time domain\n (impulse or step) response for a digital filter.\n\n Parameters\n ----------\n b: \"\"\"\n freq, resp = freqz(b, a, fs=fs, xlim=freq_lim, N=N, xlog=freq_log)\n t, impulse = impulse_z(b, a, fs, N=N, prob=prob)\n\n figax = magtime(freq, resp, t, impulse, freq_lim=freq_lim,\n freq_log=freq_log, dB=dB, mag_lim=mag_lim, step=step,\n stem=stem, figax=figax, rcParams=rcParams)\n\n return figax\n\n\ndef magtime_firs(bs, fs=1, freq_lim=None, N=1000, freq_log=False, dB=True,\n mag_lim=None, prob=0.005, step=False, centered=False,\n stem=False, figax=None, rcParams={}):\n for b in bs:\n figax = magtime_z(b, a=1, fs=fs,\n freq_lim=freq_lim, N=N, freq_log=freq_log,\n dB=dB, mag_lim=mag_lim, prob=prob, step=step,\n centered=centered, stem=stem, figax=figax,\n rcParams=rcParams)\n\n return figax\n\n\ndef magtime_zz(systems, fs=1, freq_lim=None, N=1000, freq_log=False, dB=True,\n mag_lim=None, prob=0.005, step=False, centered=False,\n stem=False, figax=None, rcParams={}):\n for system in systems:\n b = system[0]\n if len(system) == 1:\n a = 1\n elif len(system) == 2:\n a = system[1]\n else:\n raise ValueError(\n \"Digital system ({0}) has more than two elements.\".format(\n system))\n\n figax = magtime_z(b, a, freq_lim=freq_lim, N=N, freq_log=freq_log,\n dB=dB, mag_lim=mag_lim, prob=prob, step=step,\n centered=centered, stem=stem, figax=figax,\n rcParams=rcParams)\n\n return figax\n\n\n# To do: should db=True be an option?\ndef bode(freq, resp, xlim=None, xlog=True, mag_lim=None, phase_lim=None,\n gain_point=None, figax=None, rcParams=None):\n \"\"\"Make a nice bode plot for the given frequency, magnitude, and phase data.\n\n Parameters\n ----------\n freq : array_like\n Array of frequencies used for the Bode plot\n resp : array_like\n Complex response evaluated at the frequencies in freq\n xlim : tuple of (x_min, x_max), optional\n Minimum and maximum values (x_min, x_max) of the plot's x-axis\n xlog : bool, optional\n Use a log (True) or linear (False) scale for the x-axis\n mag_lim : tuple of (mag_min, mag_max, mag_delta), optional\n A three element tuple containing the magnitude axis minimum, maximum\n and tick spacing\n phase_lim : tuple of (phase_min, phase_max, phase_delta), optional\n A three element tuple containing the phase axis minimum, maximum\n and tick spacing\n gain_point : float, optional\n If given, draws a vertical line on the bode plot when the gain crosses\n this point.\n figax : tuple of (fig, (ax1, ax2)), optional\n The figure and axes to create the plot on, if given. If omitted, a new\n figure and axes are created\n rcParams : dictionary, optional\n matplotlib rc settings dictionary\n\n Returns\n -------\n figax : tuple of (fig, (ax1, ax2))\n The figure and axes of the bode plot\n\n \"\"\"\n mag, phase = mag_phase(resp, dB=True, degrees=True)\n\n rcParamsDefault = {'figure.figsize' : (8,6),\n 'lines.linewidth': 1.5,\n 'figure.dpi' : 300,\n 'savefig.dpi' : 300,\n 'axes.labelsize' : 12,}\n\n if rcParams is not None:\n rcParamsDefault.update(rcParams)\n\n with mpl.rc_context(rcParamsDefault):\n if figax is None:\n fig, (ax1, ax2) = plt.subplots(nrows=2)\n else:\n fig, (ax1, ax2) = figax\n\n # Light grey major y gridlines\n ax1.yaxis.grid(True, linestyle='-', color='.8')\n ax2.yaxis.grid(True, linestyle='-', color='.8')\n\n if xlog:\n ax1.semilogx(freq, mag)\n ax2.semilogx(freq, phase)\n else:\n ax1.plot(freq, mag)\n ax2.plot(freq, phase)\n\n if xlim is not None:\n ax1.set_xlim(*xlim)\n ax2.set_xlim(*xlim)\n\n adjust_ylim_ticks(ax1, mag_lim)\n adjust_ylim_ticks(ax2, phase_lim)\n\n if gain_point is not None:\n # Would be nice to switch this for high-pass applications\n gain_index = find_crossings(mag, gain_point)\n for i in gain_index:\n ax1.axvline(x=freq[i], color='k', linestyle='--')\n ax2.axvline(x=freq[i], color='k', linestyle='--')\n\n ax1.set_ylabel('Magnitude [dB]')\n ax2.set_ylabel('Phase [deg.]')\n ax2.set_xlabel('Frequency')\n fig.tight_layout()\n return fig, (ax1, ax2)\n\n\ndef bodes(freq, resp, xlim=None, xlog=True, mag_lim=None, phase_lim=None,\n gain_point=None, figax=None, rcParams=None):\n \"\"\"Make a nice bode plot for several filters at once.\n\n Parameters\n ----------\n freq : list of arrays\n frequencies used for the Bode plot\n resp : list of array\n Complex response evaluated at the frequencies in freq\n xlim : tuple of (x_min, x_max), optional\n Minimum and maximum values (x_min, x_max) of the plot's x-axis\n xlog : bool, optional\n Use a log (True) or linear (False) scale for the x-axis\n mag_lim : tuple of (mag_min, mag_max, mag_delta), optional\n A three element tuple containing the magnitude axis minimum, maximum\n and tick spacing\n phase_lim : tuple of (phase_min, phase_max, phase_delta), optional\n A three element tuple containing the phase axis minimum, maximum\n and tick spacing\n gain_point : float, optional\n If given, draws a vertical line on the bode plot when the gain crosses\n this point.\n figax : tuple of (fig, (ax1, ax2)), optional\n The figure and axes to create the plot on, if given. If omitted, a new\n figure and axes are created\n rcParams : dictionary, optional\n matplotlib rc settings dictionary\n\n Returns\n -------\n figax : tuple of (fig, (ax1, ax2))\n The figure and axes of the bode plot\n\n \"\"\"\n for f, r in zip(freq, resp):\n figax = bode(f, r, xlim=xlim, xlog=xlog, mag_lim=mag_lim,\n phase_lim=phase_lim, gain_point=gain_point,\n figax=figax, rcParams=rcParams)\n\n return figax\n\n\ndef bode_sys(system, xlim=None, N=10000, xlog=True, mag_lim=None,\n phase_lim=None, gain_point=None, figax=None, rcParams=None):\n \"\"\"Make a nice bode plot for the given system.\n\n Parameters\n ----------\n system : an instance of the LTI class or a tuple describing the system.\n The following gives the number of elements in the tuple and\n the interpretation:\n\n * 2 (num, den)\n * 3 (zeros, poles, gain)\n * 4 (A, B, C, D)\n xlim : tuple of (x_min, x_max), optional\n Minimum and maximum values (x_min, x_max) of the plot's x-axis\n N : int, optional\n The number of points to calculate the system response at\n xlog : bool, optional\n Use a log (True) or linear (False) scale for the x-axis\n mag_lim : tuple of (mag_min, mag_max, mag_delta), optional\n A three element tuple containing the magnitude axis minimum, maximum\n and tick spacing\n phase_lim : tuple of (phase_min, phase_max, phase_delta), optional\n A three element tuple containing the phase axis minimum, maximum\n and tick spacing\n gain_point : float, optional\n If given, draws a vertical line on the bode plot at this point\n figax : tuple of (fig, (ax1, ax2)), optional\n The figure and axes to create the plot on, if given. If omitted, a new\n figure and axes are created\n rcParams : dictionary, optional\n matplotlib rc settings dictionary\"\"\"\n freq, resp = freqresp(system, xlim=xlim, N=N, xlog=xlog)\n\n return bode(freq, resp, xlim=xlim, xlog=xlog, mag_lim=mag_lim,\n phase_lim=phase_lim, gain_point=gain_point,\n figax=figax, rcParams=rcParams)\n\n\ndef bode_syss(systems, xlim=None, N=10000, xlog=True, mag_lim=None,\n phase_lim=None, gain_point=None, figax=None, rcParams=None):\n \"\"\"Make a nice bode plot for the given system.\n\n Parameters\n ----------\n systems : an iterable containing instances of the LTI class or a tuple\n describing the system. The following gives the number of elements\n in the tuple and the interpretation:\n\n * 2 (num, den)\n * 3 (zeros, poles, gain)\n * 4 (A, B, C, D)\n xlim : tuple of (x_min, x_max), optional\n Minimum and maximum values (x_min, x_max) of the plot's x-axis\n N : int, optional\n The number of points to calculate the system response at\n xlog : bool, optional\n Use a log (True) or linear (False) scale for the x-axis\n mag_lim : tuple of (mag_min, mag_max, mag_delta), optional\n A three element tuple containing the magnitude axis minimum, maximum\n and tick spacing\n phase_lim : tuple of (phase_min, phase_max, phase_delta), optional\n A three element tuple containing the phase axis minimum, maximum\n and tick spacing\n gain_point : float, optional\n If given, draws a vertical line on the bode plot at this point\n figax : tuple of (fig, (ax1, ax2)), optional\n The figure and axes to create the plot on, if given. If omitted, a new\n figure and axes are created\n rcParams : dictionary, optional\n matplotlib rc settings dictionary\"\"\"\n for system in systems:\n figax = bode_sys(system, xlim=xlim, N=N, xlog=xlog, mag_lim=mag_lim,\n phase_lim=phase_lim, gain_point=gain_point,\n figax=figax, rcParams=rcParams)\n return figax\n\n\ndef bode_z(b, a=1, fs=1, xlim=None, N=1000, xlog=False, mag_lim=None,\n phase_lim=None, gain_point=None, figax=None, rcParams=None):\n \"\"\"Make a nice bode plot for a discrete time system.\n\n Parameters\n ----------\nb : array_like\n The numerator coefficient vector in a 1-D sequence.\na : array_like\n The denominator coefficient vector in a 1-D sequence. If ``a[0]``\n is not 1, then both `a` and `b` are normalized by ``a[0]``.\n\n \"\"\"\n freq, resp = freqz(b=b, a=a, fs=fs, xlim=xlim, N=N, xlog=xlog)\n\n return bode(freq, resp, xlim=xlim, xlog=xlog, mag_lim=mag_lim,\n phase_lim=phase_lim, gain_point=gain_point,\n figax=figax, rcParams=rcParams)\n\n\ndef bode_firs(bs, fs=1, xlim=None, N=1000, xlog=False, mag_lim=None,\n phase_lim=None, gain_point=None, figax=None, rcParams=None):\n for b in bs:\n figax = bode_z(b, a=1, fs=fs, xlim=xlim, N=N, xlog=xlog,\n mag_lim=mag_lim, phase_lim=phase_lim,\n gain_point=gain_point, figax=figax,\n rcParams=rcParams)\n return figax\n\n\ndef bode_zz(systems, fs=1, xlim=None, N=1000, xlog=False, mag_lim=None,\n phase_lim=None, gain_point=None, figax=None, rcParams=None):\n \"\"\"\"\"\"\n for system in systems:\n b = system[0]\n if len(system) == 1:\n a = 1\n elif len(system) == 2:\n a = system[1]\n else:\n raise ValueError(\n \"Digital system ({0}) has more than two elements.\".format(\n system))\n\n figax = bode_z(b, a, fs=fs, xlim=xlim, N=N, xlog=xlog,\n mag_lim=mag_lim, phase_lim=phase_lim,\n gain_point=gain_point, figax=figax,\n rcParams=rcParams)\n\n return figax\n\n\ndef bode_an_dig(analogs, digitals, fs, xlim=None, N=1000, xlog=False,\n mag_lim=None, phase_lim=None, gain_point=None, figax=None,\n rcParams=None):\n \"\"\"Plots analog and digital systems together on the same axes.\"\"\"\n\n figax = bode_syss(analogs, N=N, xlim=xlim, xlog=xlog, mag_lim=mag_lim,\n phase_lim=phase_lim, gain_point=gain_point,\n figax=figax, rcParams=rcParams)\n\n bode_zz(digitals, fs=fs, xlim=xlim, xlog=xlog, mag_lim=mag_lim,\n phase_lim=phase_lim, gain_point=gain_point,\n figax=figax, rcParams=rcParams)\n\n return figax\n\n\ndef _pole_zero(z, p, k, xlim=None, ylim=None, figax=None, rcParams=None):\n z = np.atleast_1d(z)\n p = np.atleast_1d(p)\n\n rcParamsDefault = {'figure.figsize' : (6,6),\n 'lines.linewidth': 1.5,\n 'figure.dpi' : 300,\n 'savefig.dpi' : 300,\n 'axes.labelsize' : 12,}\n if rcParams is not None:\n rcParamsDefault.update(rcParams)\n\n with mpl.rc_context(rcParamsDefault):\n if figax is None:\n fig, ax = plt.subplots()\n else:\n fig, ax = figax\n\n markersize = mpl.rcParams['lines.markersize']\n markeredgewidth = mpl.rcParams['lines.markeredgewidth']\n\n zeros, = ax.plot(z.real, z.imag, linewidth=0, marker='o',\n markerfacecolor=None,)\n poles, = ax.plot(p.real, p.imag, linewidth=0, color=zeros.get_color(),\n marker ='x', markeredgewidth=3.5*markeredgewidth,\n markersize=markersize*1.5)\n\n ax.set_xlim(-1.5, 1.5)\n ax.set_ylim(-1.5, 1.5)\n circ = plt.Circle((0, 0), radius=1, linewidth=1,\n fill=False, color='gray')\n ax.axvline(0, color='k')\n ax.axhline(0, color='k')\n ax.add_patch(circ)\n ax.grid()\n\n x_per_inch = _x_per_inch(ax)\n y_per_inch = _y_per_inch(ax)\n\n m_f = mpl.rcParams['font.size']\n m_z = zeros.get_markersize()\n\n m_inch_z = _font_pt_to_inches(m_z/2. + m_f/2.)\n\n m_x_z = m_inch_z * x_per_inch\n m_y_z = m_inch_z * y_per_inch\n\n m_p = poles.get_markersize()\n m_inch_p = _font_pt_to_inches(m_p/2. + m_f/2.)\n m_x_p = m_inch_p * x_per_inch\n m_y_p = m_inch_z * y_per_inch\n\n rep_zeros = find_repeated_roots(z)\n rep_poles = find_repeated_roots(p)\n\n for pt, val in rep_zeros.items():\n ax.text(pt.real + m_x_z, pt.imag + m_y_z, str(val))\n\n for pt, val in rep_poles.items():\n ax.text(pt.real + m_x_p, pt.imag + m_y_p, str(val))\n\n return fig, ax\n\n\ndef pole_zero(sys, xlim=None, ylim=None, figax=None, rcParams=None):\n if len(sys) == 2:\n z, p, k = signal.tf2zpk(*sys)\n elif len(sys) == 3:\n z, p, k = sys\n elif len(sys) == 4:\n z, p, k = signal.ss2zpk(*sys)\n else:\n ValueError(\"\"\"\\\nsys must have 2 (transfer function), 3 (zeros, poles, gain),\nor 4 (state space) elements. sys is: {}\"\"\".format(sys))\n\n return _pole_zero(z, p, k, xlim=xlim, ylim=ylim, figax=figax,\n rcParams=rcParams)\n\n\ndef nyquist(freq, resp, freq_lim=None, xlim=None, ylim=None,\n figax=None, rcParams=None):\n if rcParams is None:\n rcParams = {'figure.figsize': (6, 6),\n 'lines.linewidth': 1.5,\n 'figure.dpi': 300,\n 'savefig.dpi': 300,\n 'font.size': 12}\n\n with mpl.rc_context(rcParams):\n if figax is None:\n fig, ax = plt.subplots()\n else:\n fig, ax = figax\n\n if freq_lim is not None:\n resp = resp[np.logical_and(freq > freq_lim[0], freq < freq_lim[1])]\n else:\n resp = resp\n\n ax.plot(resp.real, resp.imag, '-')\n circ = plt.Circle((0, 0), radius=1, linewidth=1, fill=False,\n color='gray')\n ax.axvline(0, color='0.5')\n ax.axhline(0, color='0.5')\n ax.add_patch(circ)\n ax.grid()\n\n if xlim is not None:\n xlim = list(ax.get_xlim())\n if xlim[0] > -1.1:\n xlim[0] = -1.1\n\n ax.set_xlim(xlim)\n else:\n ax.set_xlim(xlim)\n\n if ylim is not None:\n ax.set_ylim(ylim)\n\n return fig, ax\n" ]
[ [ "numpy.sum", "numpy.cumsum", "numpy.zeros", "matplotlib.pyplot.Circle", "numpy.logical_and", "numpy.isclose", "numpy.abs", "matplotlib.pyplot.subplots", "numpy.atleast_1d", "numpy.arange", "scipy.signal.lfilter", "scipy.signal.ss2zpk", "scipy.signal.tf2zpk", "numpy.array", "numpy.signbit", "numpy.nonzero", "matplotlib.rc_context" ] ]
cplan082-tech/project_csi4103
[ "987d19deacc8cb36c473adf33335fc63ae4aab10" ]
[ "datasets/plot.py" ]
[ "import csv\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef read_csv_file(name):\n file = open(name)\n type(file)\n csvreader = csv.reader(file)\n\n header = []\n header = next(csvreader) #First line of CSV is name of headers\n\n \"Populates array with rows from CSV [[shoulder_angle_1,elbow_angle_2],...]\"\n rows = []\n for row in csvreader:\n rows.append(row)\n\n file.close()\n return rows\n\ndef plot(rows):\n for row in rows:\n x = float(row[0])\n y = float(row[1])\n plt.scatter(x,y,s=1.5, color='black')\n plt.axis('off')\n fig = plt.gcf()\n fig.savefig('scanned_image.png',dpi=100)\n plt.show()\n return\n\ndef main():\n rows = read_csv_file('xycoordinates.csv') #change name to actual file name\n plot(rows)\n\nif __name__ == \"__main__\":\n\tmain()\n" ]
[ [ "matplotlib.pyplot.gcf", "matplotlib.pyplot.axis", "matplotlib.pyplot.show", "matplotlib.pyplot.scatter" ] ]
shahviraj/pgdgan
[ "97fb63547144f02d76ef0c384b9e2fbbb90c9d50" ]
[ "src/dcgan_utils.py" ]
[ "# Files of this project is modified versions of 'https://github.com/AshishBora/csgm', which\n#comes with the MIT licence: https://github.com/AshishBora/csgm/blob/master/LICENSE\n\n\"\"\"Utils for the DCGAN model\nFile based on : https://github.com/carpedm20/DCGAN-tensorflow/blob/master/utils.py\nIt comes with the following license: https://github.com/carpedm20/DCGAN-tensorflow/blob/master/LICENSE\n\"\"\"\n# pylint: skip-file\n\nfrom __future__ import division\nimport math\nimport json\nimport random\nimport pprint\nimport scipy.misc\nimport numpy as np\nfrom time import gmtime, strftime\n\npp = pprint.PrettyPrinter()\n\nget_stddev = lambda x, k_h, k_w: 1/math.sqrt(k_w*k_h*x.get_shape()[-1])\n\ndef get_image(image_path, image_size, is_crop=True, resize_w=64, is_grayscale = False):\n return transform(imread(image_path, is_grayscale), image_size, is_crop, resize_w)\n\ndef save_images(images, size, image_path):\n return imsave(inverse_transform(images), size, image_path)\n\ndef imread(path, is_grayscale = False):\n if (is_grayscale):\n return scipy.misc.imread(path, flatten = True).astype(np.float)\n else:\n return scipy.misc.imread(path).astype(np.float)\n\ndef merge_images(images, size):\n return inverse_transform(images)\n\ndef merge(images, size):\n h, w = images.shape[1], images.shape[2]\n img = np.zeros((h * size[0], w * size[1], 3))\n for idx, image in enumerate(images):\n i = idx % size[1]\n j = idx // size[1]\n img[j*h:j*h+h, i*w:i*w+w, :] = image\n\n return img\n\ndef imsave(images, size, path):\n return scipy.misc.imsave(path, merge(images, size))\n\ndef center_crop(x, crop_h, crop_w=None, resize_w=64):\n if crop_w is None:\n crop_w = crop_h\n h, w = x.shape[:2]\n j = int(round((h - crop_h)/2.))\n i = int(round((w - crop_w)/2.))\n return scipy.misc.imresize(x[j:j+crop_h, i:i+crop_w],\n [resize_w, resize_w])\n\ndef transform(image, npx=64, is_crop=True, resize_w=64):\n # npx : # of pixels width/height of image\n if is_crop:\n cropped_image = center_crop(image, npx, resize_w=resize_w)\n else:\n cropped_image = image\n return np.array(cropped_image)/127.5 - 1.\n\ndef inverse_transform(images):\n return (images+1.)/2.\n\n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
LYHTHU/MixMatch-pytorch
[ "a738cc95aae88f76761aeeb405201bc7ae200e7d" ]
[ "dataset/cifar10.py" ]
[ "import numpy as np\nfrom PIL import Image\n\nimport torchvision\nimport torch\n\nclass TransformTwice:\n def __init__(self, transform):\n self.transform = transform\n\n def __call__(self, inp):\n out1 = self.transform(inp)\n out2 = self.transform(inp)\n return out1, out2\n\ndef get_cifar10(root, n_labeled,\n transform_train=None, transform_val=None,\n download=True):\n\n base_dataset = torchvision.datasets.CIFAR10(root, train=True, download=download)\n train_labeled_idxs, train_unlabeled_idxs, val_idxs = train_val_split(base_dataset.targets, int(n_labeled/10))\n\n train_labeled_dataset = CIFAR10_labeled(root, train_labeled_idxs, train=True, transform=transform_train)\n train_unlabeled_dataset = CIFAR10_unlabeled(root, train_unlabeled_idxs, train=True, transform=TransformTwice(transform_train))\n val_dataset = CIFAR10_labeled(root, val_idxs, train=True, transform=transform_val, download=True)\n test_dataset = CIFAR10_labeled(root, train=False, transform=transform_val, download=True)\n\n print (f\"#Labeled: {len(train_labeled_idxs)} #Unlabeled: {len(train_unlabeled_idxs)} #Val: {len(val_idxs)}\")\n return train_labeled_dataset, train_unlabeled_dataset, val_dataset, test_dataset\n \n\ndef train_val_split(labels, n_labeled_per_class):\n labels = np.array(labels)\n train_labeled_idxs = []\n train_unlabeled_idxs = []\n val_idxs = []\n\n for i in range(10):\n idxs = np.where(labels == i)[0]\n np.random.shuffle(idxs)\n train_labeled_idxs.extend(idxs[:n_labeled_per_class])\n train_unlabeled_idxs.extend(idxs[n_labeled_per_class:-500])\n val_idxs.extend(idxs[-500:])\n np.random.shuffle(train_labeled_idxs)\n np.random.shuffle(train_unlabeled_idxs)\n np.random.shuffle(val_idxs)\n\n return train_labeled_idxs, train_unlabeled_idxs, val_idxs\n\ncifar10_mean = (0.4914, 0.4822, 0.4465) # equals np.mean(train_set.train_data, axis=(0,1,2))/255\ncifar10_std = (0.2471, 0.2435, 0.2616) # equals np.std(train_set.train_data, axis=(0,1,2))/255\n\ndef normalise(x, mean=cifar10_mean, std=cifar10_std):\n x, mean, std = [np.array(a, np.float32) for a in (x, mean, std)]\n x -= mean*255\n x *= 1.0/(255*std)\n return x\n\ndef transpose(x, source='NHWC', target='NCHW'):\n return x.transpose([source.index(d) for d in target]) \n\ndef pad(x, border=4):\n return np.pad(x, [(0, 0), (border, border), (border, border)], mode='reflect')\n\nclass RandomPadandCrop(object):\n \"\"\"Crop randomly the image.\n\n Args:\n output_size (tuple or int): Desired output size. If int, square crop\n is made.\n \"\"\"\n\n def __init__(self, output_size):\n assert isinstance(output_size, (int, tuple))\n if isinstance(output_size, int):\n self.output_size = (output_size, output_size)\n else:\n assert len(output_size) == 2\n self.output_size = output_size\n\n def __call__(self, x):\n x = pad(x, 4)\n\n h, w = x.shape[1:]\n new_h, new_w = self.output_size\n\n top = np.random.randint(0, h - new_h)\n left = np.random.randint(0, w - new_w)\n\n x = x[:, top: top + new_h, left: left + new_w]\n\n return x\n\nclass RandomFlip(object):\n \"\"\"Flip randomly the image.\n \"\"\"\n def __call__(self, x):\n if np.random.rand() < 0.5:\n x = x[:, :, ::-1]\n\n return x.copy()\n\nclass GaussianNoise(object):\n \"\"\"Add gaussian noise to the image.\n \"\"\"\n def __call__(self, x):\n c, h, w = x.shape\n x += np.random.randn(c, h, w) * 0.15\n return x\n\nclass ToTensor(object):\n \"\"\"Transform the image to tensor.\n \"\"\"\n def __call__(self, x):\n x = torch.from_numpy(x)\n return x\n\nclass CIFAR10_labeled(torchvision.datasets.CIFAR10):\n\n def __init__(self, root, indexs=None, train=True,\n transform=None, target_transform=None,\n download=False):\n super(CIFAR10_labeled, self).__init__(root, train=train,\n transform=transform, target_transform=target_transform,\n download=download)\n if indexs is not None:\n self.data = self.data[indexs]\n self.targets = np.array(self.targets)[indexs]\n self.data = transpose(normalise(self.data))\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (image, target) where target is index of the target class.\n \"\"\"\n img, target = self.data[index], self.targets[index]\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target\n \n\nclass CIFAR10_unlabeled(CIFAR10_labeled):\n\n def __init__(self, root, indexs, train=True,\n transform=None, target_transform=None,\n download=False):\n super(CIFAR10_unlabeled, self).__init__(root, indexs, train=train,\n transform=transform, target_transform=target_transform,\n download=download)\n self.targets = np.array([-1 for i in range(len(self.targets))])\n " ]
[ [ "numpy.random.shuffle", "numpy.random.randn", "numpy.where", "torch.from_numpy", "numpy.random.rand", "numpy.array", "numpy.pad", "numpy.random.randint" ] ]
lvwuyunlifan/Tensorflow_to_learn_DL
[ "c534f36b580990342219b300c418ae13c070b9a5" ]
[ "chapter4/defined_cross.py" ]
[ "#--*--coding: utf-8 --*--\n\nimport tensorflow as tf\nfrom numpy.random import RandomState\n\n\nbacth_size = 8\n\n# 两个输入节点\nx = tf.placeholder(tf.float32, shape=[None, 2], name='x-input')\n# 回归问题一般只有一个输出节点\ny_ = tf.placeholder(tf.float32, shape=[None, 1], name='y-output')\n\n# 定义了一个单层的神经网络前向传播的过程, 这里就是简单的加权和\nw1 = tf.Variable(tf.random_normal([2, 1], stddev=1, seed=1))\ny = tf.matmul(x, w1)\n\n# 定义预测多了和与预测少了的成本\nloss_more = 10\nloss_less = 1\n# 损失函数\nloss = tf.reduce_sum(tf.where(tf.greater(y, y_), (y-y_)*loss_more, (y_-y)*loss_less))\n'''\n tf.greater的输入为两个变量,比较变量的每个元素的大小,返回大True,小False\n tf.where输入三个变量,第一个为选择条件,True时选择第二个参数,False时选第三个参数\n'''\n# 优化器\noptimiter = tf.train.AdamOptimizer(0.001).minimize(loss)\n\n# 通过随机数生成一个模拟数据集\nrdm = RandomState(1)\ndataset_size = 128\nX = rdm.rand(dataset_size, 2)\n\n# 设置回归的正确值为两个输入的和加上一个随机数。之所以要加上一个随机量是为了加入不可预测的噪音,\n# 否则不同的损失函数的意义就不大了,因为不同的损失函数都会在能完全预测正确的时候最低。\n# 一般来说噪音为一个均值为0的小量,所以这里的噪音设置为-0.05~0.05的随机数\nY = [[x1 + x2 + rdm.rand()/10.0-0.05] for (x1, x2) in X]\n\n# 训练神经网络\nwith tf.Session() as sess:\n init = tf.global_variables_initializer()\n sess.run(init)\n\n epoch = 10000\n for i in range(epoch):\n start = (i * bacth_size) % dataset_size\n end = min(start+bacth_size, dataset_size)\n\n sess.run(optimiter, feed_dict={x:X[start:end], y_:Y[start:end]})\n if i % 500 == 0:\n total_loss = sess.run(loss, feed_dict={x:X, y_:Y}) \n print('After %d loss is %g' % (i, total_loss)) \n print(sess.run(w1))" ]
[ [ "tensorflow.placeholder", "tensorflow.greater", "tensorflow.global_variables_initializer", "tensorflow.train.AdamOptimizer", "tensorflow.matmul", "numpy.random.RandomState", "tensorflow.Session", "tensorflow.random_normal" ] ]
ramaneswaran/quickvision
[ "ff494ea9c6ae09c129603b35236f314b25d56d27" ]
[ "quickvision/datasets/classification.py" ]
[ "# Add code for Mapping using dataframe containaing id and target.\n# Port from pytorch_cnn_trainer\n# https://github.com/oke-aditya/pytorch_cnn_trainer\n\nimport torchvision\nfrom torchvision import datasets\nfrom torch.utils.data import Dataset\nimport os\nimport torch\nfrom PIL import Image\n\n__all__ = [\"create_folder_dataset\", \"CSVSingleLabelDataset\"]\n\n\ndef create_folder_dataset(root_dir, transforms, split: float = 0.8, **kwargs):\n \"\"\"\n Creates Train and Validation Dataset from a Root folder\n Arrange dataset as follows: -\n root/class_a/image01.png\n root/class_b/image01.png\n\n Creates train and validation dataset from this root dir.\n This applies same transforms to both train and validation\n\n Args:\n root_dir : Root directory of the dataset to read from\n transforms: Transforms to be applied to train and validation datasets.\n split: Float number denoting percentage of train items\n\n \"\"\"\n complete_dataset = datasets.ImageFolder(root_dir, transform=transforms)\n train_split = len(complete_dataset) * split\n valid_split = len(complete_dataset) * (1 - split)\n\n train_set, valid_set = torch.utils.data.random_split(complete_dataset, [train_split, valid_split])\n return train_set, valid_set\n\n\nclass CSVSingleLabelDataset(Dataset):\n \"\"\"\n Creates Torchvision Dataset From CSV File.\n Args:\n df: DataFrame with 2 columns ``image_id`` and ``target``.\n data_dir: Directory from where data is to be read.\n image_id: Column name which has IDs of the images.\n target: target column name.\n transform: Trasforms to apply while creating Dataset.\n img_type: Type of the image like `png` or `jpg` etc.\n \"\"\"\n\n def __init__(self, df, data_dir, image_id, target, transform, img_type):\n super().__init__()\n self.df = df\n self.data_dir = data_dir\n self.image_id = image_id\n self.target = target\n self.transform = transform\n self.img_type = img_type\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, idx):\n img_name = self.df[self.image_id][idx]\n label = self.df[self.target][idx]\n\n img_path = os.path.join(self.data_dir, str(img_name) + f'.{self.img_type}')\n image = Image.open(img_path)\n image = self.transform(image)\n\n return image, label\n" ]
[ [ "torch.utils.data.random_split" ] ]
bakwadunka/dunka3
[ "265ec0964087bac524da9a3f3b07bc483a466c63" ]
[ "utils.py" ]
[ "import os\nimport pickle\nimport torch\nimport numpy as np\n\ndef save(toBeSaved, filename, mode='wb'):\n dirname = os.path.dirname(filename)\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n file = open(filename, mode)\n pickle.dump(toBeSaved, file)\n file.close()\n\ndef load(filename, mode='rb'):\n file = open(filename, mode)\n loaded = pickle.load(file)\n file.close()\n return loaded\n\ndef pad_sents(sents, pad_token):\n sents_padded = []\n lens = get_lens(sents)\n max_len = max(lens)\n sents_padded = [sents[i] + [pad_token] * (max_len - l) for i, l in enumerate(lens)]\n return sents_padded\n\ndef sort_sents(sents, reverse=True):\n sents.sort(key=(lambda s: len(s)), reverse=reverse)\n return sents\n\ndef get_mask(sents, unmask_idx=1, mask_idx=0):\n lens = get_lens(sents)\n max_len = max(lens)\n mask = [([unmask_idx] * l + [mask_idx] * (max_len - l)) for l in lens]\n return mask\n\ndef get_lens(sents):\n return [len(sent) for sent in sents]\n\ndef get_max_len(sents):\n max_len = max([len(sent) for sent in sents])\n return max_len\n\ndef truncate_sents(sents, length):\n sents = [sent[:length] for sent in sents]\n return sents\n\ndef get_loss_weight(labels, label_order):\n nums = [np.sum(labels == lo) for lo in label_order]\n loss_weight = torch.tensor([n / len(labels) for n in nums])\n return loss_weight\n" ]
[ [ "numpy.sum" ] ]
lalonderodney/D-Caps
[ "47050505170472abe1ea36e50903ea06054fcf07" ]
[ "utils.py" ]
[ "import os\nimport errno\n\nimport tensorflow as tf\nfrom keras import backend as K\n\ndef safe_mkdir(dir_to_make: str) -> None:\n '''\n Attempts to make a directory following the Pythonic EAFP strategy which prevents race conditions.\n\n :param dir_to_make: The directory path to attempt to make.\n :return: None\n '''\n try:\n os.makedirs(dir_to_make)\n except OSError as e:\n if e.errno != errno.EEXIST:\n print('ERROR: Unable to create directory: {}'.format(dir_to_make), e)\n raise\n\ndef as_keras_metric(method):\n import functools\n @functools.wraps(method)\n def wrapper(self, args, **kwargs):\n \"\"\" Wrapper for turning tensorflow metrics into keras metrics \"\"\"\n value, update_op = method(self, args, **kwargs)\n K.get_session().run(tf.local_variables_initializer())\n with tf.control_dependencies([update_op]):\n value = tf.identity(value)\n return value\n return wrapper" ]
[ [ "tensorflow.identity", "tensorflow.local_variables_initializer", "tensorflow.control_dependencies" ] ]
antofuller/configaformers
[ "293253cd35d96c8a24c4004ba3d24fc6dc85a260" ]
[ "norm_module.py" ]
[ "import torch\nfrom torch import nn\nfrom utils import set_default\n\n\n# This module is dedicated to Norm Macdonald\n# Implementations from https://github.com/lucidrains/x-transformer\n\nclass RMSNorm(nn.Module):\n def __init__(self, dim, eps=1e-8):\n super().__init__()\n self.scale = dim ** -0.5\n self.eps = eps\n self.g = nn.Parameter(torch.ones(dim))\n\n def forward(self, x):\n _norm = torch.norm(x, dim=-1, keepdim=True) * self.scale\n return x / _norm.clamp(min=self.eps) * self.g\n\n\nclass ScaleNorm(nn.Module):\n def __init__(self, dim, eps=1e-5):\n super().__init__()\n self.scale = dim ** -0.5\n self.eps = eps\n self.g = nn.Parameter(torch.ones(1))\n\n def forward(self, x):\n norm = torch.norm(x, dim=-1, keepdim=True) * self.scale\n return x / norm.clamp(min=self.eps) * self.g\n\n\ndef init_norm(_key, _config, _dim):\n if _key not in _config:\n norm_bool = False\n norm_function = False\n else:\n assert type(_config[_key]) == str, f\"{_config[_key]} is type {type(_config[_key])}, but should be a string!\"\n norm_bool = True\n norm_function = get_norm(norm_type=_config[_key], dim=_dim)\n\n return norm_bool, norm_function\n\n\ndef get_norm(norm_type: str, dim: int):\n # TODO: Batch norm may involve rearranging\n norm_type = norm_type.lower() # Make lowercase\n if norm_type == 'layer_norm':\n return nn.LayerNorm(dim)\n\n elif norm_type == 'rms_norm':\n return RMSNorm(dim)\n\n elif norm_type == 'scale_norm':\n return ScaleNorm(dim)\n\n else:\n print(f\"Norm: {norm_type} not available.\")\n\n\nclass Norm(nn.Module):\n def __init__(self,\n config,\n _streams,\n ):\n super().__init__()\n \"\"\"\n Norm module\n \"\"\"\n # Configure input(s) and output(s)\n self.input_name = set_default(_look='input_name', _dict=config, _default='x')\n self.output_name = set_default(_look='output_name', _dict=config, _default='x')\n\n self.input_dim = _streams[self.input_name][-1]\n input_shape = _streams[self.input_name]\n\n # Configuring norm\n norm_name = set_default(_look='norm_type', _dict=config, _default='layer_norm')\n self.norm = get_norm(norm_type=norm_name, dim=self.input_dim)\n\n # Prepare streams info\n self.streams_in_module = {'inputs': [[self.input_name, input_shape],\n ],\n\n 'outputs': [[self.output_name, input_shape],\n ]\n }\n\n def forward(self, _data):\n _data[self.output_name] = self.norm(_data[self.input_name])\n return _data\n\n\nclass ScaleAlongDimension(nn.Module):\n def __init__(self,\n config,\n _streams,\n ):\n super().__init__()\n \"\"\"\n Learned scale used in as a weighted residual, or for scaling mha heads (see NormFormer)\n \"\"\"\n # Configure input(s) and output(s)\n self.input_name = set_default(_look='input_name', _dict=config, _default='x')\n self.dim_to_scale = set_default(_look='dim_to_scale', _dict=config, _default=2, _type=int)\n self.output_name = set_default(_look='output_name', _dict=config, _default='x')\n\n self.input_shape = _streams[self.input_name]\n assert self.dim_to_scale > 0, f'dim_to_scale must be greater than 0!'\n assert self.dim_to_scale <= len(self.input_shape), f'dim_to_scale must less than or equal to the number of ' \\\n f'input dimensions!'\n num_params = self.input_shape[self.dim_to_scale]\n\n # Initialize gate to 1\n self.scale = nn.Parameter(torch.ones(num_params), requires_grad=True)\n\n # Built einsum input strings\n self.einsum_in_1 = 'abcdef' # max of 6 dims\n self.einsum_in_1 = self.einsum_in_1[:len(self.input_shape)]\n self.einsum_in_2 = self.einsum_in_1[self.dim_to_scale]\n\n print(f\"{self.einsum_in_1},{self.einsum_in_2}->{self.einsum_in_1}\")\n\n # Prepare streams info\n self.streams_in_module = {'inputs': [[self.input_name, self.input_shape],\n ],\n\n 'outputs': [[self.output_name, self.input_shape],\n ]\n }\n\n def forward(self, _data):\n _data[self.output_name] = torch.einsum(f'{self.einsum_in_1},{self.einsum_in_2}->{self.einsum_in_1}', _data[self.input_name], self.scale)\n return _data" ]
[ [ "torch.einsum", "torch.ones", "torch.nn.LayerNorm", "torch.norm" ] ]
achilleas-k/mne-python
[ "0078e1af13a92ab47498dd167bc5ec73be864427" ]
[ "mne/tests/test_cov.py" ]
[ "# Author: Alexandre Gramfort <[email protected]>\n# Denis Engemann <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport os.path as op\nimport itertools as itt\n\nfrom numpy.testing import (assert_array_almost_equal, assert_array_equal,\n assert_equal, assert_allclose)\nimport pytest\nimport numpy as np\nfrom scipy import linalg\n\nfrom mne.cov import (regularize, whiten_evoked,\n _auto_low_rank_model,\n prepare_noise_cov, compute_whitener,\n _regularized_covariance)\n\nfrom mne import (read_cov, write_cov, Epochs, merge_events,\n find_events, compute_raw_covariance,\n compute_covariance, read_evokeds, compute_proj_raw,\n pick_channels_cov, pick_types, make_ad_hoc_cov,\n make_fixed_length_events)\nfrom mne.datasets import testing\nfrom mne.fixes import _get_args\nfrom mne.io import read_raw_fif, RawArray, read_raw_ctf\nfrom mne.io.pick import _DATA_CH_TYPES_SPLIT\nfrom mne.preprocessing import maxwell_filter\nfrom mne.rank import _compute_rank_int\nfrom mne.tests.common import assert_snr\nfrom mne.utils import (_TempDir, requires_version, run_tests_if_main,\n catch_logging)\n\nbase_dir = op.join(op.dirname(__file__), '..', 'io', 'tests', 'data')\ncov_fname = op.join(base_dir, 'test-cov.fif')\ncov_gz_fname = op.join(base_dir, 'test-cov.fif.gz')\ncov_km_fname = op.join(base_dir, 'test-km-cov.fif')\nraw_fname = op.join(base_dir, 'test_raw.fif')\nave_fname = op.join(base_dir, 'test-ave.fif')\nerm_cov_fname = op.join(base_dir, 'test_erm-cov.fif')\nhp_fif_fname = op.join(base_dir, 'test_chpi_raw_sss.fif')\n\nctf_fname = op.join(testing.data_path(download=False), 'CTF',\n 'testdata_ctf.ds')\n\n\[email protected]('proj', (True, False))\[email protected]('pca', (True, 'white', False))\ndef test_compute_whitener(proj, pca):\n \"\"\"Test properties of compute_whitener.\"\"\"\n raw = read_raw_fif(raw_fname).crop(0, 3).load_data()\n raw.pick_types(eeg=True, exclude=())\n if proj:\n raw.apply_proj()\n else:\n raw.del_proj()\n with pytest.warns(RuntimeWarning, match='Too few samples'):\n cov = compute_raw_covariance(raw)\n W, _, C = compute_whitener(cov, raw.info, pca=pca, return_colorer=True,\n verbose='error')\n n_channels = len(raw.ch_names)\n n_reduced = len(raw.ch_names)\n rank = n_channels - len(raw.info['projs'])\n n_reduced = rank if pca is True else n_channels\n assert W.shape == C.shape[::-1] == (n_reduced, n_channels)\n # round-trip mults\n round_trip = np.dot(W, C)\n if pca is True:\n assert_allclose(round_trip, np.eye(n_reduced), atol=1e-7)\n elif pca == 'white':\n # Our first few rows/cols are zeroed out in the white space\n assert_allclose(round_trip[-rank:, -rank:],\n np.eye(rank), atol=1e-7)\n else:\n assert pca is False\n assert_allclose(round_trip, np.eye(n_channels), atol=0.05)\n\n\ndef test_cov_mismatch():\n \"\"\"Test estimation with MEG<->Head mismatch.\"\"\"\n raw = read_raw_fif(raw_fname).crop(0, 5).load_data()\n events = find_events(raw, stim_channel='STI 014')\n raw.pick_channels(raw.ch_names[:5])\n raw.add_proj([], remove_existing=True)\n epochs = Epochs(raw, events, None, tmin=-0.2, tmax=0., preload=True)\n for kind in ('shift', 'None'):\n epochs_2 = epochs.copy()\n # This should be fine\n compute_covariance([epochs, epochs_2])\n if kind == 'shift':\n epochs_2.info['dev_head_t']['trans'][:3, 3] += 0.001\n else: # None\n epochs_2.info['dev_head_t'] = None\n pytest.raises(ValueError, compute_covariance, [epochs, epochs_2])\n compute_covariance([epochs, epochs_2], on_mismatch='ignore')\n with pytest.raises(RuntimeWarning, match='transform mismatch'):\n compute_covariance([epochs, epochs_2], on_mismatch='warn')\n pytest.raises(ValueError, compute_covariance, epochs,\n on_mismatch='x')\n # This should work\n epochs.info['dev_head_t'] = None\n epochs_2.info['dev_head_t'] = None\n compute_covariance([epochs, epochs_2], method=None)\n\n\ndef test_cov_order():\n \"\"\"Test covariance ordering.\"\"\"\n raw = read_raw_fif(raw_fname)\n raw.set_eeg_reference(projection=True)\n info = raw.info\n # add MEG channel with low enough index number to affect EEG if\n # order is incorrect\n info['bads'] += ['MEG 0113']\n ch_names = [info['ch_names'][pick]\n for pick in pick_types(info, meg=False, eeg=True)]\n cov = read_cov(cov_fname)\n # no avg ref present warning\n prepare_noise_cov(cov, info, ch_names, verbose='error')\n # big reordering\n cov_reorder = cov.copy()\n order = np.random.RandomState(0).permutation(np.arange(len(cov.ch_names)))\n cov_reorder['names'] = [cov['names'][ii] for ii in order]\n cov_reorder['data'] = cov['data'][order][:, order]\n # Make sure we did this properly\n _assert_reorder(cov_reorder, cov, order)\n # Now check some functions that should get the same result for both\n # regularize\n with pytest.raises(ValueError, match='rank, if str'):\n regularize(cov, info, rank='foo')\n with pytest.raises(TypeError, match='rank must be'):\n regularize(cov, info, rank=False)\n with pytest.raises(TypeError, match='rank must be'):\n regularize(cov, info, rank=1.)\n cov_reg = regularize(cov, info, rank='full')\n cov_reg_reorder = regularize(cov_reorder, info, rank='full')\n _assert_reorder(cov_reg_reorder, cov_reg, order)\n # prepare_noise_cov\n cov_prep = prepare_noise_cov(cov, info, ch_names)\n cov_prep_reorder = prepare_noise_cov(cov, info, ch_names)\n _assert_reorder(cov_prep, cov_prep_reorder,\n order=np.arange(len(cov_prep['names'])))\n # compute_whitener\n whitener, w_ch_names, n_nzero = compute_whitener(\n cov, info, return_rank=True)\n assert whitener.shape[0] == whitener.shape[1]\n whitener_2, w_ch_names_2, n_nzero_2 = compute_whitener(\n cov_reorder, info, return_rank=True)\n assert_array_equal(w_ch_names_2, w_ch_names)\n assert_allclose(whitener_2, whitener)\n assert n_nzero == n_nzero_2\n # with pca\n assert n_nzero < whitener.shape[0]\n whitener_pca, w_ch_names_pca, n_nzero_pca = compute_whitener(\n cov, info, pca=True, return_rank=True)\n assert_array_equal(w_ch_names_pca, w_ch_names)\n assert n_nzero_pca == n_nzero\n assert whitener_pca.shape == (n_nzero_pca, len(w_ch_names))\n # whiten_evoked\n evoked = read_evokeds(ave_fname)[0]\n evoked_white = whiten_evoked(evoked, cov)\n evoked_white_2 = whiten_evoked(evoked, cov_reorder)\n assert_allclose(evoked_white_2.data, evoked_white.data)\n\n\ndef _assert_reorder(cov_new, cov_orig, order):\n \"\"\"Check that we get the same result under reordering.\"\"\"\n inv_order = np.argsort(order)\n assert_array_equal([cov_new['names'][ii] for ii in inv_order],\n cov_orig['names'])\n assert_allclose(cov_new['data'][inv_order][:, inv_order],\n cov_orig['data'], atol=1e-20)\n\n\ndef test_ad_hoc_cov():\n \"\"\"Test ad hoc cov creation and I/O.\"\"\"\n tempdir = _TempDir()\n out_fname = op.join(tempdir, 'test-cov.fif')\n evoked = read_evokeds(ave_fname)[0]\n cov = make_ad_hoc_cov(evoked.info)\n cov.save(out_fname)\n assert 'Covariance' in repr(cov)\n cov2 = read_cov(out_fname)\n assert_array_almost_equal(cov['data'], cov2['data'])\n std = dict(grad=2e-13, mag=10e-15, eeg=0.1e-6)\n cov = make_ad_hoc_cov(evoked.info, std)\n cov.save(out_fname)\n assert 'Covariance' in repr(cov)\n cov2 = read_cov(out_fname)\n assert_array_almost_equal(cov['data'], cov2['data'])\n\n\ndef test_io_cov():\n \"\"\"Test IO for noise covariance matrices.\"\"\"\n tempdir = _TempDir()\n cov = read_cov(cov_fname)\n cov['method'] = 'empirical'\n cov['loglik'] = -np.inf\n cov.save(op.join(tempdir, 'test-cov.fif'))\n cov2 = read_cov(op.join(tempdir, 'test-cov.fif'))\n assert_array_almost_equal(cov.data, cov2.data)\n assert_equal(cov['method'], cov2['method'])\n assert_equal(cov['loglik'], cov2['loglik'])\n assert 'Covariance' in repr(cov)\n\n cov2 = read_cov(cov_gz_fname)\n assert_array_almost_equal(cov.data, cov2.data)\n cov2.save(op.join(tempdir, 'test-cov.fif.gz'))\n cov2 = read_cov(op.join(tempdir, 'test-cov.fif.gz'))\n assert_array_almost_equal(cov.data, cov2.data)\n\n cov['bads'] = ['EEG 039']\n cov_sel = pick_channels_cov(cov, exclude=cov['bads'])\n assert cov_sel['dim'] == (len(cov['data']) - len(cov['bads']))\n assert cov_sel['data'].shape == (cov_sel['dim'], cov_sel['dim'])\n cov_sel.save(op.join(tempdir, 'test-cov.fif'))\n\n cov2 = read_cov(cov_gz_fname)\n assert_array_almost_equal(cov.data, cov2.data)\n cov2.save(op.join(tempdir, 'test-cov.fif.gz'))\n cov2 = read_cov(op.join(tempdir, 'test-cov.fif.gz'))\n assert_array_almost_equal(cov.data, cov2.data)\n\n # test warnings on bad filenames\n cov_badname = op.join(tempdir, 'test-bad-name.fif.gz')\n with pytest.warns(RuntimeWarning, match='-cov.fif'):\n write_cov(cov_badname, cov)\n with pytest.warns(RuntimeWarning, match='-cov.fif'):\n read_cov(cov_badname)\n\n\[email protected]('method', (None, ['empirical']))\ndef test_cov_estimation_on_raw(method):\n \"\"\"Test estimation from raw (typically empty room).\"\"\"\n tempdir = _TempDir()\n raw = read_raw_fif(raw_fname, preload=True)\n cov_mne = read_cov(erm_cov_fname)\n\n # The pure-string uses the more efficient numpy-based method, the\n # the list gets triaged to compute_covariance (should be equivalent\n # but use more memory)\n with pytest.warns(None): # can warn about EEG ref\n cov = compute_raw_covariance(raw, tstep=None, method=method,\n rank='full')\n assert_equal(cov.ch_names, cov_mne.ch_names)\n assert_equal(cov.nfree, cov_mne.nfree)\n assert_snr(cov.data, cov_mne.data, 1e4)\n\n # tstep=0.2 (default)\n with pytest.warns(None): # can warn about EEG ref\n cov = compute_raw_covariance(raw, method=method, rank='full')\n assert_equal(cov.nfree, cov_mne.nfree - 119) # cutoff some samples\n assert_snr(cov.data, cov_mne.data, 1e2)\n\n # test IO when computation done in Python\n cov.save(op.join(tempdir, 'test-cov.fif')) # test saving\n cov_read = read_cov(op.join(tempdir, 'test-cov.fif'))\n assert cov_read.ch_names == cov.ch_names\n assert cov_read.nfree == cov.nfree\n assert_array_almost_equal(cov.data, cov_read.data)\n\n # test with a subset of channels\n raw_pick = raw.copy().pick_channels(raw.ch_names[:5])\n raw_pick.info.normalize_proj()\n cov = compute_raw_covariance(raw_pick, tstep=None, method=method,\n rank='full')\n assert cov_mne.ch_names[:5] == cov.ch_names\n assert_snr(cov.data, cov_mne.data[:5, :5], 1e4)\n cov = compute_raw_covariance(raw_pick, method=method, rank='full')\n assert_snr(cov.data, cov_mne.data[:5, :5], 90) # cutoff samps\n # make sure we get a warning with too short a segment\n raw_2 = read_raw_fif(raw_fname).crop(0, 1)\n with pytest.warns(RuntimeWarning, match='Too few samples'):\n cov = compute_raw_covariance(raw_2, method=method)\n # no epochs found due to rejection\n pytest.raises(ValueError, compute_raw_covariance, raw, tstep=None,\n method='empirical', reject=dict(eog=200e-6))\n # but this should work\n cov = compute_raw_covariance(raw.copy().crop(0, 10.),\n tstep=None, method=method,\n reject=dict(eog=1000e-6),\n verbose='error')\n\n\[email protected]\n@requires_version('sklearn', '0.15')\ndef test_cov_estimation_on_raw_reg():\n \"\"\"Test estimation from raw with regularization.\"\"\"\n raw = read_raw_fif(raw_fname, preload=True)\n raw.info['sfreq'] /= 10.\n raw = RawArray(raw._data[:, ::10].copy(), raw.info) # decimate for speed\n cov_mne = read_cov(erm_cov_fname)\n with pytest.warns(RuntimeWarning, match='Too few samples'):\n # XXX don't use \"shrunk\" here, for some reason it makes Travis 2.7\n # hang... \"diagonal_fixed\" is much faster. Use long epochs for speed.\n cov = compute_raw_covariance(raw, tstep=5., method='diagonal_fixed')\n assert_snr(cov.data, cov_mne.data, 5)\n\n\ndef _assert_cov(cov, cov_desired, tol=0.005, nfree=True):\n assert_equal(cov.ch_names, cov_desired.ch_names)\n err = (linalg.norm(cov.data - cov_desired.data, ord='fro') /\n linalg.norm(cov.data, ord='fro'))\n assert err < tol, '%s >= %s' % (err, tol)\n if nfree:\n assert_equal(cov.nfree, cov_desired.nfree)\n\n\[email protected]\[email protected]('rank', ('full', None))\ndef test_cov_estimation_with_triggers(rank):\n \"\"\"Test estimation from raw with triggers.\"\"\"\n tempdir = _TempDir()\n raw = read_raw_fif(raw_fname)\n raw.set_eeg_reference(projection=True).load_data()\n events = find_events(raw, stim_channel='STI 014')\n event_ids = [1, 2, 3, 4]\n reject = dict(grad=10000e-13, mag=4e-12, eeg=80e-6, eog=150e-6)\n\n # cov with merged events and keep_sample_mean=True\n events_merged = merge_events(events, event_ids, 1234)\n epochs = Epochs(raw, events_merged, 1234, tmin=-0.2, tmax=0,\n baseline=(-0.2, -0.1), proj=True,\n reject=reject, preload=True)\n\n cov = compute_covariance(epochs, keep_sample_mean=True)\n _assert_cov(cov, read_cov(cov_km_fname))\n\n # Test with tmin and tmax (different but not too much)\n cov_tmin_tmax = compute_covariance(epochs, tmin=-0.19, tmax=-0.01)\n assert np.all(cov.data != cov_tmin_tmax.data)\n err = (linalg.norm(cov.data - cov_tmin_tmax.data, ord='fro') /\n linalg.norm(cov_tmin_tmax.data, ord='fro'))\n assert err < 0.05\n\n # cov using a list of epochs and keep_sample_mean=True\n epochs = [Epochs(raw, events, ev_id, tmin=-0.2, tmax=0,\n baseline=(-0.2, -0.1), proj=True, reject=reject)\n for ev_id in event_ids]\n cov2 = compute_covariance(epochs, keep_sample_mean=True)\n assert_array_almost_equal(cov.data, cov2.data)\n assert cov.ch_names == cov2.ch_names\n\n # cov with keep_sample_mean=False using a list of epochs\n cov = compute_covariance(epochs, keep_sample_mean=False)\n _assert_cov(cov, read_cov(cov_fname), nfree=False)\n\n method_params = {'empirical': {'assume_centered': False}}\n pytest.raises(ValueError, compute_covariance, epochs,\n keep_sample_mean=False, method_params=method_params)\n pytest.raises(ValueError, compute_covariance, epochs,\n keep_sample_mean=False, method='shrunk', rank=rank)\n\n # test IO when computation done in Python\n cov.save(op.join(tempdir, 'test-cov.fif')) # test saving\n cov_read = read_cov(op.join(tempdir, 'test-cov.fif'))\n _assert_cov(cov, cov_read, 1e-5)\n\n # cov with list of epochs with different projectors\n epochs = [Epochs(raw, events[:1], None, tmin=-0.2, tmax=0,\n baseline=(-0.2, -0.1), proj=True),\n Epochs(raw, events[:1], None, tmin=-0.2, tmax=0,\n baseline=(-0.2, -0.1), proj=False)]\n # these should fail\n pytest.raises(ValueError, compute_covariance, epochs)\n pytest.raises(ValueError, compute_covariance, epochs, projs=None)\n # these should work, but won't be equal to above\n with pytest.warns(RuntimeWarning, match='Too few samples'):\n cov = compute_covariance(epochs, projs=epochs[0].info['projs'])\n with pytest.warns(RuntimeWarning, match='Too few samples'):\n cov = compute_covariance(epochs, projs=[])\n\n # test new dict support\n epochs = Epochs(raw, events, dict(a=1, b=2, c=3, d=4), tmin=-0.01, tmax=0,\n proj=True, reject=reject, preload=True)\n with pytest.warns(RuntimeWarning, match='Too few samples'):\n compute_covariance(epochs)\n with pytest.warns(RuntimeWarning, match='Too few samples'):\n compute_covariance(epochs, projs=[])\n pytest.raises(TypeError, compute_covariance, epochs, projs='foo')\n pytest.raises(TypeError, compute_covariance, epochs, projs=['foo'])\n\n\ndef test_arithmetic_cov():\n \"\"\"Test arithmetic with noise covariance matrices.\"\"\"\n cov = read_cov(cov_fname)\n cov_sum = cov + cov\n assert_array_almost_equal(2 * cov.nfree, cov_sum.nfree)\n assert_array_almost_equal(2 * cov.data, cov_sum.data)\n assert cov.ch_names == cov_sum.ch_names\n\n cov += cov\n assert_array_almost_equal(cov_sum.nfree, cov.nfree)\n assert_array_almost_equal(cov_sum.data, cov.data)\n assert cov_sum.ch_names == cov.ch_names\n\n\ndef test_regularize_cov():\n \"\"\"Test cov regularization.\"\"\"\n raw = read_raw_fif(raw_fname)\n raw.info['bads'].append(raw.ch_names[0]) # test with bad channels\n noise_cov = read_cov(cov_fname)\n # Regularize noise cov\n reg_noise_cov = regularize(noise_cov, raw.info,\n mag=0.1, grad=0.1, eeg=0.1, proj=True,\n exclude='bads', rank='full')\n assert noise_cov['dim'] == reg_noise_cov['dim']\n assert noise_cov['data'].shape == reg_noise_cov['data'].shape\n assert np.mean(noise_cov['data'] < reg_noise_cov['data']) < 0.08\n # make sure all args are represented\n assert set(_DATA_CH_TYPES_SPLIT) - set(_get_args(regularize)) == set()\n\n\ndef test_whiten_evoked():\n \"\"\"Test whitening of evoked data.\"\"\"\n evoked = read_evokeds(ave_fname, condition=0, baseline=(None, 0),\n proj=True)\n cov = read_cov(cov_fname)\n\n ###########################################################################\n # Show result\n picks = pick_types(evoked.info, meg=True, eeg=True, ref_meg=False,\n exclude='bads')\n\n noise_cov = regularize(cov, evoked.info, grad=0.1, mag=0.1, eeg=0.1,\n exclude='bads', rank='full')\n\n evoked_white = whiten_evoked(evoked, noise_cov, picks, diag=True)\n whiten_baseline_data = evoked_white.data[picks][:, evoked.times < 0]\n mean_baseline = np.mean(np.abs(whiten_baseline_data), axis=1)\n assert np.all(mean_baseline < 1.)\n assert np.all(mean_baseline > 0.2)\n\n # degenerate\n cov_bad = pick_channels_cov(cov, include=evoked.ch_names[:10])\n pytest.raises(RuntimeError, whiten_evoked, evoked, cov_bad, picks)\n\n\ndef test_regularized_covariance():\n \"\"\"Test unchanged data with regularized_covariance.\"\"\"\n evoked = read_evokeds(ave_fname, condition=0, baseline=(None, 0),\n proj=True)\n data = evoked.data.copy()\n # check that input data remain unchanged. gh-5698\n _regularized_covariance(data)\n assert_allclose(data, evoked.data, atol=1e-20)\n\n\n@requires_version('sklearn', '0.15')\ndef test_auto_low_rank():\n \"\"\"Test probabilistic low rank estimators.\"\"\"\n n_samples, n_features, rank = 400, 10, 5\n sigma = 0.1\n\n def get_data(n_samples, n_features, rank, sigma):\n rng = np.random.RandomState(42)\n W = rng.randn(n_features, n_features)\n X = rng.randn(n_samples, rank)\n U, _, _ = linalg.svd(W.copy())\n X = np.dot(X, U[:, :rank].T)\n\n sigmas = sigma * rng.rand(n_features) + sigma / 2.\n X += rng.randn(n_samples, n_features) * sigmas\n return X\n\n X = get_data(n_samples=n_samples, n_features=n_features, rank=rank,\n sigma=sigma)\n method_params = {'iter_n_components': [4, 5, 6]}\n cv = 3\n n_jobs = 1\n mode = 'factor_analysis'\n rescale = 1e8\n X *= rescale\n est, info = _auto_low_rank_model(X, mode=mode, n_jobs=n_jobs,\n method_params=method_params,\n cv=cv)\n assert_equal(info['best'], rank)\n\n X = get_data(n_samples=n_samples, n_features=n_features, rank=rank,\n sigma=sigma)\n method_params = {'iter_n_components': [n_features + 5]}\n msg = ('You are trying to estimate %i components on matrix '\n 'with %i features.') % (n_features + 5, n_features)\n with pytest.warns(RuntimeWarning, match=msg):\n _auto_low_rank_model(X, mode=mode, n_jobs=n_jobs,\n method_params=method_params, cv=cv)\n\n\[email protected]\[email protected]('rank', ('full', None, 'info'))\n@requires_version('sklearn', '0.15')\ndef test_compute_covariance_auto_reg(rank):\n \"\"\"Test automated regularization.\"\"\"\n raw = read_raw_fif(raw_fname, preload=True)\n raw.resample(100, npad='auto') # much faster estimation\n events = find_events(raw, stim_channel='STI 014')\n event_ids = [1, 2, 3, 4]\n reject = dict(mag=4e-12)\n\n # cov with merged events and keep_sample_mean=True\n events_merged = merge_events(events, event_ids, 1234)\n # we need a few channels for numerical reasons in PCA/FA\n picks = pick_types(raw.info, meg='mag', eeg=False)[:10]\n raw.pick_channels([raw.ch_names[pick] for pick in picks])\n raw.info.normalize_proj()\n epochs = Epochs(\n raw, events_merged, 1234, tmin=-0.2, tmax=0,\n baseline=(-0.2, -0.1), proj=True, reject=reject, preload=True)\n epochs = epochs.crop(None, 0)[:5]\n\n method_params = dict(factor_analysis=dict(iter_n_components=[3]),\n pca=dict(iter_n_components=[3]))\n\n covs = compute_covariance(epochs, method='auto',\n method_params=method_params,\n return_estimators=True, rank=rank)\n # make sure regularization produces structured differencess\n diag_mask = np.eye(len(epochs.ch_names)).astype(bool)\n off_diag_mask = np.invert(diag_mask)\n for cov_a, cov_b in itt.combinations(covs, 2):\n if (cov_a['method'] == 'diagonal_fixed' and\n # here we have diagnoal or no regularization.\n cov_b['method'] == 'empirical' and rank == 'full'):\n\n assert not np.any(cov_a['data'][diag_mask] ==\n cov_b['data'][diag_mask])\n\n # but the rest is the same\n assert_array_equal(cov_a['data'][off_diag_mask],\n cov_b['data'][off_diag_mask])\n\n else:\n # and here we have shrinkage everywhere.\n assert not np.any(cov_a['data'][diag_mask] ==\n cov_b['data'][diag_mask])\n\n assert not np.any(cov_a['data'][diag_mask] ==\n cov_b['data'][diag_mask])\n\n logliks = [c['loglik'] for c in covs]\n assert np.diff(logliks).max() <= 0 # descending order\n\n methods = ['empirical', 'ledoit_wolf', 'oas', 'shrunk', 'shrinkage']\n if rank == 'full':\n methods.extend(['factor_analysis', 'pca'])\n with catch_logging() as log:\n cov3 = compute_covariance(epochs, method=methods,\n method_params=method_params, projs=None,\n return_estimators=True, rank=rank,\n verbose=True)\n log = log.getvalue().split('\\n')\n if rank is None:\n assert 'Not doing PCA for MAG.' in log\n assert 'Reducing data rank from 10 -> 7' in log\n else:\n assert 'Reducing' not in log\n method_names = [cov['method'] for cov in cov3]\n best_bounds = [-45, -35]\n bounds = [-55, -45] if rank == 'full' else best_bounds\n for method in set(methods) - {'empirical', 'shrunk'}:\n this_lik = cov3[method_names.index(method)]['loglik']\n assert bounds[0] < this_lik < bounds[1]\n this_lik = cov3[method_names.index('shrunk')]['loglik']\n assert best_bounds[0] < this_lik < best_bounds[1]\n this_lik = cov3[method_names.index('empirical')]['loglik']\n bounds = [-110, -100] if rank == 'full' else best_bounds\n assert bounds[0] < this_lik < bounds[1]\n\n assert_equal({c['method'] for c in cov3}, set(methods))\n\n cov4 = compute_covariance(epochs, method=methods,\n method_params=method_params, projs=None,\n return_estimators=False, rank=rank)\n assert cov3[0]['method'] == cov4['method'] # ordering\n\n # invalid prespecified method\n pytest.raises(ValueError, compute_covariance, epochs, method='pizza')\n\n # invalid scalings\n pytest.raises(ValueError, compute_covariance, epochs, method='shrunk',\n scalings=dict(misc=123))\n\n\ndef _cov_rank(cov, info, proj=True):\n # ignore warnings about rank mismatches: sometimes we will intentionally\n # violate the computed/info assumption, such as when using SSS with\n # `rank='full'`\n with pytest.warns(None):\n return _compute_rank_int(cov, info=info, proj=proj)\n\n\[email protected](scope='module')\ndef raw_epochs_events():\n \"\"\"Create raw, epochs, and events for tests.\"\"\"\n raw = read_raw_fif(raw_fname).set_eeg_reference(projection=True).crop(0, 3)\n raw = maxwell_filter(raw, regularize=None) # heavily reduce the rank\n assert raw.info['bads'] == [] # no bads\n events = make_fixed_length_events(raw)\n epochs = Epochs(raw, events, tmin=-0.2, tmax=0, preload=True)\n return (raw, epochs, events)\n\n\n@requires_version('sklearn', '0.15')\[email protected]('rank', (None, 'full', 'info'))\ndef test_low_rank_methods(rank, raw_epochs_events):\n \"\"\"Test low-rank covariance matrix estimation.\"\"\"\n epochs = raw_epochs_events[1]\n sss_proj_rank = 139 # 80 MEG + 60 EEG - 1 proj\n n_ch = 366\n methods = ('empirical', 'diagonal_fixed', 'oas')\n bounds = {\n 'None': dict(empirical=(-6000, -5000),\n diagonal_fixed=(-1500, -500),\n oas=(-700, -600)),\n 'full': dict(empirical=(-9000, -8000),\n diagonal_fixed=(-2000, -1600),\n oas=(-1600, -1000)),\n 'info': dict(empirical=(-6000, -5000),\n diagonal_fixed=(-700, -600),\n oas=(-700, -600)),\n }\n with pytest.warns(RuntimeWarning, match='Too few samples'):\n covs = compute_covariance(\n epochs, method=methods, return_estimators=True, rank=rank,\n verbose=True)\n for cov in covs:\n method = cov['method']\n these_bounds = bounds[str(rank)][method]\n this_rank = _cov_rank(cov, epochs.info, proj=(rank != 'full'))\n if rank == 'full' and method != 'empirical':\n assert this_rank == n_ch\n else:\n assert this_rank == sss_proj_rank\n assert these_bounds[0] < cov['loglik'] < these_bounds[1], \\\n (rank, method)\n\n\n@requires_version('sklearn', '0.15')\ndef test_low_rank_cov(raw_epochs_events):\n \"\"\"Test additional properties of low rank computations.\"\"\"\n raw, epochs, events = raw_epochs_events\n sss_proj_rank = 139 # 80 MEG + 60 EEG - 1 proj\n n_ch = 366\n proj_rank = 365 # one EEG proj\n with pytest.warns(RuntimeWarning, match='Too few samples'):\n emp_cov = compute_covariance(epochs)\n # Test equivalence with mne.cov.regularize subspace\n with pytest.raises(ValueError, match='are dependent.*must equal'):\n regularize(emp_cov, epochs.info, rank=None, mag=0.1, grad=0.2)\n assert _cov_rank(emp_cov, epochs.info) == sss_proj_rank\n reg_cov = regularize(emp_cov, epochs.info, proj=True, rank='full')\n assert _cov_rank(reg_cov, epochs.info) == proj_rank\n with pytest.warns(RuntimeWarning, match='exceeds the theoretical'):\n _compute_rank_int(reg_cov, info=epochs.info)\n del reg_cov\n with catch_logging() as log:\n reg_r_cov = regularize(emp_cov, epochs.info, proj=True, rank=None,\n verbose=True)\n log = log.getvalue()\n assert 'jointly' in log\n assert _cov_rank(reg_r_cov, epochs.info) == sss_proj_rank\n reg_r_only_cov = regularize(emp_cov, epochs.info, proj=False, rank=None)\n assert _cov_rank(reg_r_only_cov, epochs.info) == sss_proj_rank\n assert_allclose(reg_r_only_cov['data'], reg_r_cov['data'])\n del reg_r_only_cov, reg_r_cov\n\n # test that rank=306 is same as rank='full'\n epochs_meg = epochs.copy().pick_types()\n assert len(epochs_meg.ch_names) == 306\n epochs_meg.info.update(bads=[], projs=[])\n cov_full = compute_covariance(epochs_meg, method='oas',\n rank='full', verbose='error')\n assert _cov_rank(cov_full, epochs_meg.info) == 306\n with pytest.deprecated_call(match='int is deprecated'):\n cov_dict = compute_covariance(epochs_meg, method='oas', rank=306)\n assert _cov_rank(cov_dict, epochs_meg.info) == 306\n assert_allclose(cov_full['data'], cov_dict['data'])\n cov_dict = compute_covariance(epochs_meg, method='oas',\n rank=dict(meg=306), verbose='error')\n assert _cov_rank(cov_dict, epochs_meg.info) == 306\n assert_allclose(cov_full['data'], cov_dict['data'])\n\n # Work with just EEG data to simplify projection / rank reduction\n raw = raw.copy().pick_types(meg=False, eeg=True)\n n_proj = 2\n raw.add_proj(compute_proj_raw(raw, n_eeg=n_proj))\n n_ch = len(raw.ch_names)\n rank = n_ch - n_proj - 1 # plus avg proj\n assert len(raw.info['projs']) == 3\n epochs = Epochs(raw, events, tmin=-0.2, tmax=0, preload=True)\n assert len(raw.ch_names) == n_ch\n emp_cov = compute_covariance(epochs, rank='full', verbose='error')\n assert _cov_rank(emp_cov, epochs.info) == rank\n reg_cov = regularize(emp_cov, epochs.info, proj=True, rank='full')\n assert _cov_rank(reg_cov, epochs.info) == rank\n reg_r_cov = regularize(emp_cov, epochs.info, proj=False, rank=None)\n assert _cov_rank(reg_r_cov, epochs.info) == rank\n dia_cov = compute_covariance(epochs, rank=None, method='diagonal_fixed',\n verbose='error')\n assert _cov_rank(dia_cov, epochs.info) == rank\n assert_allclose(dia_cov['data'], reg_cov['data'])\n # test our deprecation: can simply remove later\n epochs.pick_channels(epochs.ch_names[:103])\n # degenerate\n with pytest.raises(ValueError, match='can.*only be used with rank=\"full\"'):\n compute_covariance(epochs, rank=None, method='pca')\n with pytest.raises(ValueError, match='can.*only be used with rank=\"full\"'):\n compute_covariance(epochs, rank=None, method='factor_analysis')\n\n\[email protected]_testing_data\n@requires_version('sklearn', '0.15')\ndef test_cov_ctf():\n \"\"\"Test basic cov computation on ctf data with/without compensation.\"\"\"\n raw = read_raw_ctf(ctf_fname).crop(0., 2.).load_data()\n events = make_fixed_length_events(raw, 99999)\n assert len(events) == 2\n ch_names = [raw.info['ch_names'][pick]\n for pick in pick_types(raw.info, meg=True, eeg=False,\n ref_meg=False)]\n\n for comp in [0, 1]:\n raw.apply_gradient_compensation(comp)\n epochs = Epochs(raw, events, None, -0.2, 0.2, preload=True)\n with pytest.warns(RuntimeWarning, match='Too few samples'):\n noise_cov = compute_covariance(epochs, tmax=0.,\n method=['empirical'])\n prepare_noise_cov(noise_cov, raw.info, ch_names)\n\n raw.apply_gradient_compensation(0)\n epochs = Epochs(raw, events, None, -0.2, 0.2, preload=True)\n with pytest.warns(RuntimeWarning, match='Too few samples'):\n noise_cov = compute_covariance(epochs, tmax=0., method=['empirical'])\n raw.apply_gradient_compensation(1)\n\n # TODO This next call in principle should fail.\n prepare_noise_cov(noise_cov, raw.info, ch_names)\n\n # make sure comps matrices was not removed from raw\n assert raw.info['comps'], 'Comps matrices removed'\n\n\nrun_tests_if_main()\n" ]
[ [ "numpy.eye", "scipy.linalg.norm", "numpy.diff", "numpy.testing.assert_equal", "numpy.invert", "numpy.any", "numpy.argsort", "numpy.testing.assert_array_equal", "numpy.abs", "numpy.random.RandomState", "numpy.testing.assert_array_almost_equal", "numpy.all", "numpy.testing.assert_allclose", "numpy.dot", "numpy.mean" ] ]
masap/optuna
[ "f56cea87c4771d53b39f441e727d733dd1785557" ]
[ "optuna/samplers/_tpe/parzen_estimator.py" ]
[ "from typing import Callable\nfrom typing import Dict\nfrom typing import NamedTuple\nfrom typing import Optional\nfrom typing import Tuple\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom optuna import distributions\nfrom optuna._imports import _LazyImport\nfrom optuna.distributions import BaseDistribution\n\n\nif TYPE_CHECKING:\n import scipy.special as special\n import scipy.stats as stats\nelse:\n special = _LazyImport(\"scipy.special\")\n stats = _LazyImport(\"scipy.stats\")\n\n\nEPS = 1e-12\nSIGMA0_MAGNITUDE = 0.2\n\n_DISTRIBUTION_CLASSES = (\n distributions.CategoricalDistribution,\n distributions.FloatDistribution,\n distributions.IntDistribution,\n)\n\n\nclass _ParzenEstimatorParameters(\n NamedTuple(\n \"_ParzenEstimatorParameters\",\n [\n (\"consider_prior\", bool),\n (\"prior_weight\", Optional[float]),\n (\"consider_magic_clip\", bool),\n (\"consider_endpoints\", bool),\n (\"weights\", Callable[[int], np.ndarray]),\n (\"multivariate\", bool),\n ],\n )\n):\n pass\n\n\nclass _ParzenEstimator:\n def __init__(\n self,\n observations: Dict[str, np.ndarray],\n search_space: Dict[str, BaseDistribution],\n parameters: _ParzenEstimatorParameters,\n predetermined_weights: Optional[np.ndarray] = None,\n ) -> None:\n\n self._search_space = search_space\n self._parameters = parameters\n self._n_observations = next(iter(observations.values())).size\n if predetermined_weights is not None:\n assert self._n_observations == len(predetermined_weights)\n self._weights = self._calculate_weights(predetermined_weights)\n\n self._low: Dict[str, Optional[float]] = {}\n self._high: Dict[str, Optional[float]] = {}\n self._q: Dict[str, Optional[float]] = {}\n for param_name, dist in search_space.items():\n if isinstance(dist, distributions.CategoricalDistribution):\n low = high = q = None\n else:\n low, high, q = self._calculate_parzen_bounds(dist)\n self._low[param_name] = low\n self._high[param_name] = high\n self._q[param_name] = q\n\n # `_low`, `_high`, `_q` are needed for transformation.\n observations = self._transform_to_uniform(observations)\n\n # Transformed `observations` might be needed for following operations.\n self._sigmas0 = self._precompute_sigmas0(observations)\n\n self._mus: Dict[str, Optional[np.ndarray]] = {}\n self._sigmas: Dict[str, Optional[np.ndarray]] = {}\n self._categorical_weights: Dict[str, Optional[np.ndarray]] = {}\n categorical_weights: Optional[np.ndarray]\n for param_name, dist in search_space.items():\n param_observations = observations[param_name]\n if isinstance(dist, distributions.CategoricalDistribution):\n mus = sigmas = None\n categorical_weights = self._calculate_categorical_params(\n param_observations, param_name\n )\n else:\n mus, sigmas = self._calculate_numerical_params(param_observations, param_name)\n categorical_weights = None\n self._mus[param_name] = mus\n self._sigmas[param_name] = sigmas\n self._categorical_weights[param_name] = categorical_weights\n\n def sample(self, rng: np.random.RandomState, size: int) -> Dict[str, np.ndarray]:\n\n samples_dict = {}\n active = rng.choice(len(self._weights), size, p=self._weights)\n\n for param_name, dist in self._search_space.items():\n\n if isinstance(dist, distributions.CategoricalDistribution):\n categorical_weights = self._categorical_weights[param_name]\n assert categorical_weights is not None\n weights = categorical_weights[active, :]\n samples = _ParzenEstimator._sample_from_categorical_dist(rng, weights)\n\n else:\n # We restore parameters of parzen estimators.\n low = self._low[param_name]\n high = self._high[param_name]\n mus = self._mus[param_name]\n sigmas = self._sigmas[param_name]\n assert low is not None\n assert high is not None\n assert mus is not None\n assert sigmas is not None\n\n # We sample from truncnorm.\n trunc_low = (low - mus[active]) / sigmas[active]\n trunc_high = (high - mus[active]) / sigmas[active]\n samples = np.full((), fill_value=high + 1.0, dtype=np.float64)\n while (samples >= high).any():\n samples = np.where(\n samples < high,\n samples,\n stats.truncnorm.rvs(\n trunc_low,\n trunc_high,\n size=size,\n loc=mus[active],\n scale=sigmas[active],\n random_state=rng,\n ),\n )\n samples_dict[param_name] = samples\n samples_dict = self._transform_from_uniform(samples_dict)\n return samples_dict\n\n def log_pdf(self, samples_dict: Dict[str, np.ndarray]) -> np.ndarray:\n\n samples_dict = self._transform_to_uniform(samples_dict)\n n_observations = len(self._weights)\n n_samples = next(iter(samples_dict.values())).size\n if n_samples == 0:\n return np.asarray([], dtype=float)\n\n # When the search space is one CategoricalDistribution, we use the faster processing,\n # whose computation result is equivalent to the general one.\n if len(self._search_space.items()) == 1:\n param_name, dist = list(self._search_space.items())[0]\n if isinstance(dist, distributions.CategoricalDistribution):\n samples = samples_dict[param_name]\n categorical_weights = self._categorical_weights[param_name]\n assert categorical_weights is not None\n ret = np.log(np.inner(categorical_weights.T, self._weights))[samples]\n return ret\n\n # We compute log pdf (component_log_pdf)\n # for each sample in samples_dict (of size n_samples)\n # for each component of `_MultivariateParzenEstimator` (of size n_observations).\n component_log_pdf = np.zeros((n_samples, n_observations))\n for param_name, dist in self._search_space.items():\n samples = samples_dict[param_name]\n if isinstance(dist, distributions.CategoricalDistribution):\n categorical_weights = self._categorical_weights[param_name]\n assert categorical_weights is not None\n log_pdf = np.log(categorical_weights.T[samples, :])\n else:\n # We restore parameters of parzen estimators.\n low = np.asarray(self._low[param_name])\n high = np.asarray(self._high[param_name])\n q = self._q[param_name]\n mus = self._mus[param_name]\n sigmas = self._sigmas[param_name]\n assert low is not None\n assert high is not None\n assert mus is not None\n assert sigmas is not None\n\n cdf_func = _ParzenEstimator._normal_cdf\n p_accept = cdf_func(high, mus, sigmas) - cdf_func(low, mus, sigmas)\n if q is None:\n distance = samples[:, None] - mus\n mahalanobis = distance / np.maximum(sigmas, EPS)\n z = np.sqrt(2 * np.pi) * sigmas\n coefficient = 1 / z / p_accept\n log_pdf = -0.5 * mahalanobis**2 + np.log(coefficient)\n else:\n upper_bound = np.minimum(samples + q / 2.0, high)\n lower_bound = np.maximum(samples - q / 2.0, low)\n cdf = cdf_func(upper_bound[:, None], mus[None], sigmas[None]) - cdf_func(\n lower_bound[:, None], mus[None], sigmas[None]\n )\n log_pdf = np.log(cdf + EPS) - np.log(p_accept + EPS)\n component_log_pdf += log_pdf\n ret = special.logsumexp(component_log_pdf + np.log(self._weights), axis=1)\n return ret\n\n def _calculate_weights(self, predetermined_weights: Optional[np.ndarray]) -> np.ndarray:\n\n # We decide the weights.\n consider_prior = self._parameters.consider_prior\n prior_weight = self._parameters.prior_weight\n weights_func = self._parameters.weights\n n_observations = self._n_observations\n\n if n_observations == 0:\n consider_prior = True\n\n if predetermined_weights is None:\n w = weights_func(n_observations)[:n_observations]\n else:\n w = predetermined_weights[:n_observations]\n\n if consider_prior:\n # TODO(HideakiImamura) Raise `ValueError` if the weight function returns an ndarray of\n # unexpected size.\n weights = np.zeros(n_observations + 1)\n weights[:-1] = w\n weights[-1] = prior_weight\n else:\n weights = w\n weights /= weights.sum()\n return weights\n\n def _calculate_parzen_bounds(\n self, distribution: BaseDistribution\n ) -> Tuple[Optional[float], Optional[float], Optional[float]]:\n\n # We calculate low and high.\n if isinstance(distribution, distributions.FloatDistribution):\n if distribution.log:\n low = np.log(distribution.low)\n high = np.log(distribution.high)\n q = None\n elif distribution.step is not None:\n q = distribution.step\n low = distribution.low - 0.5 * q\n high = distribution.high + 0.5 * q\n else:\n low = distribution.low\n high = distribution.high\n q = None\n elif isinstance(distribution, distributions.IntDistribution):\n if distribution.log:\n low = np.log(distribution.low - 0.5)\n high = np.log(distribution.high + 0.5)\n q = None\n else:\n q = distribution.step\n low = distribution.low - 0.5 * q\n high = distribution.high + 0.5 * q\n else:\n distribution_list = [\n distributions.CategoricalDistribution.__name__,\n distributions.FloatDistribution.__name__,\n distributions.IntDistribution.__name__,\n ]\n raise NotImplementedError(\n \"The distribution {} is not implemented. \"\n \"The parameter distribution should be one of the {}\".format(\n distribution, distribution_list\n )\n )\n\n assert low < high\n\n return low, high, q\n\n def _transform_to_uniform(self, samples_dict: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]:\n\n transformed = {}\n for param_name, samples in samples_dict.items():\n distribution = self._search_space[param_name]\n\n assert isinstance(distribution, _DISTRIBUTION_CLASSES)\n if isinstance(\n distribution,\n (distributions.FloatDistribution, distributions.IntDistribution),\n ):\n if distribution.log:\n samples = np.log(samples)\n\n transformed[param_name] = samples\n return transformed\n\n def _transform_from_uniform(\n self, samples_dict: Dict[str, np.ndarray]\n ) -> Dict[str, np.ndarray]:\n\n transformed = {}\n for param_name, samples in samples_dict.items():\n distribution = self._search_space[param_name]\n\n assert isinstance(distribution, _DISTRIBUTION_CLASSES)\n if isinstance(distribution, distributions.FloatDistribution):\n if distribution.log:\n transformed[param_name] = np.exp(samples)\n elif distribution.step is not None:\n q = self._q[param_name]\n assert q is not None\n samples = np.round((samples - distribution.low) / q) * q + distribution.low\n transformed[param_name] = np.asarray(\n np.clip(samples, distribution.low, distribution.high)\n )\n else:\n transformed[param_name] = samples\n elif isinstance(distribution, distributions.IntDistribution):\n if distribution.log:\n samples = np.round(np.exp(samples))\n transformed[param_name] = np.asarray(\n np.clip(samples, distribution.low, distribution.high)\n )\n else:\n q = self._q[param_name]\n assert q is not None\n samples = np.round((samples - distribution.low) / q) * q + distribution.low\n transformed[param_name] = np.asarray(\n np.clip(samples, distribution.low, distribution.high)\n )\n elif isinstance(distribution, distributions.CategoricalDistribution):\n transformed[param_name] = samples\n\n return transformed\n\n def _precompute_sigmas0(self, observations: Dict[str, np.ndarray]) -> Optional[float]:\n\n n_observations = next(iter(observations.values())).size\n n_observations = max(n_observations, 1)\n n_params = len(observations)\n\n # If it is univariate, there is no need to precompute sigmas0, so this method returns None.\n if not self._parameters.multivariate:\n return None\n\n # We use Scott's rule for bandwidth selection if the number of parameters > 1.\n # This rule was used in the BOHB paper.\n # TODO(kstoneriv3): The constant factor SIGMA0_MAGNITUDE=0.2 might not be optimal.\n return SIGMA0_MAGNITUDE * n_observations ** (-1.0 / (n_params + 4))\n\n def _calculate_categorical_params(\n self, observations: np.ndarray, param_name: str\n ) -> np.ndarray:\n\n # TODO(kstoneriv3): This the bandwidth selection rule might not be optimal.\n observations = observations.astype(int)\n n_observations = self._n_observations\n consider_prior = self._parameters.consider_prior\n prior_weight = self._parameters.prior_weight\n distribution = self._search_space[param_name]\n assert isinstance(distribution, distributions.CategoricalDistribution)\n choices = distribution.choices\n\n if n_observations == 0:\n consider_prior = True\n\n if consider_prior:\n shape = (n_observations + 1, len(choices))\n assert prior_weight is not None\n value = prior_weight / (n_observations + 1)\n else:\n shape = (n_observations, len(choices))\n assert prior_weight is not None\n value = prior_weight / n_observations\n weights = np.full(shape, fill_value=value)\n weights[np.arange(n_observations), observations] += 1\n weights /= weights.sum(axis=1, keepdims=True)\n return weights\n\n def _calculate_numerical_params(\n self, observations: np.ndarray, param_name: str\n ) -> Tuple[np.ndarray, np.ndarray]:\n\n n_observations = self._n_observations\n consider_prior = self._parameters.consider_prior\n consider_endpoints = self._parameters.consider_endpoints\n consider_magic_clip = self._parameters.consider_magic_clip\n multivariate = self._parameters.multivariate\n sigmas0 = self._sigmas0\n low = self._low[param_name]\n high = self._high[param_name]\n assert low is not None\n assert high is not None\n assert len(observations) == self._n_observations\n\n if n_observations == 0:\n consider_prior = True\n\n prior_mu = 0.5 * (low + high)\n prior_sigma = 1.0 * (high - low)\n\n if consider_prior:\n mus = np.empty(n_observations + 1)\n mus[:n_observations] = observations\n mus[n_observations] = prior_mu\n sigmas = np.empty(n_observations + 1)\n else:\n mus = observations\n sigmas = np.empty(n_observations)\n\n if multivariate:\n assert sigmas0 is not None\n sigmas[:] = sigmas0 * (high - low)\n else:\n assert sigmas0 is None\n sorted_indices = np.argsort(mus)\n sorted_mus = mus[sorted_indices]\n sorted_mus_with_endpoints = np.empty(len(mus) + 2, dtype=float)\n sorted_mus_with_endpoints[0] = low\n sorted_mus_with_endpoints[1:-1] = sorted_mus\n sorted_mus_with_endpoints[-1] = high\n\n sorted_sigmas = np.maximum(\n sorted_mus_with_endpoints[1:-1] - sorted_mus_with_endpoints[0:-2],\n sorted_mus_with_endpoints[2:] - sorted_mus_with_endpoints[1:-1],\n )\n\n if not consider_endpoints and sorted_mus_with_endpoints.shape[0] >= 4:\n sorted_sigmas[0] = sorted_mus_with_endpoints[2] - sorted_mus_with_endpoints[1]\n sorted_sigmas[-1] = sorted_mus_with_endpoints[-2] - sorted_mus_with_endpoints[-3]\n\n sigmas[:] = sorted_sigmas[np.argsort(sorted_indices)]\n\n # We adjust the range of the 'sigmas' according to the 'consider_magic_clip' flag.\n maxsigma = 1.0 * (high - low)\n if consider_magic_clip:\n minsigma = 1.0 * (high - low) / min(100.0, (1.0 + len(mus)))\n else:\n minsigma = EPS\n sigmas = np.asarray(np.clip(sigmas, minsigma, maxsigma))\n\n if consider_prior:\n sigmas[n_observations] = prior_sigma\n\n return mus, sigmas\n\n @staticmethod\n def _normal_cdf(x: np.ndarray, mu: np.ndarray, sigma: np.ndarray) -> np.ndarray:\n\n mu, sigma = map(np.asarray, (mu, sigma))\n denominator = x - mu\n numerator = np.maximum(np.sqrt(2) * sigma, EPS)\n z = denominator / numerator\n return 0.5 * (1 + special.erf(z))\n\n @staticmethod\n def _sample_from_categorical_dist(\n rng: np.random.RandomState, probabilities: np.ndarray\n ) -> np.ndarray:\n\n n_samples = probabilities.shape[0]\n rnd_quantile = rng.rand(n_samples)\n cum_probs = np.cumsum(probabilities, axis=1)\n return np.sum(cum_probs < rnd_quantile[..., None], axis=1)\n" ]
[ [ "numpy.sqrt", "numpy.sum", "numpy.cumsum", "numpy.empty", "numpy.zeros", "numpy.argsort", "numpy.asarray", "numpy.exp", "numpy.arange", "numpy.clip", "numpy.log", "numpy.maximum", "numpy.inner", "numpy.full", "numpy.round", "numpy.minimum" ] ]
ericlearning/Progressive-Image-Translation-Network
[ "972c54dfdbc4c065328f7fc54b2b47c2cefcc609" ]
[ "others/paired/progressive/dataset.py" ]
[ "import os\nimport torch\nimport random\nimport numpy as np\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import DataLoader\nfrom PIL import Image\n\nclass Dataset():\n\tdef __init__(self, train_dir, basic_types = None, shuffle = True):\n\t\tself.train_dir = train_dir\n\t\tself.basic_types = basic_types\n\t\tself.shuffle = shuffle\n\n\tdef get_loader(self, sz, bs, num_workers = 1):\n\t\tif(self.basic_types == 'Pix2Pix'):\n\t\t\tdt = {\n\t\t\t\t'input' : transforms.Compose([\n\t\t\t\t\ttransforms.Resize((sz, sz)),\n\t\t\t\t\ttransforms.ToTensor(),\n\t\t\t\t\ttransforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n\t\t\t\t]),\n\t\t\t\t'target' : transforms.Compose([\n\t\t\t\t\ttransforms.Resize((sz, sz)),\n\t\t\t\t\ttransforms.ToTensor(),\n\t\t\t\t\ttransforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n\t\t\t\t])\n\t\t\t}\n\t\t\tinput_transform = dt['input']\n\t\t\ttarget_transform = dt['target']\n\n\t\t\ttrain_dataset = Pix2Pix_Dataset(self.train_dir[0], self.train_dir[1], input_transform, target_transform)\n\t\t\ttrain_loader = DataLoader(train_dataset, batch_size = bs, shuffle = self.shuffle, num_workers = num_workers)\n\n\t\t\treturns = (train_loader)\n\n\t\treturn returns\n\nclass Pix2Pix_Dataset():\n\tdef __init__(self, input_dir, target_dir, input_transform, target_transform):\n\t\tself.input_dir = input_dir\n\t\tself.target_dir = target_dir\n\t\tself.input_transform = input_transform\n\t\tself.target_transform = target_transform\n\n\t\tself.image_name_list = []\n\t\tfor file in os.listdir(input_dir):\n\t\t\tif(file.endswith('.png') or file.endswith('.jpeg') or file.endswith('.jpg') or file.endswith('.bmp')):\n\t\t\t\tself.image_name_list.append(file)\n\n\tdef __len__(self):\n\t\treturn len(self.image_name_list)\n\n\tdef __getitem__(self, idx):\n\t\tif(self.target_dir == None):\n\t\t\tinput_img = Image.open(os.path.join(self.input_dir, self.image_name_list[idx]))\n\t\t\ttarget_img = input_img.copy()\n\t\telse:\n\t\t\tinput_img = Image.open(os.path.join(self.input_dir, self.image_name_list[idx]))\n\t\t\ttarget_img = Image.open(os.path.join(self.target_dir, self.image_name_list[idx]))\n\n\t\tinput_img = self.input_transform(input_img)\n\t\ttarget_img = self.target_transform(target_img)\n\n\t\tsample = (input_img, target_img)\n\t\treturn sample" ]
[ [ "torch.utils.data.DataLoader" ] ]
lim0606/pytorch-ardae-rl
[ "6e861d8f09ee27fa8f7b42d1eb209788c93395fa" ]
[ "main_ardae.py" ]
[ "\"\"\"\nPyTorch code for SAC-AR-DAE. Copied and modified from PyTorch code for SAC-NF (Mazoure et al., 2019): https://arxiv.org/abs/1905.06893\n\"\"\"\n\nimport os\nimport sys\nimport argparse\nimport time\nimport datetime\nimport itertools\nimport random\nimport pickle\nimport glob\n\nimport gym\nimport numpy as np\nimport torch\nfrom sac_ardae import SAC\nfrom normalized_actions import NormalizedActions\nfrom replay_memory import ReplayMemory\nimport pandas as pd\ntry:\n import pybulletgym\nexcept:\n print('No PyBullet Gym. Skipping...')\nfrom utils import logging, get_time, print_args\nfrom utils import save_checkpoint, load_checkpoint\n\nfrom tensorboardX import SummaryWriter\n\n\nparser = argparse.ArgumentParser(description='PyTorch code for SAC-AR-DAE (Lim et al. 2020, https://arxiv.org/abs/2006.05164)')\nparser.add_argument('--env-name', default=\"Ant-v2\",\n help='name of the environment to run')\nparser.add_argument('--eval', type=bool, default=True,\n help='Evaluates a policy a policy every 10 episode (default:True)')\nparser.add_argument('--gamma', type=float, default=0.99, metavar='G',\n help='discount factor for reward (default: 0.99)')\nparser.add_argument('--tau', type=float, default=0.005, metavar='G',\n help='target smoothing coefficient(tau) (default: 0.005)')\nparser.add_argument('--lr', type=float, default=0.0003, metavar='G',\n help='learning rate (default: 0.0003)')\nparser.add_argument('--num_enc_layers', type=int, default=1,\n help='number of fc layers in stochastic policy (default: 1)')\nparser.add_argument('--num_fc_layers', type=int, default=1,\n help='number of fc layers in stochastic policy (default: 1)')\nparser.add_argument('--policy_nonlin', default='relu',\n help='nonlinear function in stochastic policy (default: relu)')\nparser.add_argument('--policy_type', default='mlp',\n choices=['mlp', 'wnres', 'res', 'mlpdeep', 'wnresdeep', 'resdeep'],\n help='type of fc network in stochastic policy network (default: mlp)')\nparser.add_argument('--alpha', type=float, default=0.05, metavar='G',\n help='Temperature parameter alpha determines the relative importance of the entropy term against the reward (default: 0.2)')\nparser.add_argument('--automatic_entropy_tuning', type=bool, default=False, metavar='G',\n help='Temperature parameter alpha automaically adjusted.')\n#parser.add_argument('--seed', type=int, default=456, metavar='N',\n# help='random seed (default: 456)')\nparser.add_argument('--batch_size', type=int, default=256, metavar='N',\n help='batch size (default: 256)')\nparser.add_argument('--num_steps', type=int, default=3000001, metavar='N',\n help='maximum number of steps (default: 1000000)')\nparser.add_argument('--hidden_size', type=int, default=256, metavar='N',\n help='hidden size (default: 256)')\nparser.add_argument('--noise_size', type=int, default=10, metavar='N',\n help='noise size (default: 10)')\nparser.add_argument('--updates_per_step', type=int, default=1, metavar='N',\n help='model updates per simulator step (default: 1)')\nparser.add_argument('--start_steps', type=int, default=10000, metavar='N',\n help='Steps sampling random actions (default: 10000)')\nparser.add_argument('--target_update_interval', type=int, default=1, metavar='N',\n help='Value target update per no. of updates per step (default: 1)')\nparser.add_argument('--hadamard',type=int,default=1)\nparser.add_argument('--replay_size', type=int, default=1000000, metavar='N',\n help='size of replay buffer (default: 10000000)')\nparser.add_argument('--cuda', action=\"store_true\",\n help='run on CUDA (default: False)')\nparser.add_argument('--cache', default='experiments', type=str)\nparser.add_argument('--experiment', default=None, help='name of experiment')\nparser.add_argument('--nb_evals', type=int, default=10,\n help='nb of evaluations')\nparser.add_argument('--resume', dest='resume', action='store_true', default=True,\n help='flag to resume the experiments')\nparser.add_argument('--no-resume', dest='resume', action='store_false', default=True,\n help='flag to resume the experiments')\nparser.add_argument('--exp-num', type=int, default=0,\n help='experiment number')\n\n# jacobian clamping\nparser.add_argument('--lmbd', type=float, default=0,\n help='')\nparser.add_argument('--nu', type=float, default=0,\n help='')\nparser.add_argument('--eta', type=float, default=0,\n help='')\nparser.add_argument('--num-pert-samples', type=int, default=0,\n help='')\nparser.add_argument('--jac-act', default='tanh',\n choices=['none', 'tanh'],\n help='')\n\n# seed\nparser.add_argument('--seed', type=int, default=456, metavar='N',\n help='random seed (default: 456)')\n\n# log\nparser.add_argument('--log-interval', type=int, default=100,\n help='log print-out interval (step)')\nparser.add_argument('--eval-interval', type=int, default=10000,\n help='eval interval (step)')\nparser.add_argument('--ckpt-interval', type=int, default=10000,\n help='checkpoint interval (step)')\n\n# grad q network\nparser.add_argument('--gqnet_num_layers', type=int, default=1,\n help='number of layers in grad q network (default: 1)')\nparser.add_argument('--gqnet_nonlin', default='relu',\n help='nonlinear function in grad q network (default: relu)')\nparser.add_argument('--q-optimizer', default='adam',\n choices=['sgd', 'adam', 'amsgrad', 'rmsprop'],\n help='optimization methods: sgd | adam | amsgrad | rmsprop ')\nparser.add_argument('--q-beta1', type=float, default=0.5, help='beta1 for adam or adam-amsgrad. default=0.5') # adam\nparser.add_argument('--q-momentum', type=float, default=0.5, help='momentum for std or rmsprop. default=0.5') # sgd or rmsprop\n#parser.add_argument('--q-lr', type=float, default=0.0001, help='initial learning rate')\n\n# use mean subtraction\nparser.add_argument('--mean-sub-method', default='none',\n choices=['none', 'entms'],\n help='mean subtraction method')\nparser.add_argument('--mean-upd-method', default='exp',\n choices=['exp', 'avg'],\n help='mean update method')\nparser.add_argument('--mean-sub-tau', type=float, default=0.005,\n help='target smoothing coefficient(tau) (default: 0.005)')\n\n# use partition function estimation\nparser.add_argument('--use-ptfnc', default=0, type=int,\n help='use partition function estimation. if 0, do not estimate. if > 0, use as the number of samples')\nparser.add_argument('--ptflogvar', type=int, default=-2.,\n help='logvar of the proposal distribution in the partition function')\n\n# cdae\nparser.add_argument('--dae-type', default='grad',\n choices=['grad', 'wnresgrad', 'resgrad', 'argrad'],\n help='type of dae')\nparser.add_argument('--dae-norm', default='none',\n choices=['none'],\n help='normalization method in cdae encoders')\nparser.add_argument('--dae-nonlin', default='softplus',\n help='nonlinear function in dae (default: softplus)')\nparser.add_argument('--dae_num_layers', type=int, default=1,\n help='number of layers in dae (default: 1)')\nparser.add_argument('--dae-enc-ctx', default='false',\n choices=['true', 'false', 'part'],\n help='dae enc architectures: true | false | part ')\nparser.add_argument('--dae-ctx-type', default='state',\n choices=['state', 'hidden'],\n help='condition methods: state | hidden ')\nparser.add_argument('--std-scale', type=float, default=1.0,\n help='std scaling for denoising autoencoder')\nparser.add_argument('--delta', type=float, default=0.1,\n help='std sampling distribution')\nparser.add_argument('--num-cdae-updates', type=int, default=1,\n help='number of cdae updates')\nparser.add_argument('--train-nz-cdae', type=int, default=100, metavar='N',\n help='the number of z samples per data point (default: 100)')\nparser.add_argument('--train-nstd-cdae', type=int, default=10, metavar='N',\n help='the number of std samples per data point (default: 10)')\nparser.add_argument('--d-optimizer', default='adam',\n choices=['sgd', 'adam', 'amsgrad', 'rmsprop'],\n help='optimization methods: sgd | adam | amsgrad | rmsprop ')\nparser.add_argument('--d-beta1', type=float, default=0.5, help='beta1 for adam or adam-amsgrad. default=0.5') # adam\nparser.add_argument('--d-momentum', type=float, default=0.5, help='momentum for std or rmsprop. default=0.5') # sgd or rmsprop\nparser.add_argument('--d-lr', type=float, default=0.0001, help='initial learning rate')\n#parser.add_argument('--clip-preact', type=float, default=25., help='clipping preactivation in cosh(preact) function.')\n\nargs = parser.parse_args()\nargs.hadamard = bool(args.hadamard)\n#assert not (args.lmbd > 0 and args.nu > 0)\nassert args.use_ptfnc >= 0\n\n# set env\nif args.env_name == 'Humanoidrllab':\n from rllab.envs.mujoco.humanoid_env import HumanoidEnv\n from rllab.envs.normalized_env import normalize\n env = normalize(HumanoidEnv())\n max_episode_steps = float('inf')\n if args.seed >= 0:\n global seed_\n seed_ = args.seed\nelse:\n env = gym.make(args.env_name)\n max_episode_steps=env._max_episode_steps\n env=NormalizedActions(env)\n if args.seed >= 0:\n env.seed(args.seed)\nif args.seed >= 0:\n torch.manual_seed(args.seed)\n np.random.seed(args.seed)\n random.seed(args.seed)\n torch.random.manual_seed(args.seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed(args.seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n\n# set args\nargs.num_actions = env.action_space.shape[0]\nargs.max_action = env.action_space.high\nargs.min_action = env.action_space.low\n\n# set cache folder\nif args.cache is None:\n args.cache = 'experiments'\nif args.experiment is None:\n args.experiment = '-'.join(['sac-ardae'#,\n '{}'.format(\n '-{}-{}{}'.format(\n args.mean_sub_method,\n args.mean_upd_method,\n '-t{}'.format(args.mean_sub_tau) if args.mean_upd_method == 'exp' else '',\n ) if args.mean_sub_method != 'none' else ''),\n 'p{}{}'.format(\n args.use_ptfnc,\n '-lv{}'.format(args.ptflogvar) if args.ptflogvar != -2. else '',\n ),\n 'jg{}-nu{}-et{}-n{}-a{}'.format(\n args.lmbd,\n args.nu,\n args.eta,\n args.num_pert_samples,\n args.jac_act,\n ),\n 'm{}-ma{}-menh{}-mfnh{}'.format(\n args.policy_type,\n args.policy_nonlin,\n args.num_enc_layers,\n args.num_fc_layers,\n ),\n 'qa{}-qnh{}'.format(\n args.gqnet_nonlin,\n args.gqnet_num_layers),\n 'd{}-da{}-dnh{}-dc{}{}'.format(\n args.dae_type,\n args.dae_nonlin,\n args.dae_num_layers,\n args.dae_ctx_type,\n '' if args.dae_enc_ctx == 'false' else ('-dencctx' if args.dae_enc_ctx == 'true' else '-dencctx-pt'), #'-dencctx' if args.dae_enc_ctx == 'true' else '',\n ),\n 'nsz{}'.format(args.noise_size),\n 'sstep{}'.format(args.start_steps),\n 'a{}'.format(args.alpha),\n 'ssc{}'.format(args.std_scale), # std scale\n 'del{}'.format(args.delta),\n 'nd{}'.format(args.num_cdae_updates),\n 'nzc{}'.format(args.train_nz_cdae),\n 'nstd{}'.format(args.train_nstd_cdae),\n 'd{}-bt1{}'.format(args.d_optimizer, args.d_beta1) if args.d_optimizer in ['adam', 'amsgrad'] else 'd{}-mt{}'.format(args.d_optimizer, args.d_momentum),\n 'dlr{}'.format(args.d_lr),\n 'q{}-qt1{}'.format(args.q_optimizer, args.q_beta1) if args.q_optimizer in ['adam', 'amsgrad'] else 'q{}-mt{}'.format(args.q_optimizer, args.q_momentum),\n 'mlr{}'.format(args.lr),\n 'seed{}'.format(args.seed),\n 'exp{}'.format(args.exp_num),\n ])\nargs.path = os.path.join(args.cache, args.experiment)\nif args.resume:\n listing = glob.glob(args.path+'-19*') + glob.glob(args.path+'-20*')\n if len(listing) == 0:\n args.path = '{}-{}'.format(args.path, get_time())\n else:\n path_sorted = sorted(listing, key=lambda x: datetime.datetime.strptime(x, args.path+'-%y%m%d-%H:%M:%S'))\n args.path = path_sorted[-1]\n pass\nelse:\n args.path = '{}-{}'.format(args.path, get_time())\nos.system('mkdir -p {}'.format(args.path))\n\n# print args\nlogging(str(args), path=args.path)\n\n# init tensorboard\nwriter = SummaryWriter(args.path)\n\n# print config\nconfiguration_setup='SAC-AR-DAE'\nconfiguration_setup+='\\n'\nconfiguration_setup+=print_args(args)\n#for arg in vars(args):\n# configuration_setup+=' {} : {}'.format(str(arg),str(getattr(args, arg)))\n# configuration_setup+='\\n'\nlogging(configuration_setup, path=args.path)\n\n# init sac\nagent = SAC(env.observation_space.shape[0], env.action_space, args)\nlogging(\"----------------------------------------\", path=args.path)\nlogging(str(agent.critic), path=args.path)\nlogging(\"----------------------------------------\", path=args.path)\nlogging(str(agent.policy), path=args.path)\nlogging(\"----------------------------------------\", path=args.path)\nlogging(str(agent.cdae), path=args.path)\nlogging(\"----------------------------------------\", path=args.path)\n\n# memory\nmemory = ReplayMemory(args.replay_size)\n\n# resume\nargs.start_episode = 1\nargs.offset_time = 0 # elapsed\nargs.total_numsteps = 0\nargs.updates = 0\nargs.eval_steps = 0\nargs.ckpt_steps = 0\nagent.load_model(args)\nmemory.load(os.path.join(args.path, 'replay_memory'), 'pkl')\n\n# Training Loop\ntotal_numsteps = args.total_numsteps # 0\nupdates = args.updates # 0\neval_steps = args.eval_steps # 0\nckpt_steps = args.ckpt_steps # 0\nstart_episode = args.start_episode # 1\noffset_time = args.offset_time # 0\nstart_time = time.time()\nif 'dataframe' in args:\n df = args.dataframe\nelse:\n df = pd.DataFrame(columns=[\"total_steps\", \"score_eval\", \"time_so_far\"])\n\nfor i_episode in itertools.count(start_episode):\n episode_reward = 0\n episode_steps = 0\n done = False\n state = env.reset()\n\n while not done:\n if args.start_steps > total_numsteps:\n action = np.random.uniform(env.action_space.low,env.action_space.high,env.action_space.shape[0]) # Sample random action\n else:\n action = agent.select_action(state) # Sample action from policy\n if len(memory) > args.start_steps:\n # Number of updates per step in environment\n for i in range(args.updates_per_step):\n # Update parameters of all the networks\n (critic_1_loss, critic_2_loss,\n policy_loss,\n cdae_loss,\n cdae_info,\n ) = agent.update_parameters(memory, args.batch_size, updates)\n updates += 1\n\n # log\n if updates % args.log_interval == 0:\n lmbd = cdae_info['lmbd']\n _action = cdae_info['action']\n __action = _action.view(-1)#.numpy()\n _mean_action = torch.mean(__action).item()\n _med_action = torch.median(__action).item()\n logvar_qa = torch.log(torch.var(_action, dim=1) + 1e-10) # bsz x zdim\n _logvar_qa = logvar_qa.view(-1).numpy()\n _mean_logvar_qa = torch.mean(logvar_qa).item()\n _med_logvar_qa = torch.median(logvar_qa).item()\n __logvar_qa = logvar_qa.view(logvar_qa.size(0), -1).numpy()\n\n logging(\"Episode: {}\"\n \", update: {}\"\n \", critic_1 loss: {:.3f}\"\n \", critic_2 loss: {:.3f}\"\n \", cdae loss {:.3f}\"\n \", lmbd {:.2f}\"\n \", logvar_action: {:.3f}\"\n .format(\n i_episode,\n updates,\n critic_1_loss,\n critic_2_loss,\n cdae_loss,\n lmbd,\n _mean_logvar_qa,\n ), path=args.path)\n\n writer.add_scalar('train/critic_1/loss/update', critic_1_loss, updates)\n writer.add_scalar('train/critic_2/loss/update', critic_2_loss, updates)\n writer.add_scalar('train/cdae/loss/update', cdae_loss, updates)\n writer.add_scalar('train/policy/lmbd/update', lmbd, updates)\n writer.add_scalar('train/action/logvar/mean/update', _mean_logvar_qa, updates)\n else:\n cdae_loss = 0\n _mean_logvar_qa = 0\n\n next_state, reward, done, _ = env.step(action) # Step\n episode_steps += 1\n total_numsteps += 1\n eval_steps += 1\n ckpt_steps += 1\n episode_reward += reward\n\n # Ignore the \"done\" signal if it comes from hitting the time horizon.\n # (https://github.com/openai/spinningup/blob/master/spinup/algos/sac/sac.py)\n mask = 1 if episode_steps == max_episode_steps else float(not done)\n\n memory.push(state, action, reward, next_state, mask) # Append transition to memory\n\n state = next_state\n\n elapsed = round((time.time() - start_time + offset_time),2)\n logging(\"Episode: {}\"\n \", time (sec): {}\"\n \", total numsteps: {}\"\n \", episode steps: {}\"\n \", reward: {}\"\n .format(\n i_episode,\n elapsed,\n total_numsteps,\n episode_steps,\n round(episode_reward, 2),\n ), path=args.path)\n writer.add_scalar('train/ep_reward/episode', episode_reward, i_episode)\n writer.add_scalar('train/ep_reward/step', episode_reward, total_numsteps)\n\n # evaluation\n if eval_steps>=args.eval_interval or total_numsteps > args.num_steps:\n logging('evaluation time', path=args.path)\n r=[]\n for _ in range(args.nb_evals):\n state = env.reset()\n episode_reward = 0\n done = False\n while not done:\n action = agent.select_action(state, eval=True)\n\n next_state, reward, done, _ = env.step(action)\n episode_reward += reward\n\n state = next_state\n r.append(episode_reward)\n mean_reward=np.mean(r)\n\n # add to data frame\n res = {\"total_steps\": total_numsteps,\n \"score_eval\": mean_reward,\n \"time_so_far\": round((time.time() - start_time),2)}\n df = df.append(res, ignore_index=True)\n\n # add to log\n logging(\"----------------------------------------\", path=args.path)\n logging(\"Test Episode: {}, mean reward: {}, ep reward: {}\"\n .format(\n i_episode, round(mean_reward, 2), round(episode_reward, 2),\n ), path=args.path)\n logging(\"----------------------------------------\", path=args.path)\n writer.add_scalar('test/ep_reward/mean/step', mean_reward, total_numsteps)\n writer.add_scalar('test/ep_reward/episode/step', episode_reward, total_numsteps)\n\n # writer\n writer.flush()\n\n # reset count\n eval_steps%=args.eval_interval\n\n if ckpt_steps>=args.ckpt_interval and args.ckpt_interval > 0:\n training_info = {\n 'start_episode': i_episode+1,\n 'offset_time': round((time.time() - start_time + offset_time),2),\n 'total_numsteps': total_numsteps,\n 'updates': updates,\n 'eval_steps': eval_steps,\n 'ckpt_steps': ckpt_steps,\n 'dataframe': df,\n }\n agent.save_model(training_info)\n memory.save(os.path.join(args.path, 'replay_memory'), 'pkl')\n ckpt_steps%=args.ckpt_interval\n\n if total_numsteps > args.num_steps:\n break\n\nenv.close()\n" ]
[ [ "numpy.random.uniform", "torch.median", "torch.cuda.manual_seed", "torch.manual_seed", "pandas.DataFrame", "numpy.random.seed", "torch.var", "torch.cuda.is_available", "torch.mean", "torch.random.manual_seed", "numpy.mean" ] ]
rezeck/grf_transport
[ "64d68dc18b950575c19e44d91ade87b01a1e9ab0" ]
[ "script/eval_1_mean_plot.py" ]
[ "#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.stats\nimport sys\n\n\ndef mean_confidence_interval(data, confidence=0.95):\n a = 1.0 * np.array(data)\n n = len(a)\n m, se = np.mean(a), scipy.stats.sem(a)\n h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)\n return m, m-h, m+h\n\n\nprefix = \"exp_adaptability/default/\"\n# prefix = \"exp_adaptability/robot_failure/\"\n# prefix = \"exp_adaptability/goal_change/\"\nexperiments = [\"exp_000.npy\", \"exp_001.npy\", \"exp_002.npy\", \"exp_003.npy\", \"exp_004.npy\", \"exp_005.npy\", \"exp_006.npy\", \"exp_007.npy\", \"exp_008.npy\", \"exp_009.npy\"]\ndata_vel = []\ndata_time = []\ndata_dist = []\nend = 440000\nfor experiment in experiments:\n print(\"Reading file: \" + prefix+experiment)\n d = np.load(prefix+experiment)\n print(d.shape)\n data_time.append(d[:end, 0])\n data_dist.append(d[:end, 1])\n data_vel.append(d[:end, 2])\n\ndata_time = np.transpose(np.array(data_time))\ndata_dist = np.transpose(np.array(data_dist))\ndata_vel = np.transpose(np.array(data_vel))\nprint(data_time.shape)\nprint(data_dist.shape)\nprint(data_vel.shape)\n\n# data = []\n# print(\"processing...\")\n# for i in range(0, end):\n# m_dist, l_dist, u_dist = mean_confidence_interval(data_dist[i, :])\n# m_vel, l_vel, u_vel = mean_confidence_interval(data_vel[i, :])\n# data.append([data_time[i, 0], m_dist, l_dist, u_dist, m_vel, l_vel, u_vel])\n# data = np.array(data)\n# print(\"saving...\")\n# np.save(\"exp_adaptability/default.npy\", data)\n# exit()\n\n\ndata_dft = np.load(\"exp_adaptability/default.npy\")\ndata_rfai = np.load(\"exp_adaptability/robot_failure.npy\")\ndata_gch = np.load(\"exp_adaptability/goal_change.npy\")\ndatas = [data_dft, data_rfai, data_gch]\n\n# Ploting data\n# fig = plt.figure(dpi=200)\n# ax = fig.add_subplot(111)\n# color = 'tab:red'\n# ax.plot(data[:, 0], data[:, 5]*100, \"--\", color=color, linewidth=0.4)\n# ax.plot(data[:, 0], data[:, 6]*100, \"--\", color=color, linewidth=0.4)\n# ax.plot(data[:, 0], data[:, 4]*100, label='object velocity', color=color)\n# ax.set_xlabel('time (seconds)')\n# ax.set_ylabel('object velocity (cm/s)', color=color)\n# ax.tick_params(axis='y', labelcolor=color)\n# ax.set_ylim([0, 3.2])\n\n\n# ax2 = ax.twinx()\n# color = 'tab:blue'\n# ax2.set_ylabel('distance to goal (m)', color=color)\n# ax2.plot(data[:, 0], data[:, 2], \"--\", color=color, linewidth=0.2)\n# ax2.plot(data[:, 0], data[:, 3], \"--\", color=color, linewidth=0.2)\n# ax2.plot(data[:, 0], data[:, 1], label='distance to goal', color=color)\n# ax2.tick_params(axis='y', labelcolor=color)\n# ax2.set_ylim([0, 2.2])\n\n# ax.set_title(\"Convergence Analyses\")\n\n# # plt.savefig(figfile, dpi=200)\n# plt.show()\n\n\nfig, axs = plt.subplots(3, sharex=True, sharey=False,\n gridspec_kw={'hspace': 0.1})\n\nfor i in range(0, 3):\n axs[i].set_rasterized(True)\n ax = axs[i]\n color = 'tab:red'\n data = datas[i]\n ax.plot(data[:, 0], data[:, 5]*100, \"--\",\n color=color, linewidth=0.2, alpha=0.1)\n ax.plot(data[:, 0], data[:, 6]*100, \"--\",\n color=color, linewidth=0.2, alpha=0.1)\n ax.plot(data[:, 0], data[:, 4]*100, label='object velocity', color=color)\n if i == 1:\n ax.set_ylabel('Object velocity (cm/s)', color=color, fontsize=14)\n ax.tick_params(axis='y', labelcolor=color)\n ax.set_ylim([0, 3.2])\n\n ax2 = ax.twinx()\n ax2.set_rasterized(True)\n color = 'tab:blue'\n if i == 1:\n ax2.set_ylabel('Distance to goal (m)', color=color, fontsize=14)\n ax2.plot(data[:, 0], data[:, 2], \"--\",\n color=color, linewidth=0.8, alpha=1.0)\n ax2.plot(data[:, 0], data[:, 3], \"--\",\n color=color, linewidth=0.8, alpha=1.0)\n\n ax2.plot(data[:, 0], data[:, 1], label='distance to goal', color=color)\n ax2.tick_params(axis='y', labelcolor=color)\n ax2.set_ylim([0, 2.2])\n\naxs[0].set_title(\"Convergence Analyses\", fontsize=16)\naxs[2].set_xlabel('Time (seconds)', fontsize=14)\n\n\nplt.savefig(\"adaptability.pdf\", dpi=200)\nplt.show()\n" ]
[ [ "numpy.load", "matplotlib.pyplot.savefig", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show", "numpy.array", "numpy.mean" ] ]
jizhouh/deepcell-tf
[ "491ece59f5024d73429477ebdcb437a6e67d766b" ]
[ "deepcell/running.py" ]
[ "# Copyright 2016-2021 The Van Valen Lab at the California Institute of\n# Technology (Caltech), with support from the Paul Allen Family Foundation,\n# Google, & National Institutes of Health (NIH) under Grant U24CA224309-01.\n# All rights reserved.\n#\n# Licensed under a modified 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.github.com/vanvalenlab/deepcell-tf/LICENSE\n#\n# The Work provided may be used for non-commercial academic purposes only.\n# For any other use of the Work, including commercial use, please contact:\n# [email protected]\n#\n# Neither the name of Caltech nor the names of its contributors may be used\n# to endorse or promote products derived from this software without specific\n# prior written permission.\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\"\"\"Functions for running convolutional neural networks\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport numpy as np\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.models import Model\n\nfrom deepcell.utils.data_utils import trim_padding\n\n\ndef get_cropped_input_shape(images,\n num_crops=4,\n receptive_field=61,\n data_format=None):\n \"\"\"Calculate the input_shape for models to process cropped sub-images.\n\n Args:\n images (numpy.array): numpy array of original data\n num_crops (int): number of slices for the x and y axis\n to create sub-images\n receptive_field (int): the receptive field of the neural network.\n data_format (str): \"channels_first\" or \"channels_last\"\n\n Returns:\n tuple: new ``input_shape`` for model to process sub-images.\n \"\"\"\n if data_format is None:\n data_format = K.image_data_format()\n if data_format == 'channels_first':\n channel_axis = 1\n row_axis = len(images.shape) - 2\n col_axis = len(images.shape) - 1\n else:\n channel_axis = len(images.shape) - 1\n row_axis = len(images.shape) - 3\n col_axis = len(images.shape) - 2\n\n channel_dim = images.shape[channel_axis]\n\n # Split the frames into quarters, as the full image size is too large\n crop_x = images.shape[row_axis] // num_crops + (receptive_field - 1)\n crop_y = images.shape[col_axis] // num_crops + (receptive_field - 1)\n\n if images.ndim == 5:\n input_shape = (images.shape[row_axis - 1], crop_x, crop_y, channel_dim)\n else:\n input_shape = (crop_x, crop_y, channel_dim)\n\n # switch to channels_first if necessary\n if channel_axis == 1:\n input_shape = tuple([input_shape[-1]] + list(input_shape[:-1]))\n\n return input_shape\n\n\ndef get_padding_layers(model):\n \"\"\"Get all names of padding layers in a model\n\n Args:\n model (tensorflow.keras.Model): Keras model\n\n Returns:\n list: list of names of padding layers inside model\n \"\"\"\n padding_layers = []\n for layer in model.layers:\n if 'padding' in layer.name:\n padding_layers.append(layer.name)\n elif isinstance(layer, Model):\n padding_layers.extend(get_padding_layers(layer))\n return padding_layers\n\n\ndef process_whole_image(model, images, num_crops=4, receptive_field=61, padding=None):\n \"\"\"Slice images into num_crops * num_crops pieces, and use the model to\n process each small image.\n\n Args:\n model (tensorflow.keras.Model): model that will process each small image\n images (numpy.array): numpy array that is too big for model.predict\n num_crops (int): number of slices for the x and y axis\n to create sub-images\n receptive_field (int): receptive field used by model,\n required to pad images\n padding (str): type of padding for input images,\n one of {'reflect', 'zero'}.\n\n Returns:\n numpy.array: model outputs for each sub-image\n\n Raises:\n ValueError: invalid padding value\n ValueError: model input shape is different than expected_input_shape\n \"\"\"\n if K.image_data_format() == 'channels_first':\n channel_axis = 1\n row_axis = len(images.shape) - 2\n col_axis = len(images.shape) - 1\n else:\n channel_axis = len(images.shape) - 1\n row_axis = len(images.shape) - 3\n col_axis = len(images.shape) - 2\n\n if not padding:\n padding_layers = get_padding_layers(model)\n if padding_layers:\n padding = 'reflect' if 'reflect' in padding_layers[0] else 'zero'\n\n if str(padding).lower() not in {'reflect', 'zero'}:\n raise ValueError('Expected `padding_mode` to be either `zero` or '\n '`reflect`. Got ', padding)\n\n # Split the frames into quarters, as the full image size is too large\n crop_x = images.shape[row_axis] // num_crops\n crop_y = images.shape[col_axis] // num_crops\n\n # Set up receptive field window for padding\n win_x, win_y = (receptive_field - 1) // 2, (receptive_field - 1) // 2\n\n # instantiate matrix for model output\n model_output_shape = tuple(list(model.layers[-1].output_shape)[1:])\n if channel_axis == 1:\n output = np.zeros(tuple([images.shape[0], model_output_shape[0]] +\n list(images.shape[2:])))\n else:\n output = np.zeros(tuple(list(images.shape[0:-1]) +\n [model_output_shape[-1]]))\n\n expected_input_shape = get_cropped_input_shape(\n images, num_crops, receptive_field)\n\n if expected_input_shape != model.input_shape[1:]:\n raise ValueError('Expected model.input_shape to be {}. Got {}. Use '\n '`get_cropped_input_shape()` to recreate your model '\n ' with the proper input_shape'.format(\n expected_input_shape, model.input_shape[1:]))\n\n # pad the images only in the x and y axes\n pad_width = []\n for i in range(len(images.shape)):\n if i == row_axis:\n pad_width.append((win_x, win_x))\n elif i == col_axis:\n pad_width.append((win_y, win_y))\n else:\n pad_width.append((0, 0))\n\n if str(padding).lower() == 'reflect':\n padded_images = np.pad(images, pad_width, mode='reflect')\n else:\n padded_images = np.pad(images, pad_width, mode='constant', constant_values=0)\n\n for i in range(num_crops):\n for j in range(num_crops):\n e, f = i * crop_x, (i + 1) * crop_x + 2 * win_x\n g, h = j * crop_y, (j + 1) * crop_y + 2 * win_y\n\n if images.ndim == 5:\n if channel_axis == 1:\n predicted = model.predict(padded_images[:, :, :, e:f, g:h])\n else:\n predicted = model.predict(padded_images[:, :, e:f, g:h, :])\n else:\n if channel_axis == 1:\n predicted = model.predict(padded_images[:, :, e:f, g:h])\n else:\n predicted = model.predict(padded_images[:, e:f, g:h, :])\n\n # if using skip_connections, get the final model output\n if isinstance(predicted, list):\n predicted = predicted[-1]\n\n # if the model uses padding, trim the output images to proper shape\n # if model does not use padding, images should already be correct\n if padding:\n predicted = trim_padding(predicted, win_x, win_y)\n\n a, b = i * crop_x, (i + 1) * crop_x\n c, d = j * crop_y, (j + 1) * crop_y\n\n if images.ndim == 5:\n if channel_axis == 1:\n output[:, :, :, a:b, c:d] = predicted\n else:\n output[:, :, a:b, c:d, :] = predicted\n else:\n if channel_axis == 1:\n output[:, :, a:b, c:d] = predicted\n else:\n output[:, a:b, c:d, :] = predicted\n\n return output\n" ]
[ [ "numpy.pad", "tensorflow.keras.backend.image_data_format" ] ]
wumpus/poliastro
[ "6ef314f3b80528018ce489fd51d26db106daac91" ]
[ "src/poliastro/twobody/angles.py" ]
[ "\"\"\"Angles and anomalies.\n\n\"\"\"\nimport numpy as np\nfrom astropy import coordinates, units as u\n\nfrom poliastro import constants\nfrom poliastro.core.angles import (\n D_to_M as D_to_M_fast,\n D_to_nu as D_to_nu_fast,\n E_to_M as E_to_M_fast,\n E_to_nu as E_to_nu_fast,\n F_to_M as F_to_M_fast,\n F_to_nu as F_to_nu_fast,\n M_to_D as M_to_D_fast,\n M_to_E as M_to_E_fast,\n M_to_F as M_to_F_fast,\n fp_angle as fp_angle_fast,\n nu_to_D as nu_to_D_fast,\n nu_to_E as nu_to_E_fast,\n nu_to_F as nu_to_F_fast,\n)\n\n\[email protected]_input(D=u.rad)\ndef D_to_nu(D):\n \"\"\"True anomaly from parabolic eccentric anomaly.\n\n Parameters\n ----------\n D : ~astropy.units.Quantity\n Eccentric anomaly.\n\n Returns\n -------\n nu : ~astropy.units.Quantity\n True anomaly.\n\n Notes\n -----\n Taken from Farnocchia, Davide, Davide Bracali Cioci, and Andrea Milani.\n \"Robust resolution of Kepler’s equation in all eccentricity regimes.\"\n Celestial Mechanics and Dynamical Astronomy 116, no. 1 (2013): 21-34.\n \"\"\"\n return (D_to_nu_fast(D.to(u.rad).value) * u.rad).to(D.unit)\n\n\[email protected]_input(nu=u.rad)\ndef nu_to_D(nu):\n \"\"\"Parabolic eccentric anomaly from true anomaly.\n\n Parameters\n ----------\n nu : ~astropy.units.Quantity\n True anomaly.\n\n Returns\n -------\n D : ~astropy.units.Quantity\n Hyperbolic eccentric anomaly.\n\n Notes\n -----\n Taken from Farnocchia, Davide, Davide Bracali Cioci, and Andrea Milani.\n \"Robust resolution of Kepler’s equation in all eccentricity regimes.\"\n Celestial Mechanics and Dynamical Astronomy 116, no. 1 (2013): 21-34.\n \"\"\"\n return (nu_to_D_fast(nu.to(u.rad).value) * u.rad).to(nu.unit)\n\n\[email protected]_input(nu=u.rad, ecc=u.one)\ndef nu_to_E(nu, ecc):\n \"\"\"Eccentric anomaly from true anomaly.\n\n .. versionadded:: 0.4.0\n\n Parameters\n ----------\n nu : ~astropy.units.Quantity\n True anomaly.\n ecc : ~astropy.units.Quantity\n Eccentricity.\n\n Returns\n -------\n E : ~astropy.units.Quantity\n Eccentric anomaly.\n\n \"\"\"\n return (nu_to_E_fast(nu.to(u.rad).value, ecc.value) * u.rad).to(nu.unit)\n\n\[email protected]_input(nu=u.rad, ecc=u.one)\ndef nu_to_F(nu, ecc):\n \"\"\"Hyperbolic eccentric anomaly from true anomaly.\n\n Parameters\n ----------\n nu : ~astropy.units.Quantity\n True anomaly.\n ecc : ~astropy.units.Quantity\n Eccentricity (>1).\n\n Returns\n -------\n F : ~astropy.units.Quantity\n Hyperbolic eccentric anomaly.\n\n Note\n -----\n Taken from Curtis, H. (2013). *Orbital mechanics for engineering students*. 167\n\n \"\"\"\n return (nu_to_F_fast(nu.to(u.rad).value, ecc.value) * u.rad).to(nu.unit)\n\n\[email protected]_input(E=u.rad, ecc=u.one)\ndef E_to_nu(E, ecc):\n \"\"\"True anomaly from eccentric anomaly.\n\n .. versionadded:: 0.4.0\n\n Parameters\n ----------\n E : ~astropy.units.Quantity\n Eccentric anomaly.\n ecc : ~astropy.units.Quantity\n Eccentricity.\n\n Returns\n -------\n nu : ~astropy.units.Quantity\n True anomaly.\n\n \"\"\"\n return (E_to_nu_fast(E.to(u.rad).value, ecc.value) * u.rad).to(E.unit)\n\n\[email protected]_input(F=u.rad, ecc=u.one)\ndef F_to_nu(F, ecc):\n \"\"\"True anomaly from hyperbolic eccentric anomaly.\n\n Parameters\n ----------\n F : ~astropy.units.Quantity\n Hyperbolic eccentric anomaly.\n ecc : ~astropy.units.Quantity\n Eccentricity (>1).\n\n Returns\n -------\n nu : ~astropy.units.Quantity\n True anomaly.\n\n \"\"\"\n return (F_to_nu_fast(F.to(u.rad).value, ecc.value) * u.rad).to(F.unit)\n\n\[email protected]_input(M=u.rad, ecc=u.one)\ndef M_to_E(M, ecc):\n \"\"\"Eccentric anomaly from mean anomaly.\n\n .. versionadded:: 0.4.0\n\n Parameters\n ----------\n M : ~astropy.units.Quantity\n Mean anomaly.\n ecc : ~astropy.units.Quantity\n Eccentricity.\n\n Returns\n -------\n E : ~astropy.units.Quantity\n Eccentric anomaly.\n\n \"\"\"\n return (M_to_E_fast(M.to(u.rad).value, ecc.value) * u.rad).to(M.unit)\n\n\[email protected]_input(M=u.rad, ecc=u.one)\ndef M_to_F(M, ecc):\n \"\"\"Hyperbolic eccentric anomaly from mean anomaly.\n\n Parameters\n ----------\n M : ~astropy.units.Quantity\n Mean anomaly.\n ecc : ~astropy.units.Quantity\n Eccentricity (>1).\n\n Returns\n -------\n F : ~astropy.units.Quantity\n Hyperbolic eccentric anomaly.\n\n \"\"\"\n return (M_to_F_fast(M.to(u.rad).value, ecc.value) * u.rad).to(M.unit)\n\n\[email protected]_input(M=u.rad, ecc=u.one)\ndef M_to_D(M):\n \"\"\"Parabolic eccentric anomaly from mean anomaly.\n\n Parameters\n ----------\n M : ~astropy.units.Quantity\n Mean anomaly.\n\n Returns\n -------\n D : ~astropy.units.Quantity\n Parabolic eccentric anomaly.\n\n \"\"\"\n return (M_to_D_fast(M.to(u.rad).value) * u.rad).to(M.unit)\n\n\[email protected]_input(E=u.rad, ecc=u.one)\ndef E_to_M(E, ecc):\n \"\"\"Mean anomaly from eccentric anomaly.\n\n .. versionadded:: 0.4.0\n\n Parameters\n ----------\n E : ~astropy.units.Quantity\n Eccentric anomaly.\n ecc : ~astropy.units.Quantity\n Eccentricity.\n\n Returns\n -------\n M : ~astropy.units.Quantity\n Mean anomaly.\n\n \"\"\"\n return (E_to_M_fast(E.to(u.rad).value, ecc.value) * u.rad).to(E.unit)\n\n\[email protected]_input(F=u.rad, ecc=u.one)\ndef F_to_M(F, ecc):\n \"\"\"Mean anomaly from eccentric anomaly.\n\n Parameters\n ----------\n F : ~astropy.units.Quantity\n Hyperbolic eccentric anomaly.\n ecc : ~astropy.units.Quantity\n Eccentricity (>1).\n\n Returns\n -------\n M : ~astropy.units.Quantity\n Mean anomaly.\n\n \"\"\"\n return (F_to_M_fast(F.to(u.rad).value, ecc.value) * u.rad).to(F.unit)\n\n\[email protected]_input(D=u.rad, ecc=u.one)\ndef D_to_M(D):\n \"\"\"Mean anomaly from eccentric anomaly.\n\n Parameters\n ----------\n D : ~astropy.units.Quantity\n Parabolic eccentric anomaly.\n\n Returns\n -------\n M : ~astropy.units.Quantity\n Mean anomaly.\n\n \"\"\"\n return (D_to_M_fast(D.to(u.rad).value) * u.rad).to(D.unit)\n\n\[email protected]_input(nu=u.rad, ecc=u.one)\ndef fp_angle(nu, ecc):\n \"\"\"Flight path angle.\n\n .. versionadded:: 0.4.0\n\n Parameters\n ----------\n nu : ~astropy.units.Quantity\n True anomaly.\n ecc : ~astropy.units.Quantity\n Eccentricity.\n\n Note\n -----\n Algorithm taken from Vallado 2007, pp. 113.\n\n \"\"\"\n return (fp_angle_fast(nu.to(u.rad).value, ecc.value) * u.rad).to(nu.unit)\n\n\[email protected]_input(ltan=u.hourangle)\ndef raan_from_ltan(epoch, ltan=12.0):\n \"\"\"RAAN angle from LTAN for SSO around the earth\n\n Parameters\n ----------\n epoch : ~astropy.time.Time\n Value of time to calculate the RAAN for\n ltan: ~astropy.units.Quantity\n Decimal hour between 0 and 24\n\n Returns\n -------\n RAAN: ~astropy.units.Quantity\n Right ascension of the ascending node angle in GCRS\n\n Note\n ----\n Calculations of the sun mean longitude and equation of time\n follow \"Fundamentals of Astrodynamics and Applications\"\n Fourth edition by Vallado, David A.\n \"\"\"\n\n T_UT1 = ((epoch.ut1 - constants.J2000).value / 36525.0) * u.deg\n T_TDB = ((epoch.tdb - constants.J2000).value / 36525.0) * u.deg\n\n # Apparent sun position\n sun_position = coordinates.get_sun(epoch)\n\n # Calculate the sun apparent local time\n salt = sun_position.ra + 12 * u.hourangle\n\n # Use the equation of time to calculate the mean sun local time (fictional sun without anomalies)\n\n # sun mean anomaly\n M_sun = 357.5291092 * u.deg + 35999.05034 * T_TDB\n\n # sun mean longitude\n l_sun = 280.460 * u.deg + 36000.771 * T_UT1\n l_ecliptic_part2 = 1.914666471 * u.deg * np.sin(\n M_sun\n ) + 0.019994643 * u.deg * np.sin(2 * M_sun)\n l_ecliptic = l_sun + l_ecliptic_part2\n\n eq_time = (\n -l_ecliptic_part2\n + 2.466 * u.deg * np.sin(2 * l_ecliptic)\n - 0.0053 * u.deg * np.sin(4 * l_ecliptic)\n )\n\n # Calculate sun mean local time\n\n smlt = salt + eq_time\n\n # Desired angle between sun and ascending node\n alpha = (coordinates.Angle(ltan).wrap_at(24 * u.hourangle)).to(u.rad)\n\n # Use the mean sun local time calculate needed RAAN for given LTAN\n raan = smlt + alpha\n return raan\n" ]
[ [ "numpy.sin" ] ]
jfc43/robust-attribution-regularization
[ "fad85f40d4b1c2efcd851c32216b4549e7122421" ]
[ "GTSRB/eval_attribution_attack.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom datetime import datetime\nimport numpy as np\nimport shutil\nimport json\nimport math\nimport os\nimport sys\nimport time\n\nimport tensorflow as tf\nimport gtsrb_input\nfrom model import Model\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\n# Global constants\nwith open('config.json') as config_file:\n config = json.load(config_file)\n\nnum_eval_examples = config['num_eval_examples']\nepsilon = config['epsilon']\nrandom_seed = config['np_random_seed']\nmodel_dir = config['model_dir']\nnum_IG_steps = config['num_IG_steps']\nk_top = config['k_top']\neval_k_top = config['eval_k_top']\nsaliency_type = config['saliency_type']\nattribution_attack_method = config['attribution_attack_method']\nattribution_attack_measure = config['attribution_attack_measure']\nattribution_attack_step_size = config['attribution_attack_step_size']\nattribution_attack_steps = config['attribution_attack_steps']\nattribution_attack_times = config['attribution_attack_times']\ndata_path = config['data_path']\n\nif saliency_type == 'ig':\n from ig_attack import IntegratedGradientsAttack as SaliencyAttack\nelif saliency_type == 'simple_gradient':\n from simple_gradient_attack import SimpleGradientAttack as SaliencyAttack\nelse:\n assert False, ('Unknown saliency type.')\n\nnp.random.seed(random_seed)\n\n# Set upd the data, hyperparameters, and the model\ngtsrb = gtsrb_input.GTSRBData(data_path)\n\nreference_image = np.zeros((32,32,3))\n\nmodel = Model(mode='eval', create_saliency_op=saliency_type)\n\nsaver = tf.train.Saver()\n\nglobal_step = tf.contrib.framework.get_or_create_global_step()\n\ncheckpoint = tf.train.latest_checkpoint(model_dir)\n\ntf_config = tf.ConfigProto()\ntf_config.gpu_options.allow_growth = True\n\nwith tf.Session(config = tf_config) as sess:\n # Restore the checkpoint\n saver.restore(sess, checkpoint)\n\n test_images = gtsrb.eval_data.xs\n test_labels = gtsrb.eval_data.ys\n \n min_intersections = []\n min_spearmans = []\n min_kendalls = []\n \n correct_cnt = 0\n\n for i in range(num_eval_examples):\n test_image = test_images[i]\n original_label = test_labels[i]\n\n module = SaliencyAttack(sess = sess, test_image = test_image, original_label = original_label, NET = model,\n attack_method = attribution_attack_method, epsilon = epsilon,\n k_top = k_top, eval_k_top = eval_k_top, num_steps = num_IG_steps,\n attack_iters = attribution_attack_steps,\n attack_times = attribution_attack_times,\n alpha = attribution_attack_step_size, attack_measure = attribution_attack_measure,\n reference_image = reference_image, same_label = True)\n\n if module.status == 1:\n \n correct_cnt += 1\n \n intersections, spearmans, kendalls = module.iterative_attack()\n \n idx = np.argmin(kendalls)\n min_intersections.append(intersections[idx])\n min_spearmans.append(spearmans[idx])\n min_kendalls.append(kendalls[idx])\n \n res_str = '{} {} '.format(i, 1)\n\n for k in range(attribution_attack_times):\n res_str += '{:.6f} {:.6f} {:.6f} '.format(intersections[k], spearmans[k], kendalls[k])\n \n\n print('progress: {}/{}, {}'.format(i + 1, num_eval_examples, res_str))\n else:\n res_str = '{} {} '.format(i, 0)\n\n for k in range(attribution_attack_times):\n res_str += '{:.6f} {:.6f} {:.6f} '.format(0, 0, 0)\n\n print('progress: {}/{}, prediction incorrect!'.format(i + 1, num_eval_examples))\n \navg_intersection = np.mean(min_intersections)\navg_spearman = np.mean(min_spearmans)\navg_kendall = np.mean(min_kendalls)\n\nprint('process {} examples'.format(num_eval_examples))\nprint('accuracy {}'.format(float(correct_cnt)/num_eval_examples))\nprint('Average top-k intersection: {:.4f}'.format(avg_intersection))\nprint('Average spearman rank correlation: {:.4f}'.format(avg_spearman))\nprint('Average kendall rank correlation: {:.4f}'.format(avg_kendall))\n\n\n" ]
[ [ "tensorflow.contrib.framework.get_or_create_global_step", "numpy.zeros", "numpy.argmin", "numpy.random.seed", "tensorflow.train.latest_checkpoint", "tensorflow.train.Saver", "tensorflow.Session", "tensorflow.ConfigProto", "numpy.mean" ] ]
weixiong-zheng-berkeley/BART-lite
[ "ead39f757acab936af815352262080318163debb" ]
[ "mesh.py" ]
[ "import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n\nimport numpy as np\n\nclass Mesh(object):\n def __init__(self, mesh_cells, domain_upper, mat_map):\n assert type(mesh_cells) == int, \"mesh_cells must be an int\"\n self._mesh_params = {'x_cell': mesh_cells,\n 'cell_length': float(domain_upper)/float(mesh_cells)}\n\n self._mat_map = mat_map\n\n i = np.repeat(np.arange(mesh_cells), mesh_cells)\n j = np.tile(np.arange(mesh_cells), mesh_cells)\n idxs = zip(i,j)\n \n self._cells = []\n\n for idx in idxs:\n self._cells.append(Cell(idx, self._mesh_params, mat_map))\n\n # Save parameters\n self._n_cell = mesh_cells**2\n assert self._n_cell == len(self._cells),\\\n \"Cell array incorrect length\"\n\n self._x_cell = mesh_cells\n self._y_cell = mesh_cells\n self._x_node = mesh_cells + 1\n self._y_node = mesh_cells + 1\n self._n_node = self._x_node * self._y_node\n self._cell_length = self._mesh_params['cell_length']\n\n def soln_plot(self, solution, plot = True): # pragma: no cover\n # Plot a given solution\n return self.__plot__(solution, plot)\n \n def test_plot(self, plot = False):\n # Plot a test solution of length n_cells\n solution = np.zeros(self._n_node)\n \n for cell in self._cells:\n for idx in cell.global_idx():\n solution[idx] += 0.5\n \n return self.__plot__(solution, plot)\n \n def __plot__(self, solution, plot):\n xs = []\n ys = []\n zs = []\n for i,s in enumerate(solution):\n x, y = self.__idx_to_xy__(i)\n xs.append(x)\n ys.append(y)\n zs.append(s)\n if plot: # pragma: no cover\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n X = np.reshape(xs, (self._x_node, self._x_node))\n Y = np.reshape(ys, (self._x_node, self._x_node))\n Z = np.reshape(zs, (self._x_node, self._x_node))\n rstride = int(self._x_node/50) + 1\n cstride = int(self._x_node/50) + 1\n surf = ax.plot_surface(X,Y,Z, cmap=cm.coolwarm, rstride=rstride,\n cstride=cstride, linewidth=0, antialiased=False)\n fig.colorbar(surf)\n plt.show()\n return fig\n else:\n return xs, ys, zs\n\n def __idx_to_xy__(self, idx):\n y = self._cell_length*int(idx/self._x_node)\n x = self._cell_length*int(idx % self._y_node)\n return (x,y)\n \n def cell_length(self):\n return self._cell_length\n \n def cells(self):\n return self._cells\n \n def n_cell(self):\n return self._n_cell\n \n def n_node(self):\n return self._n_node\n \n def x_cell(self):\n return self._x_cell\n \n def x_node(self):\n return self._x_node\n \n def y_cell(self):\n return self._y_cell\n \n def y_node(self):\n return self._y_node\n\nclass Cell(object):\n \"\"\" A single cell in the mesh, holds location and material data \"\"\"\n\n def __init__(self, index, mesh_params, mat_map=None):\n \"\"\" Cell constructor, give index in a tuple (i,j) \"\"\"\n \n # Constructor validations\n assert isinstance(index, tuple), \"Index must be a tuple\"\n assert len(index) == 2, \"Index must be a length 2 tuple\"\n \n try:\n assert mesh_params['cell_length'] > 0, \"cell_length must be greater than 0\"\n except KeyError:\n raise KeyError(\"Missing 'cell_length' parameter in mesh_params\")\n\n self._index = index\n\n try:\n self._length = float(mesh_params['cell_length'])\n except ValueError:\n raise TypeError(\"cell_length parameter must be a number\")\n\n # Calculate global_idx\n x_node = mesh_params['x_cell'] + 1\n i,j = index[0], index[1]\n self._global_idx = [x_node*i + j,\n x_node*i + j + 1,\n x_node*(i + 1) + j,\n x_node*(i + 1) + j + 1]\n \n # Determine if on a boundary\n self._bounds = {}\n x_cell = mesh_params['x_cell']\n try:\n y_cell = mesh_params['y_cell']\n except KeyError:\n y_cell = x_cell\n \n # Verify cell is in the mesh\n assert i < x_cell, \"Cell i exceeds num of x nodes\"\n assert j < y_cell, \"Cell j exceeds num of y nodes\"\n \n if index[0] == 0:\n self._bounds.update({'x_min': None})\n if index[0] == y_cell - 1:\n self._bounds.update({'x_max': None})\n if index[1] == 0:\n self._bounds.update({'y_min': None})\n if index[1] == x_cell - 1:\n self._bounds.update({'y_max': None})\n\n # Get material properties\n if mat_map:\n assert (mat_map.dx * mat_map.n) == (x_cell * self._length),\\\n \"Material map and cells must have the same total x length\"\n assert (mat_map.dy * mat_map.n) == (y_cell * self._length),\\\n \"Material map and cells must have the same total y length\"\n \n self._mat_map = mat_map\n\n\n # UTILITY FUNCTIONS ================================================\n\n # MATERIAL PROPERTIES ==============================================\n def get(self, prop):\n try:\n x = self._length*(self._index[0] + 0.5)\n y = self._length*(self._index[1] + 0.5)\n \n return self._mat_map.get(prop, loc=(x,y))\n except AttributeError:\n raise AttributeError(\"This cell has no material map assigned\")\n\n \n # ATTRIBUTES =======================================================\n \n def bounds(self, bound=None, value=None):\n if bound and bound in self._bounds:\n if value:\n self._bounds[bound] = value\n else:\n return self._bounds[bound]\n elif bound and not bound in self._bounds:\n raise KeyError(\"Cell does not have bound \" + str(bound))\n else:\n return self._bounds \n \n def global_idx(self):\n \"\"\" Returns global index, a list of the node indices \"\"\"\n return self._global_idx\n\n def index(self):\n return self._index\n \n def length(self):\n return self._length\n" ]
[ [ "numpy.zeros", "matplotlib.pyplot.figure", "numpy.reshape", "numpy.arange", "matplotlib.pyplot.show" ] ]
PaulWang1905/tensorflow
[ "ebf12d22b4801fb8dab5034cc94562bf7cc33fa0" ]
[ "tensorflow/python/training/experimental/loss_scale.py" ]
[ "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Contains LossScale classes.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\n\nimport six\n\nfrom tensorflow.python.distribute import distribution_strategy_context\nfrom tensorflow.python.distribute import reduce_util\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.training.tracking import base as trackable\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.util.tf_export import tf_export\n\n\[email protected]_metaclass(abc.ABCMeta)\n@tf_export('train.experimental.LossScale')\nclass LossScale(trackable.Trackable):\n \"\"\"Loss scale base class.\n\n Loss scaling is a process that multiplies the loss by a multiplier called the\n loss scale, and divides each gradient by the same multiplier. The pseudocode\n for this process is:\n\n ```\n loss = ...\n loss *= loss_scale\n grads = gradients(loss, vars)\n grads /= loss_scale\n ```\n\n Mathematically, loss scaling has no effect, but can help avoid numerical\n underflow in intermediate gradients when float16 tensors are used for mixed\n precision training. By multiplying the loss, each intermediate gradient will\n have the same multiplier applied.\n\n Instances of this class represent a loss scale. Calling instances of this\n class returns the loss scale as a scalar float32 tensor, while method\n `update()` updates the loss scale depending on the values of the gradients.\n Optimizers use instances of this class to scale loss and gradients.\n \"\"\"\n\n def __init__(self):\n \"\"\"Initializes the loss scale class.\"\"\"\n self._weights = {}\n\n @abc.abstractmethod\n def __call__(self):\n \"\"\"Returns the current loss scale as a scalar `float32` tensor.\"\"\"\n pass\n\n @abc.abstractmethod\n def update(self, grads):\n \"\"\"Updates the value of the loss scale.\n\n The loss scale will be potentially updated, based on the value of `grads`.\n The tensor returned by calling this class is only updated when this function\n is evaluated.\n\n In eager mode, this directly updates the loss scale, so that calling\n `__call__` will return the newly updated loss scale. In graph mode,\n this returns an op that, when evaluated, updates the loss scale.\n\n This function also returns a `should_apply_gradients` bool. If False,\n gradients should not be applied to the variables that step, as nonfinite\n gradients were found, and the loss scale has been be updated to reduce the\n chance of finding nonfinite gradients in the next step. Some loss scale\n classes will always return True, as they cannot adjust themselves in\n response to nonfinite gradients.\n\n When a DistributionStrategy is used, this function may only be called in a\n cross-replica context.\n\n Args:\n grads: A list of unscaled gradients, each which is the gradient of the\n loss with respect to a weight. The gradients should have already been\n divided by the loss scale being before passed to this function. 'None'\n gradients are accepted, and are ignored.\n\n Returns:\n update_op: In eager mode, None. In graph mode, an op to update the loss\n scale.\n should_apply_gradients: Either a bool or a scalar boolean tensor. If\n False, the caller should skip applying `grads` to the variables this\n step.\n \"\"\"\n pass\n\n def _add_weight(self, name, initial_value, dtype=None):\n \"\"\"Adds a weight to this loss scale.\n\n Args:\n name: Variable name.\n initial_value: The variable's initial value.\n dtype: The type of the variable.\n\n Returns:\n A variable.\n\n Raises:\n RuntimeError: If a weight with `name` has already been added.\n \"\"\"\n variable = variable_scope.variable(\n initial_value=initial_value,\n name=name,\n dtype=dtype,\n trainable=False,\n use_resource=True,\n synchronization=variables.VariableSynchronization.AUTO,\n # Set aggregation to NONE, as loss scaling variables should never be\n # aggregated.\n aggregation=variables.VariableAggregation.NONE)\n if context.executing_eagerly():\n graph_key = None\n else:\n graph = ops.get_default_graph()\n graph_key = graph._graph_key # pylint: disable=protected-access\n\n key = (name, graph_key)\n if self._weights.get(key, None) is not None:\n raise RuntimeError('Duplicate variables detected. {}'.format(key))\n self._weights[key] = variable\n self._handle_deferred_dependencies(name=name, trackable=variable)\n return variable\n\n @property\n def _checkpoint_dependencies(self):\n \"\"\"From Trackable. Gather graph-specific weights to save.\"\"\"\n if context.executing_eagerly():\n graph_key = None\n else:\n graph = ops.get_default_graph()\n graph_key = graph._graph_key # pylint: disable=protected-access\n weights = []\n for (name, g), v in sorted(self._weights.items(), key=lambda i: i[0][0]):\n if g == graph_key:\n weights.append(trackable.TrackableReference(name=name, ref=v))\n return super(LossScale, self)._checkpoint_dependencies + weights\n\n def _lookup_dependency(self, name):\n \"\"\"From Trackable. Find a weight in the current graph.\"\"\"\n unconditional = super(LossScale, self)._lookup_dependency(name)\n if unconditional is not None:\n return unconditional\n if context.executing_eagerly():\n graph_key = None\n else:\n graph = ops.get_default_graph()\n graph_key = graph._graph_key # pylint: disable=protected-access\n return self._weights.get((name, graph_key), None)\n\n @abc.abstractmethod\n def get_config(self):\n \"\"\"Returns the config of this loss scale.\"\"\"\n pass\n\n @classmethod\n def from_config(cls, config):\n \"\"\"Creates the LossScale from its config.\"\"\"\n return cls(**config)\n\n\ndef get_loss_scale_weights(loss_scale):\n return loss_scale._weights.values() # pylint: disable=protected-access\n\n\n@tf_export('train.experimental.FixedLossScale')\nclass FixedLossScale(LossScale):\n \"\"\"Loss scale with a fixed value.\n\n The loss scale is not updated for the lifetime of instances of this class.\n A given instance of this class always returns the same number when called.\n \"\"\"\n\n def __init__(self, loss_scale_value):\n \"\"\"Creates the fixed loss scale.\n\n Args:\n loss_scale_value: A Python float. Its ideal value varies depending on\n models to run. Choosing a too small loss_scale might affect model\n quality; a too big loss_scale might cause inf or nan. There is no single\n right loss_scale to apply. There is no harm choosing a relatively big\n number as long as no nan or inf is encountered in training.\n\n Raises:\n ValueError: If loss_scale is less than 1.\n \"\"\"\n super(FixedLossScale, self).__init__()\n if not isinstance(loss_scale_value, six.integer_types + (float,)):\n raise ValueError('loss_scale_value must be a Python int or float.')\n if loss_scale_value < 1:\n raise ValueError('loss_scale_value must be at least 1.')\n # It's important we do not create tensors in the constructor, as such\n # tensors might be on a different device or tf.function vs when the tensor\n # is used. This would hurt performance. Therefore, we do not create a tensor\n # from loss_scale_value, but instead leave it as a Python float.\n # TODO(reedwm): Also do not create tensors in the DynamicLossScale\n # constructor.\n self._loss_scale_value = float(loss_scale_value)\n\n def __call__(self):\n return ops.convert_to_tensor(self._loss_scale_value)\n\n def update(self, grads):\n del grads\n return control_flow_ops.no_op(), True\n\n def get_config(self):\n return {'loss_scale_value': self._loss_scale_value}\n\n\ndef _is_all_finite(grads):\n \"\"\"Returns a scalar boolean tensor indicating if all gradients are finite.\"\"\"\n is_finite_per_grad = [\n math_ops.reduce_all(math_ops.is_finite(g)) for g in grads if g is not None\n ]\n return math_ops.reduce_all(is_finite_per_grad)\n\n\ndef _op_in_graph_mode(tensor):\n \"\"\"Returns the tensor's op in graph mode, or the tensor in eager mode.\n\n This is useful because sometimes an op is needed in graph mode instead of a\n tensor. In eager mode, there are no ops.\n\n Args:\n tensor: A tensor.\n\n Returns:\n The tensor's op in graph mode. The tensor in eager mode.\n \"\"\"\n if context.executing_eagerly():\n return tensor\n return tensor.op\n\n\ndef _assign_if_finite(var, value):\n \"\"\"Assigns a value to a variable if the value is finite.\"\"\"\n return control_flow_ops.cond(\n math_ops.is_finite(value), lambda: _op_in_graph_mode(var.assign(value)),\n control_flow_ops.no_op)\n\n\n@tf_export('train.experimental.DynamicLossScale')\nclass DynamicLossScale(LossScale):\n \"\"\"Loss scale that dynamically adjusts itself.\n\n Dynamic loss scaling works by adjusting the loss scale as training progresses.\n The goal is to keep the loss scale as high as possible without overflowing the\n gradients. As long as the gradients do not overflow, raising the loss scale\n never hurts.\n\n The algorithm starts by setting the loss scale to an initial value. Every N\n steps that the gradients are finite, the loss scale is increased by some\n factor. However, if a NaN or Inf gradient is found, the gradients for that\n step are not applied, and the loss scale is decreased by the factor. This\n process tends to keep the loss scale as high as possible without gradients\n overflowing.\n \"\"\"\n\n def __init__(self,\n initial_loss_scale=2 ** 15, # See docstring for why this is big.\n increment_period=2000,\n multiplier=2.):\n \"\"\"Creates the dynamic loss scale.\n\n Args:\n initial_loss_scale: A Python float. The loss scale to use at the\n beginning. It's better to start this at a very high number, because a\n loss scale that is too high gets lowered far more quickly than a loss\n scale that is to low gets raised. The default is 2 ** 15, which is\n approximately half the maximum float16 value.\n increment_period: Increases loss scale every `increment_period`\n consecutive steps that finite gradients are encountered. If a nonfinite\n gradient is encountered, the count is reset back to zero.\n multiplier: The multiplier to use when increasing or decreasing the loss\n scale.\n \"\"\"\n super(DynamicLossScale, self).__init__()\n self._initial_loss_scale = float(initial_loss_scale)\n self._increment_period = int(increment_period)\n self._multiplier = float(multiplier)\n\n self._current_loss_scale = self._add_weight(\n name='current_loss_scale',\n dtype=dtypes.float32,\n initial_value=self._initial_loss_scale)\n # The number of consecutive steps with finite gradients since the last\n # nonfinite gradient or change in loss scale.\n self._num_good_steps = self._add_weight(\n name='good_steps', dtype=dtypes.int64, initial_value=0)\n\n @property\n def initial_loss_scale(self):\n return self._initial_loss_scale\n\n @property\n def increment_period(self):\n return self._increment_period\n\n @property\n def multiplier(self):\n return self._multiplier\n\n def __call__(self):\n return self._current_loss_scale\n\n def update(self, grads):\n \"\"\"Updates loss scale based on if gradients are finite in current step.\"\"\"\n if distribution_strategy_context.has_strategy():\n distribution = distribution_strategy_context.get_cross_replica_context()\n\n def get_is_finite(grads):\n is_finite = _is_all_finite(grads)\n # We cast to float, because we cannot reduce booleans with\n # DistributionStrategy.\n return math_ops.cast(is_finite, dtypes.float32)\n\n is_finite_float = distribution.extended.call_for_each_replica(\n get_is_finite, args=(grads,))\n reduced_is_finite_float = distribution.reduce(reduce_util.ReduceOp.SUM,\n is_finite_float, axis=None)\n is_finite = math_ops.equal(reduced_is_finite_float,\n distribution.num_replicas_in_sync)\n else:\n is_finite = _is_all_finite(grads)\n\n def update_if_finite_grads():\n \"\"\"Update assuming the gradients are finite.\"\"\"\n\n def incr_loss_scale():\n new_loss_scale = self._current_loss_scale * self._multiplier\n return control_flow_ops.group(\n _assign_if_finite(self._current_loss_scale, new_loss_scale),\n self._num_good_steps.assign(0))\n\n return control_flow_ops.cond(\n self._num_good_steps + 1 >= self._increment_period,\n incr_loss_scale, lambda: _op_in_graph_mode(\n self._num_good_steps.assign_add(1)))\n\n def update_if_not_finite_grads():\n \"\"\"Update assuming the gradients are nonfinite.\"\"\"\n\n new_loss_scale = math_ops.maximum(\n self._current_loss_scale / self._multiplier, 1)\n return control_flow_ops.group(\n self._num_good_steps.assign(0),\n self._current_loss_scale.assign(new_loss_scale))\n\n update_op = control_flow_ops.cond(is_finite, update_if_finite_grads,\n update_if_not_finite_grads)\n should_apply_gradients = is_finite\n return update_op, should_apply_gradients\n\n def get_config(self):\n return {\n 'initial_loss_scale': self.initial_loss_scale,\n 'increment_period': self.increment_period,\n 'multiplier': self.multiplier,\n }\n\n\ndef get(identifier):\n \"\"\"Get a loss scale object.\"\"\"\n if isinstance(identifier, six.integer_types + (float,)):\n return FixedLossScale(identifier)\n if identifier == 'dynamic':\n return DynamicLossScale()\n if isinstance(identifier, LossScale):\n return identifier\n elif identifier is None:\n return None\n else:\n raise ValueError('Could not interpret loss scale identifier: %s' %\n identifier)\n" ]
[ [ "tensorflow.python.ops.math_ops.equal", "tensorflow.python.ops.variable_scope.variable", "tensorflow.python.training.tracking.base.TrackableReference", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.ops.math_ops.maximum", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.ops.math_ops.is_finite", "tensorflow.python.ops.math_ops.reduce_all", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.ops.control_flow_ops.no_op", "tensorflow.python.ops.control_flow_ops.cond", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.distribute.distribution_strategy_context.get_cross_replica_context", "tensorflow.python.distribute.distribution_strategy_context.has_strategy" ] ]
quickgrid/Chunkmogrify
[ "10fb9ab3eef0fb50cec0e474ab48333032ee3c3b" ]
[ "styleclip_mapper.py" ]
[ "import math\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.nn import Module\n\ndef fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5):\n rest_dim = [1] * (input.ndim - bias.ndim - 1)\n input = input.cuda()\n if input.ndim == 3:\n return (\n F.leaky_relu(\n input + bias.view(1, *rest_dim, bias.shape[0]), negative_slope=negative_slope\n )\n * scale\n )\n else:\n return (\n F.leaky_relu(\n input + bias.view(1, bias.shape[0], *rest_dim), negative_slope=negative_slope\n )\n * scale\n )\n\nclass PixelNorm(nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, input):\n return input * torch.rsqrt(torch.mean(input ** 2, dim=1, keepdim=True) + 1e-8)\n\n\nclass EqualLinear(nn.Module):\n def __init__(\n self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, activation=None\n ):\n super().__init__()\n\n self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))\n\n if bias:\n self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))\n\n else:\n self.bias = None\n\n self.activation = activation\n\n self.scale = (1 / math.sqrt(in_dim)) * lr_mul\n self.lr_mul = lr_mul\n\n def forward(self, input):\n if self.activation:\n out = F.linear(input, self.weight * self.scale)\n out = fused_leaky_relu(out, self.bias * self.lr_mul)\n\n else:\n out = F.linear(\n input, self.weight * self.scale, bias=self.bias * self.lr_mul\n )\n\n return out\n\n def __repr__(self):\n return (\n f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'\n )\n\nclass Mapper(Module):\n\n def __init__(self, opts):\n super(Mapper, self).__init__()\n\n self.opts = opts\n layers = [PixelNorm()]\n\n for i in range(4):\n layers.append(\n EqualLinear(\n 512, 512, lr_mul=0.01, activation='fused_lrelu'\n )\n )\n\n self.mapping = nn.Sequential(*layers)\n\n\n def forward(self, x):\n x = self.mapping(x)\n return x\n\n\nclass SingleMapper(Module):\n\n def __init__(self, opts):\n super(SingleMapper, self).__init__()\n\n self.opts = opts\n\n self.mapping = Mapper(opts)\n\n def forward(self, x):\n out = self.mapping(x)\n return out\n\n\nclass LevelsMapper(Module):\n\n def __init__(self, opts):\n super(LevelsMapper, self).__init__()\n\n self.opts = opts\n\n if not opts.no_coarse_mapper:\n self.course_mapping = Mapper(opts)\n if not opts.no_medium_mapper:\n self.medium_mapping = Mapper(opts)\n if not opts.no_fine_mapper:\n self.fine_mapping = Mapper(opts)\n\n def forward(self, x):\n x_coarse = x[:, :4, :]\n x_medium = x[:, 4:8, :]\n x_fine = x[:, 8:, :]\n\n if not self.opts.no_coarse_mapper:\n x_coarse = self.course_mapping(x_coarse)\n else:\n x_coarse = torch.zeros_like(x_coarse)\n if not self.opts.no_medium_mapper:\n x_medium = self.medium_mapping(x_medium)\n else:\n x_medium = torch.zeros_like(x_medium)\n if not self.opts.no_fine_mapper:\n x_fine = self.fine_mapping(x_fine)\n else:\n x_fine = torch.zeros_like(x_fine)\n\n\n out = torch.cat([x_coarse, x_medium, x_fine], dim=1)\n\n return out\n\ndef get_keys(d, name):\n if 'state_dict' in d:\n d = d['state_dict']\n d_filt = {k[len(name) + 1:]: v for k, v in d.items() if k[:len(name)] == name}\n return d_filt\n\n\nclass StyleCLIPMapper(nn.Module):\n\n def __init__(self, opts):\n super().__init__()\n self.opts = opts\n # Define architecture\n self.mapper = self.set_mapper()\n # Load weights if needed\n self.load_weights()\n\n def set_mapper(self):\n if self.opts.mapper_type == 'SingleMapper':\n mapper = SingleMapper(self.opts)\n elif self.opts.mapper_type == 'LevelsMapper':\n mapper = LevelsMapper(self.opts)\n else:\n raise Exception('{} is not a valid mapper'.format(self.opts.mapper_type))\n return mapper\n\n def load_weights(self):\n if self.opts.checkpoint_path is not None:\n print('Loading from checkpoint: {}'.format(self.opts.checkpoint_path))\n ckpt = torch.load(self.opts.checkpoint_path, map_location='cpu')\n self.mapper.load_state_dict(get_keys(ckpt, 'mapper'), strict=True)\n" ]
[ [ "torch.load", "torch.nn.functional.linear", "torch.randn", "torch.zeros_like", "torch.nn.Sequential", "torch.zeros", "torch.cat", "torch.mean" ] ]
RomaKoks/collie_recs
[ "bc8979c8dbf68deefb030336d50f07f788cf1667" ]
[ "collie/metrics.py" ]
[ "from typing import Any, Callable, Iterable, List, Optional, Tuple, Union\nimport warnings\n\nimport numpy as np\nimport pytorch_lightning\nfrom scipy.sparse import csr_matrix\nimport torch\nfrom torchmetrics import Metric\nfrom torchmetrics.functional import auroc\nfrom tqdm.auto import tqdm\n\nimport collie\nfrom collie.interactions import ExplicitInteractions, Interactions, InteractionsDataLoader\nfrom collie.model import BasePipeline\n\n\ndef _get_user_item_pairs(user_ids: Union[np.array, torch.tensor],\n n_items: int,\n device: Union[str, torch.device]) -> Tuple[torch.tensor, torch.tensor]:\n \"\"\"\n Create tensors pairing each input user ID with each item ID.\n\n Parameters\n ----------\n user_ids: np.array or torch.tensor, 1-d\n Iterable[int] of users to score\n n_items: int\n Number of items in the training data\n device: string\n Device to store tensors on\n\n Returns\n -------\n users: torch.tensor, 1-d\n Tensor with ``n_items`` copies of each user ID\n items: torch.tensor, 1-d\n Tensor with ``len(user_ids)`` copies of each item ID\n\n Example\n -------\n .. code-block:: python\n\n >>> user_ids = np.array([10, 11, 12])\n >>> n_items = 4\n >>> user, item = _get_user_item_pairs(user_ids: user_ids, n_items: 4, device: 'cpu'):\n >>> user\n np.array([10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12])\n >>> item\n np.array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3])\n\n \"\"\"\n # Added because sometimes we call this function with ``n_items`` as ``np.int64`` type which\n # breaks ``repeat_interleave``.\n if isinstance(n_items, np.int64):\n n_items = n_items.item()\n\n users = torch.tensor(\n user_ids,\n dtype=torch.int64,\n requires_grad=False,\n device=device,\n ).repeat_interleave(n_items)\n\n items = torch.arange(\n start=0,\n end=n_items,\n requires_grad=False,\n device=device,\n ).repeat(len(user_ids))\n\n return users, items\n\n\ndef get_preds(model: BasePipeline,\n user_ids: Union[np.array, torch.tensor],\n n_items: int,\n device: Union[str, torch.device]) -> torch.tensor:\n \"\"\"\n Returns a ``n_users x n_items`` tensor with the item IDs of recommended products for each user\n ID.\n\n Parameters\n ----------\n model: collie.model.BasePipeline\n Model that can take a (user_id, item_id) pair as input and return a recommendation score\n user_ids: np.array or torch.tensor\n Iterable[int] of users to score\n n_items: int\n Number of items in the training data\n device: string\n Device torch should use\n\n Returns\n -------\n predicted_scores: torch.tensor\n Tensor of shape ``n_users x n_items``\n\n \"\"\"\n user, item = _get_user_item_pairs(user_ids, n_items, device)\n\n with torch.no_grad():\n predicted_scores = model(user, item)\n\n return predicted_scores.view(-1, n_items)\n\n\ndef _get_labels(targets: csr_matrix,\n user_ids: Union[np.array, torch.tensor],\n preds: Union[np.array, torch.tensor],\n device: str) -> torch.tensor:\n \"\"\"\n Returns a binary array indicating which of the recommended products are in each user's target\n set.\n\n Parameters\n ----------\n targets: scipy.sparse.csr_matrix\n Interaction matrix containing user and item IDs\n user_ids: np.array or torch.tensor\n Users corresponding to the recommendations in the top k predictions\n preds: torch.tensor\n Top ``k`` item IDs to recommend to each user of shape (n_users x k)\n device: string\n Device torch should use\n\n Returns\n -------\n labels: torch.tensor\n Tensor with the same dimensions as input ``preds``\n\n \"\"\"\n return torch.tensor(\n (targets[user_ids[:, None], np.array(preds.detach().cpu())] > 0)\n .astype('double')\n .toarray(),\n requires_grad=False,\n device=device,\n )\n\n\ndef mapk(targets: csr_matrix,\n user_ids: Union[np.array, torch.tensor],\n preds: Union[np.array, torch.tensor],\n k: int = 10) -> float:\n \"\"\"\n Calculate the mean average precision at K (MAP@K) score for each user.\n\n Parameters\n ----------\n targets: scipy.sparse.csr_matrix\n Interaction matrix containing user and item IDs\n user_ids: np.array or torch.tensor\n Users corresponding to the recommendations in the top k predictions\n preds: torch.tensor\n Tensor of shape (n_users x n_items) with each user's scores for each item\n k: int\n Number of recommendations to consider per user\n\n Returns\n -------\n mapk_score: float\n\n \"\"\"\n device = preds.device\n n_users = preds.shape[0]\n\n try:\n predicted_items = preds.topk(k, dim=1).indices\n except RuntimeError as e:\n raise ValueError(\n f'Ensure ``k`` ({k}) is less than the number of items ({preds.shape[1]}):', str(e)\n )\n\n topk_labeled = _get_labels(targets, user_ids, predicted_items, device)\n accuracy = topk_labeled.int()\n\n weights = (\n 1.0 / torch.arange(\n start=1,\n end=k+1,\n dtype=torch.float64,\n requires_grad=False,\n device=device\n )\n ).repeat(n_users, 1)\n\n denominator = torch.min(\n torch.tensor(k, device=device, dtype=torch.int).repeat(len(user_ids)),\n torch.tensor(targets[user_ids].getnnz(axis=1), device=device)\n )\n\n res = ((accuracy * accuracy.cumsum(axis=1) * weights).sum(axis=1)) / denominator\n res[torch.isnan(res)] = 0\n\n return res.mean().item()\n\n\ndef mrr(targets: csr_matrix,\n user_ids: Union[np.array, torch.tensor],\n preds: Union[np.array, torch.tensor],\n k: Optional[Any] = None) -> float:\n \"\"\"\n Calculate the mean reciprocal rank (MRR) of the input predictions.\n\n Parameters\n ----------\n targets: scipy.sparse.csr_matrix\n Interaction matrix containing user and item IDs\n user_ids: np.array or torch.tensor\n Users corresponding to the recommendations in the top k predictions\n preds: torch.tensor\n Tensor of shape (n_users x n_items) with each user's scores for each item\n k: Any\n Ignored, included only for compatibility with ``mapk``\n\n Returns\n -------\n mrr_score: float\n\n \"\"\"\n predicted_items = preds.topk(preds.shape[1], dim=1).indices\n labeled = _get_labels(targets, user_ids, predicted_items, device=preds.device)\n\n # weighting each 0/1 by position so that topk returns index of *first* postive result\n position_weight = 1.0/(\n torch.arange(1, targets.shape[1] + 1, device=preds.device)\n .repeat(len(user_ids), 1)\n .float()\n )\n labeled_weighted = (labeled.float() * position_weight)\n\n highest_score, rank = labeled_weighted.topk(k=1)\n\n reciprocal_rank = 1.0/(rank.float() + 1)\n reciprocal_rank[highest_score == 0] = 0\n\n return reciprocal_rank.mean().item()\n\n\ndef auc(targets: csr_matrix,\n user_ids: Union[np.array, torch.tensor],\n preds: Union[np.array, torch.tensor],\n k: Optional[Any] = None) -> float:\n \"\"\"\n Calculate the area under the ROC curve (AUC) for each user and average the results.\n\n Parameters\n ----------\n targets: scipy.sparse.csr_matrix\n Interaction matrix containing user and item IDs\n user_ids: np.array or torch.tensor\n Users corresponding to the recommendations in the top k predictions\n preds: torch.tensor\n Tensor of shape (n_users x n_items) with each user's scores for each item\n k: Any\n Ignored, included only for compatibility with ``mapk``\n\n Returns\n -------\n auc_score: float\n\n \"\"\"\n agg = 0\n for i, user_id in enumerate(user_ids):\n target_tensor = torch.tensor(\n targets[user_id].toarray(),\n device=preds.device,\n dtype=torch.long\n ).view(-1)\n # many models' ``preds`` may be unbounded if a final activation layer is not applied\n # we have to normalize ``preds`` here to avoid a ``ValueError`` stating that ``preds``\n # should be probabilities, but values were detected outside of [0,1] range\n auc = auroc(torch.sigmoid(preds[i, :]), target=target_tensor, pos_label=1)\n agg += auc\n\n return (agg/len(user_ids)).item()\n\n\ndef evaluate_in_batches(\n metric_list: Iterable[Callable[\n [csr_matrix, Union[np.array, torch.tensor], Union[np.array, torch.tensor], Optional[int]],\n float\n ]],\n test_interactions: collie.interactions.Interactions,\n model: collie.model.BasePipeline,\n k: int = 10,\n batch_size: int = 20,\n logger: pytorch_lightning.loggers.base.LightningLoggerBase = None,\n verbose: bool = True,\n) -> List[float]:\n \"\"\"\n Evaluate a model with potentially several different metrics.\n\n Memory constraints require that most test sets will need to be evaluated in batches. This\n function handles the looping and batching boilerplate needed to properly evaluate the model\n without running out of memory.\n\n Parameters\n ----------\n metric_list: list of functions\n List of evaluation functions to apply. Each function must accept keyword arguments:\n\n * ``targets``\n\n * ``user_ids``\n\n * ``preds``\n\n * ``k``\n\n test_interactions: collie.interactions.Interactions\n Interactions to use as labels\n model: collie.model.BasePipeline\n Model that can take a (user_id, item_id) pair as input and return a recommendation score\n k: int\n Number of recommendations to consider per user. This is ignored by some metrics\n batch_size: int\n Number of users to score in a single batch. For best efficiency, this number should be as\n high as possible without running out of memory\n logger: pytorch_lightning.loggers.base.LightningLoggerBase\n If provided, will log outputted metrics dictionary using the ``log_metrics`` method with\n keys being the string representation of ``metric_list`` and values being\n ``evaluation_results``. Additionally, if ``model.hparams.num_epochs_completed`` exists, this\n will be logged as well, making it possible to track metrics progress over the course of\n model training\n verbose: bool\n Display progress bar and print statements during function execution\n\n Returns\n -------\n evaluation_results: list\n List of floats, with each metric value corresponding to the respective function passed in\n ``metric_list``\n\n Examples\n --------\n .. code-block:: python\n\n from collie.metrics import auc, evaluate_in_batches, mapk, mrr\n\n\n map_10_score, mrr_score, auc_score = evaluate_in_batches(\n metric_list=[mapk, mrr, auc],\n test_interactions=test,\n model=model,\n )\n\n print(map_10_score, mrr_score, auc_score)\n\n \"\"\"\n if not isinstance(test_interactions, Interactions):\n raise ValueError(\n '``test_interactions`` must be of type ``Interactions``, not '\n f'{type(test_interactions)}. Try using ``explicit_evaluate_in_batches`` instead.'\n )\n\n device = _get_evaluate_in_batches_device(model=model)\n model.to(device)\n model._move_any_external_data_to_device()\n\n test_users = np.unique(test_interactions.mat.row)\n targets = test_interactions.mat.tocsr()\n\n if len(test_users) < batch_size:\n batch_size = len(test_users)\n\n accumulators = [0] * len(metric_list)\n\n data_to_iterate_over = range(int(np.ceil(len(test_users) / batch_size)))\n if verbose:\n data_to_iterate_over = tqdm(data_to_iterate_over)\n\n for i in data_to_iterate_over:\n user_range = test_users[i * batch_size:(i + 1) * batch_size]\n preds = get_preds(model, user_range, test_interactions.num_items, device)\n for metric_ind, metric in enumerate(metric_list):\n score = metric(targets=targets, user_ids=user_range, preds=preds, k=k)\n accumulators[metric_ind] += (score * len(user_range))\n\n all_scores = [acc_score / len(test_users) for acc_score in accumulators]\n\n if logger is not None:\n _log_metrics(model=model,\n logger=logger,\n metric_list=metric_list,\n all_scores=all_scores,\n verbose=verbose)\n\n return all_scores[0] if len(all_scores) == 1 else all_scores\n\n\ndef explicit_evaluate_in_batches(\n metric_list: Iterable[Metric],\n test_interactions: collie.interactions.ExplicitInteractions,\n model: collie.model.BasePipeline,\n logger: pytorch_lightning.loggers.base.LightningLoggerBase = None,\n verbose: bool = True,\n **kwargs,\n) -> List[float]:\n \"\"\"\n Evaluate a model with potentially several different metrics.\n\n Memory constraints require that most test sets will need to be evaluated in batches. This\n function handles the looping and batching boilerplate needed to properly evaluate the model\n without running out of memory.\n\n Parameters\n ----------\n metric_list: list of ``torchmetrics.Metric``\n List of evaluation functions to apply. Each function must accept arguments for predictions\n and targets, in order\n test_interactions: collie.interactions.ExplicitInteractions\n model: collie.model.BasePipeline\n Model that can take a (user_id, item_id) pair as input and return a recommendation score\n batch_size: int\n Number of users to score in a single batch. For best efficiency, this number should be as\n high as possible without running out of memory\n logger: pytorch_lightning.loggers.base.LightningLoggerBase\n If provided, will log outputted metrics dictionary using the ``log_metrics`` method with\n keys being the string representation of ``metric_list`` and values being\n ``evaluation_results``. Additionally, if ``model.hparams.num_epochs_completed`` exists, this\n will be logged as well, making it possible to track metrics progress over the course of\n model training\n verbose: bool\n Display progress bar and print statements during function execution\n **kwargs: keyword arguments\n Additional arguments sent to the ``InteractionsDataLoader``\n\n Returns\n ----------\n evaluation_results: list\n List of floats, with each metric value corresponding to the respective function passed in\n ``metric_list``\n\n Examples\n -------------\n .. code-block:: python\n\n import torchmetrics\n\n from collie.metrics import explicit_evaluate_in_batches\n\n\n mse_score, mae_score = evaluate_in_batches(\n metric_list=[torchmetrics.MeanSquaredError(), torchmetrics.MeanAbsoluteError()],\n test_interactions=test,\n model=model,\n )\n\n print(mse_score, mae_score)\n\n \"\"\"\n if not isinstance(test_interactions, ExplicitInteractions):\n raise ValueError(\n '``test_interactions`` must be of type ``ExplicitInteractions``, not '\n f'{type(test_interactions)}. Try using ``evaluate_in_batches`` instead.'\n )\n\n try:\n device = _get_evaluate_in_batches_device(model=model)\n model.to(device)\n model._move_any_external_data_to_device()\n\n test_loader = InteractionsDataLoader(interactions=test_interactions,\n **kwargs)\n\n data_to_iterate_over = test_loader\n if verbose:\n data_to_iterate_over = tqdm(test_loader)\n\n for batch in data_to_iterate_over:\n users, items, ratings = batch\n\n # move data to batch before sending to model\n users = users.to(device)\n items = items.to(device)\n ratings = ratings.cpu()\n\n preds = model(users, items)\n\n for metric in metric_list:\n metric(preds.cpu(), ratings)\n\n all_scores = [metric.compute() for metric in metric_list]\n\n if logger is not None:\n _log_metrics(model=model,\n logger=logger,\n metric_list=metric_list,\n all_scores=all_scores,\n verbose=verbose)\n\n return all_scores[0] if len(all_scores) == 1 else all_scores\n finally:\n for metric in metric_list:\n metric.reset()\n\n\ndef _get_evaluate_in_batches_device(model: BasePipeline):\n device = getattr(model, 'device', None)\n\n if torch.cuda.is_available() and str(device) == 'cpu':\n warnings.warn('CUDA available but model device is set to CPU - is this desired?')\n\n if device is None:\n if torch.cuda.is_available():\n warnings.warn(\n '``model.device`` attribute is ``None``. Since GPU is available, putting model on '\n 'GPU.'\n )\n device = 'cuda:0'\n else:\n device = 'cpu'\n\n return device\n\n\ndef _log_metrics(model: BasePipeline,\n logger: pytorch_lightning.loggers.base.LightningLoggerBase,\n metric_list: List[Union[Callable[..., Any], Metric]],\n all_scores: List[float],\n verbose: bool):\n try:\n step = model.hparams.get('num_epochs_completed')\n except torch.nn.modules.module.ModuleAttributeError:\n # if, somehow, there is no ``model.hparams`` attribute, this shouldn't fail\n step = None\n\n try:\n metrics_dict = dict(zip([x.__name__ for x in metric_list], all_scores))\n except AttributeError:\n metrics_dict = dict(zip([type(x).__name__ for x in metric_list], all_scores))\n\n if verbose:\n print(f'Logging metrics {metrics_dict} to ``logger``...')\n\n logger.log_metrics(metrics=metrics_dict, step=step)\n" ]
[ [ "torch.no_grad", "torch.tensor", "torch.arange", "torch.cuda.is_available", "torch.isnan", "torch.sigmoid", "numpy.unique" ] ]
RausellLab/tiresias
[ "2acca303a0f6b4b1be784f597a59c1a883dbe43d" ]
[ "src/pipeline/validation/loocv/bagging_logistic_regression.py" ]
[ "import ray\nimport mlflow\nimport torch\nfrom src.models import Bagging\nfrom src.models import LogisticRegression\nfrom src.evaluation import loocv\nfrom src.utils import data_loaders\nfrom src.utils import data_savers\nfrom src.utils import mlflow as u_mlflow\n\n\nRUN_NAME = \"Bagging Logistic Regression\"\nMODEL_NAME = \"bagging-logistic-regression\"\n\n\n#@ray.remote(num_gpus=1)\ndef bagging_logistic_regression(\n embeddings_file, node_labels_file, node_features_file, use_cuda, params, metadata\n):\n mlflow.set_experiment(\"LOOCV\")\n\n with mlflow.start_run(run_name=RUN_NAME):\n mlflow.log_param(\"model\", MODEL_NAME)\n\n u_mlflow.add_params(**params)\n u_mlflow.add_metadata(metadata)\n mlflow.set_tag(\"use_cuda\", use_cuda)\n\n labels = data_loaders.load_labels(node_labels_file, use_cuda=use_cuda)\n n_nodes = labels.size(0)\n\n embeddings = None\n node_features = None\n\n if embeddings_file is not None:\n mlflow.log_param(\"embeddings\", True)\n mlflow.log_artifact(embeddings_file, \"inputs\")\n embeddings = data_loaders.load_embeddings(\n embeddings_file, use_cuda=use_cuda\n )\n else:\n mlflow.log_param(\"embeddings\", False)\n\n if node_features_file is not None:\n mlflow.log_param(\"node_features\", True)\n mlflow.log_artifact(node_features_file, \"inputs\")\n node_features = data_loaders.load_node_features(\n node_features_file, use_cuda\n )\n else:\n mlflow.log_param(\"node_features\", False)\n\n if embeddings is not None and node_features is not None:\n in_features = torch.cat((embeddings, node_features), dim=1)\n elif embeddings is not None:\n in_features = embeddings\n elif node_features is not None:\n in_features = node_features\n\n print(RUN_NAME)\n ranks_df = loocv.run(\n labels=labels,\n model_class=Bagging,\n bagging_model=LogisticRegression,\n features=in_features,\n **params\n )\n\n data_savers.save_ranks(ranks_df, n_nodes, RUN_NAME, params)\n" ]
[ [ "torch.cat" ] ]
iwasakishuto/Keras-Imitation
[ "8ac0cd7c8912d49d13b19a0182ad534c0781fbfe" ]
[ "kerasy/initializers.py" ]
[ "# coding: utf-8\nimport re\nimport numpy as np\nfrom scipy import stats\nfrom abc import ABCMeta, abstractmethod\n\nfrom .utils import mk_class_get\nfrom .utils import handleKeyError\nfrom .utils import handleRandomState\n\nclass KerasyAbstInitializer(metaclass=ABCMeta):\n def __init__(self):\n self.name = re.sub(r\"([a-z])([A-Z])\", r\"\\1_\\2\", self.__class__.__name__).lower()\n\n @abstractmethod\n def __call__(self, shape, dtype=None):\n raise NotImplementedError\n\nclass Zeros(KerasyAbstInitializer):\n def __call__(self, shape, dtype=None):\n return np.zeros(shape=shape, dtype=dtype)\n\nclass Ones(KerasyAbstInitializer):\n def __call__(self, shape, dtype=None):\n return np.ones(shape=shape, dtype=dtype)\n\nclass Constant(KerasyAbstInitializer):\n def __call__(self, shape, value=0, dtype=None):\n return np.full(shape=shape, fill_value=value, dtype=dtype)\n\nclass RandomNormal(KerasyAbstInitializer):\n def __call__(self, shape, mean=0, stddev=0.05, dtype=None, seed=None):\n rnd = handleRandomState(seed)\n return rnd.normal(size=shape, loc=mean, scale=stddev).astype(dtype)\n\nclass RandomUniform(KerasyAbstInitializer):\n def __call__(self, shape, minval=-0.05, maxval=0.05, dtype=None, seed=None):\n rnd = handleRandomState(seed)\n return rnd.uniform(size=shape, low=minval, high=maxval)\n\nclass TruncatedNormal(KerasyAbstInitializer):\n def __call__(self, shape, mean=0.0, stddev=0.05, dtype=None, seed=None):\n X = stats.truncnorm(\n (-stddev - mean) / stddev,\n (stddev - mean) / stddev,\n loc=mean,\n scale=stddev,\n )\n return X.rvs(size=shape,random_state=seed).astype(dtype)\n\nclass VarianceScaling(KerasyAbstInitializer):\n def __call__(self, shape, scale=1.0, mode='fan_in', distribution='normal', dtype=None, seed=None):\n fan_in, fan_out = _compute_fans(shape)\n n = fan_in if mode==\"fan_in\" else fan_out if mode==\"fan_out\" else (fan_in+fan_out)/2\n scale /= max(1., n)\n if distribution=='normal':\n # 0.879... = scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.)\n stddev = np.sqrt(scale) / .87962566103423978\n return TruncatedNormal()(shape=shape, mean=0.0, stddev=stddev, dtype=dtype, seed=seed)\n else:\n limit = np.sqrt(3 * scale)\n return RandomUniform()(shape=shape, minval=-limit, maxval=limit, dtype=dtype, seed=seed)\n\nclass Orthogonal(KerasyAbstInitializer):\n def __call__(self, shape, gain=1.0, dtype=None, seed=None):\n rnd = handleRandomState(seed)\n num_rows = 1\n for dim in shape[:-1]:\n num_rows *= dim\n num_cols = shape[-1]\n flat_shape = (num_rows, num_cols)\n a = rnd.normal(loc=0.0, scale=1.0, size=flat_shape).astype(dtype)\n u, _, v = np.linalg.svd(a, full_matrices=False)\n # Pick the one with the correct shape.\n q = u if u.shape == flat_shape else v\n q = q.reshape(shape)\n return gain * q[:shape[0], :shape[1]]\n\nclass Identity(KerasyAbstInitializer):\n def __call__(self, shape, dtype=None, gain=1.0):\n if len(shape) != 2 or shape[0]!=shape[1]:\n raise ValueError('Identity matrix initializer can only be used for 2D Square matrices.')\n return gain * np.eye(N=shape[0], dtype=dtype)\n\nclass GlorotNormal(KerasyAbstInitializer):\n def __call__(self, shape, dtype=None, seed=None):\n return VarianceScaling()(\n shape=shape,\n scale=1.,\n mode='fan_avg',\n distribution='normal',\n dtype=dtype,\n seed=seed\n )\n\nclass GlorotUniform(KerasyAbstInitializer):\n def __call__(self, shape, dtype=None, seed=None):\n return VarianceScaling()(\n shape=shape,\n scale=1.,\n mode='fan_avg',\n distribution='uniform',\n dtype=dtype,\n seed=seed\n )\n\nclass HeNormal(KerasyAbstInitializer):\n def __call__(self, shape, dtype=None, seed=None):\n return VarianceScaling()(\n shape=shape,\n scale=2.,\n mode='fan_in',\n distribution='normal',\n dtype=dtype,\n seed=seed\n )\n\nclass LeCunNormal(KerasyAbstInitializer):\n def __call__(self, shape, dtype=None, seed=None):\n return VarianceScaling()(\n shape=shape,\n scale=1.,\n mode='fan_in',\n distribution='normal',\n dtype=dtype,\n seed=seed\n )\n\nclass HeUniform(KerasyAbstInitializer):\n def __call__(self, shape, dtype=None, seed=None):\n return VarianceScaling()(\n shape=shape,\n scale=2.,\n mode='fan_in',\n distribution='uniform',\n dtype=dtype,\n seed=seed\n )\n\nclass LeCunUniform(KerasyAbstInitializer):\n def __call__(self, shape, dtype=None, seed=None):\n return VarianceScaling()(\n shape=shape,\n scale=1.,\n mode='fan_in',\n distribution='uniform',\n dtype=dtype,\n seed=seed\n )\n\ndef _compute_fans(shape, data_format='channels_last'):\n \"\"\"Computes the number of input and output units for a weight shape.\n @param shape : Integer shape tuple.\n @param data_format: Image data format to use for convolution kernels.\n @return fan_in : size of the input shape.\n @return fan_out : size of the output shape.\n \"\"\"\n if len(shape) == 2:\n fan_in,fan_out = shape\n elif len(shape) in {3, 4, 5}:\n # Assuming convolution kernels (1D, 2D or 3D).\n # TH kernel shape: (depth, input_depth, ...)\n # TF kernel shape: (..., input_depth, depth)\n if data_format == 'channels_first':\n receptive_field_size = np.prod(shape[2:])\n fan_in = shape[1] * receptive_field_size\n fan_out = shape[0] * receptive_field_size\n elif data_format == 'channels_last':\n receptive_field_size = np.prod(shape[:-2])\n fan_in = shape[-2] * receptive_field_size\n fan_out = shape[-1] * receptive_field_size\n else:\n raise ValueError('Invalid data_format: ' + data_format)\n else:\n # No specific assumptions.\n fan_in = np.sqrt(np.prod(shape))\n fan_out = np.sqrt(np.prod(shape))\n return fan_in, fan_out\n\nall = KerasyInitializerFunctions = {\n 'zeros' : Zeros,\n 'ones' : Ones,\n 'constant' : Constant,\n 'random_normal' : RandomNormal,\n 'random_uniform' : RandomUniform,\n 'truncated_normal' : TruncatedNormal,\n 'variance_scaling' : VarianceScaling,\n 'orthogonal' : Orthogonal,\n 'identity' : Identity,\n 'glorot_normal' : GlorotNormal,\n 'glorot_uniform' : GlorotUniform,\n 'he_normal' : HeNormal,\n 'lecun_normal' : LeCunNormal,\n 'he_uniform' : HeUniform,\n 'lecun_uniform' : LeCunUniform,\n}\n\nget = mk_class_get(\n all_classes=KerasyInitializerFunctions,\n kerasy_abst_class=[KerasyAbstInitializer],\n genre=\"initializer\"\n)\n" ]
[ [ "numpy.ones", "numpy.eye", "numpy.zeros", "numpy.linalg.svd", "scipy.stats.truncnorm", "numpy.prod", "numpy.sqrt", "numpy.full" ] ]
kartik-hegde/mindmappings
[ "e96f2a287da2a93c4af0794a3bab1211bc95ba0a" ]
[ "mindmappings/costModel/timeloop/model_cnn.py" ]
[ "import random\nimport itertools\nimport subprocess as sp\nimport os\nimport shutil\nfrom subprocess import STDOUT\nimport os, sys\nimport numpy as np\n\nfrom mindmappings.parameters import Parameters\nfrom mindmappings.costModel.timeloop.timeloop import Timeloop\nfrom mindmappings.utils.utils import factors, replicate\nexamples = Parameters(algorithm='CNN-layer')\n\nclass Model_CNN(Timeloop):\n \"\"\"\n This is an object implemeted to support Timeloop on a specific architecture for CNN Layer\n \"\"\"\n\n def __init__(self, problem=[16,256,256,3,3,14,14], parameters=examples, arch=examples.ARCHITECTURE):\n \n # Create the problem specifications.\n self.arch, self.problem = self.defineProblem(arch, problem)\n self.parameters = parameters\n # Generate the search space.\n self.references = self.refGen()\n\n def refGen(self):\n \"\"\"\n Generates a search space. Might include invalid points.\n \"\"\"\n\n numHierarchy = self.arch['numHierarchy']\n numBanks = self.arch['numBanks']\n tiled_dimensions = self.problem['dimension_names']\n bounds = self.problem['dimension_sizes'] # this should be in the same order as the above\n\n # Tile generation\n ref_tiles = [self.getTileGen(bounds[d], numHierarchy+1) for d in range(len(bounds))]\n # Corner case, we want minimum two items (don't ask why, ask SKOPT guys)\n ref_tiles = [replicate(r) for r in ref_tiles]\n\n # Loop order generation\n ref_loop_orders = [''.join(p) for p in list(itertools.permutations(tiled_dimensions))]\n\n # Partition generation (Hardcoded as of now for 3 partitions) - write a recursive function if you need generalization\n ref_partition = [list(([i,j,b-(i+j)] for i in range(1, b, 1)\n for j in range(1, b-i, 1))) for b in numBanks]\n return ref_tiles, ref_loop_orders, ref_partition\n\n def checkTileValidity(self, tile_choices, mapping_partitions):\n \"\"\"\n Make sure the tiles fits in the buffers. This is an optimization to prune out the space.\n Timeloop does not require this.\n \"\"\"\n # print(tile_choices, mapping_partitions)\n L2_partitions, L1_partitions = mapping_partitions\n\n # Buffer sizes\n L2_input, L2_weight, L2_psum = [self.arch['bank_sizes'][0]*L2_partitions[i] for i in range(3)]\n L1_input, L1_weight, L1_psum = [self.arch['bank_sizes'][1]*L1_partitions[i] for i in range(3)]\n\n # Tile sizes\n N,C,K,R,S,P,Q = [np.prod(list(zip(*tile_choices))[i][1:]) for i in range(7)]\n L2_input_tile, L2_weight_tile, L2_psum_tile = N*(P+R-1)*(Q+S-1)*C, K*R*S*C, P*Q*K*N\n N,C,K,R,S,P,Q = [np.prod(list(zip(*tile_choices))[i][2:]) for i in range(7)]\n L1_input_tile, L1_weight_tile, L1_psum_tile = N*(P+R-1)*(Q+S-1)*C, K*R*S*C, P*Q*K*N\n\n if( (L2_input_tile>L2_input) or (L2_weight_tile>L2_weight) or (L2_psum_tile>L2_psum) or\n (L1_input_tile>L1_input) or (L1_weight_tile>L1_weight) or (L1_psum_tile>L1_psum)):\n return False\n else:\n return True\n\n def generateOracleCost(self, metric='RAW'):\n \"\"\"\n The oracle cost towards which we will guide the results towards. \n \"\"\"\n # Sophisticated Oracle (theoretical lower bound)\n\n # Get tensor sizes\n N,C,K,R,S,P,Q = self.problem['dimension_sizes']\n input_size, weight_size, output_size = [N*P*Q*C, R*S*C*K, N*P*Q*K] # Input, weight, output\n\n # Memory energy costs\n DRAM_cost = 200.0\n L2_buf, L1_buf = self.arch['buffer_access_energy']\n\n # Compute costs\n MAC_cost = self.arch['mac_energy']\n num_flops = N*R*S*C*P*Q*K\n num_PE = self.arch['numPEs']\n\n # Oracle costs per tensor per mem hierarchy\n L1_input_energy = input_size * L1_buf\n L1_weight_energy = weight_size * L1_buf\n L1_output_energy = output_size * L1_buf\n L2_input_energy = input_size * L2_buf\n L2_weight_energy = weight_size * L2_buf\n L2_output_energy = output_size * L2_buf\n DRAM_input_energy = input_size * DRAM_cost\n DRAM_weight_energy = weight_size * DRAM_cost\n DRAM_output_energy = output_size * DRAM_cost\n compute_energy = num_flops * MAC_cost\n PE_util = 1.0\n energy = sum([L1_input_energy,L1_weight_energy,L1_output_energy,\n L2_input_energy,L2_weight_energy,L2_output_energy,\n DRAM_input_energy, DRAM_weight_energy, DRAM_output_energy,\n compute_energy]) * 1e-6\n cycles = num_flops/num_PE\n\n cost_arr = np.array([L1_input_energy,L1_weight_energy,L1_output_energy,\n L2_output_energy,L2_weight_energy,L2_input_energy,\n DRAM_weight_energy, DRAM_input_energy, DRAM_output_energy,\n PE_util,energy,cycles])\n\n if(metric == 'RAW'):\n return cost_arr\n elif(metric == 'ENERGY'):\n return cost_arr[-2]*1e-6\n elif(metric == 'CYCLES'):\n return cost_arr[-1]*1e-9\n else:\n return cost_arr[-2]*cost_arr[-1]*1e-15\n\n def defineProblem(self, arch, bounds = [16,256,512,3,3,56,56]):\n \"\"\"\n Define a problem.\n \"\"\"\n\n # Arch Spec (only needed to change based on mapping)\n arch['bank_sizes'] = [arch['bufferSizes'][i]/(arch['numBanks'][i] * arch['bufferWidth'][i]) for i in range(arch['numHierarchy']-1)]\n\n # Define the domain\n dimensions = ['N','C','K','R','S','Q','P']\n problem = {'dimension_sizes': bounds, 'dimension_names':dimensions}\n\n return arch, problem\n\n def writeConfig(self, mapping, paths, unique_ID):\n \"\"\"\n This is a highly specialized version to write out a config file, get the cost and return the validity of the mapping.\n \"\"\"\n OUTPUT_DIR, (CFG_FILE_OUT_ARCH, CFG_FILE_OUT_MAP, CFG_FILE_OUT_PROB, CFG_FILE_OUT_MODEL) = paths\n\n tiling, loop_orders, partitions = mapping\n numHierarchy = self.arch['numHierarchy']\n N,C,K,R,S,P,Q = self.problem['dimension_sizes']\n\n\n # Extract\n dim_factors = [' factors: N={0} C={1} K={2} R={3} S={4} P={5} Q={6}\\n'.format(*tiling[i]) for i in range(numHierarchy+1)]\n\n # Buffer sizes\n DRAM_factors, L2_factors, spatial_factors, L1_factors = dim_factors\n DRAM_orders, L2_orders, L1_orders = loop_orders\n L2_partitions, L1_partitions = partitions\n\n L2_input, L2_weight, L2_psum = [int(self.arch['bank_sizes'][0]*L2_partitions[i]) for i in range(3)]\n L1_input, L1_weight, L1_psum = [int(self.arch['bank_sizes'][1]*L1_partitions[i]) for i in range(3)]\n\n # Open the sample file\n with open(self.parameters.SAMPLE_CFG_FILE, 'r') as f:\n data = f.readlines()\n\n # Do the replacements\n data[20] = ' depth: {0}\\n'.format(L2_input)\n data[30] = ' depth: {0}\\n'.format(L2_weight)\n data[40] = ' depth: {0}\\n'.format(L2_psum)\n data[53] = ' depth: {0}\\n'.format(L1_input)\n data[64] = ' depth: {0}\\n'.format(L1_weight)\n data[75] = ' depth: {0}\\n'.format(L1_psum)\n data[91] = DRAM_factors\n data[92] = ' permutation: {0}\\n'.format(DRAM_orders)\n data[104] = L2_factors\n data[93] = ' - permutation: {0}\\n'.format(L2_orders)\n data[97] = ' - permutation: {0}\\n'.format(L2_orders)\n data[101] = ' - permutation: {0}\\n'.format(L2_orders)\n data[108] = spatial_factors\n data[109] = ' - permutation: {0}\\n'.format(L1_orders)\n data[113] = ' - permutation: {0}\\n'.format(L1_orders)\n data[117] = ' - permutation: {0}\\n'.format(L1_orders)\n data[120] = L1_factors\n data[201] = ' C: {0}\\n'.format(C)\n data[202] = ' K: {0}\\n'.format(K)\n data[203] = ' R: {0}\\n'.format(R)\n data[204] = ' S: {0}\\n'.format(S)\n data[205] = ' P: {0}\\n'.format(P)\n data[206] = ' Q: {0}\\n'.format(Q)\n data[207] = ' N: {0}\\n'.format(N)\n\n data[211] = ' out_prefix: {0}'.format(unique_ID)\n\n # Write the file back\n with open(CFG_FILE_OUT_ARCH, 'w') as f:\n f.writelines(data[:88])\n with open(CFG_FILE_OUT_MAP, 'w') as f:\n f.writelines(data[88:164])\n with open(CFG_FILE_OUT_PROB, 'w') as f:\n f.writelines(data[164:209])\n with open(CFG_FILE_OUT_MODEL, 'w') as f:\n f.writelines(data[209:])\n\n os.chdir(OUTPUT_DIR)\n # print(OUTPUT_DIR)\n\n # Run the config file and check the validity\n command = [ self.parameters.COSTMODEL_EXECUTABLE,\n CFG_FILE_OUT_ARCH,\n CFG_FILE_OUT_MAP,\n CFG_FILE_OUT_PROB,\n CFG_FILE_OUT_MODEL\n ]\n DEVNULL = open(os.devnull, 'wb')\n prnt = sp.call(command, shell=False,stdout=DEVNULL , stderr=DEVNULL)\n\n if(prnt ==0):\n return True\n else:\n return False\n # try:\n # DEVNULL = open(os.devnull, 'wb')\n # prnt = sp.call(command, shell=False,stdout=DEVNULL, stderr=STDOUT)\n # print(prnt)\n # # os.system(COSTMODEL_EXECUTABLE + ' ' + CFG_FILE_OUT)\n # except:\n # return False\n\n return True\n\n def parse(self, PATH):\n \"\"\"\n Parse the output file to get the stats we want.\n \"\"\"\n with open(PATH, 'r') as f:\n data=f.readlines()\n\n energy_IDs = [2,5, 8, 11,14,17,20,23,26]\n energy_count = 0\n\n cost = []\n\n for idx,line in enumerate(data):\n if('Energy (total)' in line):\n energy_count += 1\n if(energy_count in energy_IDs):\n cost.append(float(data[idx].split(\" \")[-2]))\n elif(energy_count > 62):\n break\n cost.append(float(data[-24].split(\" \")[-1]))\n cost.append(float(data[-22].split(\" \")[-2]))\n cost.append(float(data[-23].split(\" \")[-1]))\n\n return cost\n\n def get_domain(self):\n \"\"\"\n Problem domain\n \"\"\"\n ref_tiles, ref_loop_orders, ref_partition = self.references\n\n domain = [\n {'name': 'Nt', 'type': 'discrete', 'domain': (0,len(ref_tiles[0])-1)},\n {'name': 'Ct', 'type': 'discrete', 'domain': (0,len(ref_tiles[1])-1)},\n {'name': 'Kt', 'type': 'discrete', 'domain': (0,len(ref_tiles[2])-1)},\n {'name': 'Rt', 'type': 'discrete', 'domain': (0,len(ref_tiles[3])-1)},\n {'name': 'St', 'type': 'discrete', 'domain': (0,len(ref_tiles[4])-1)},\n {'name': 'Pt', 'type': 'discrete', 'domain': (0,len(ref_tiles[5])-1)},\n {'name': 'Qt', 'type': 'discrete', 'domain': (0,len(ref_tiles[6])-1)},\n {'name': 'loop_order_DRAM', 'type': 'discrete', 'domain': (0,len(ref_loop_orders)-1)},\n {'name': 'loop_order_L2', 'type': 'discrete', 'domain': (0,len(ref_loop_orders)-1)},\n {'name': 'loop_order_L1', 'type': 'discrete', 'domain': (0,len(ref_loop_orders)-1)},\n {'name': 'buffer_part_L2', 'type': 'discrete', 'domain': (0,len(ref_partition[0])-1)},\n {'name': 'buffer_part_L1', 'type': 'discrete', 'domain': (0,len(ref_partition[1])-1)}\n ]\n\n return domain\n\n def parseMetaMapping(self, meta_mapping):\n \"\"\"\n Given a flat mapping, turn it to a mapping that cost model understands.\n \"\"\"\n\n # Extracct\n numHierarchy = self.arch['numHierarchy']\n parHierarchy = self.arch['parallelHierarchy']\n bound = self.problem['dimension_sizes'] # this should be in the same order as the above\n ref_tiles, ref_loop_orders, ref_partition = self.references\n\n tiling, orders, partitions = meta_mapping[:7], meta_mapping[7:10], meta_mapping[10:12]\n\n tile_choices = [ref_tiles[idx][int(t)] for idx,t in enumerate(tiling)]\n mapping_tiles = [list(zip(*tile_choices))[h] for h in range(numHierarchy+1)]\n mapping_orders = [ref_loop_orders[int(o)] for o in orders]\n mapping_partitions = [ref_partition[idx][int(p)] for idx,p in enumerate(partitions)]\n\n return [mapping_tiles, mapping_orders, mapping_partitions]\n\n def getInputVector(self, mapping):\n \"\"\"\n This function returns a flattened mapping vector.\n \"\"\"\n \n # Extract\n tiling, loop_orders, partitions = mapping\n\n ##### Form input tuple: Hyperparameters + Mapping\n\n # Hyperparameters\n input_hyperparams = self.problem['dimension_sizes']\n # Tiling is represented as is\n input_tiling = [item for tile_factors in tiling for item in tile_factors]\n # Loop order is mentioned as the index of each of the dimension.\n input_loop_order = [lord.index(dim) for lord in loop_orders for dim in self.problem['dimension_names']]\n # Partition is mentioned as is.\n input_partitions = [item for partition_sizes in partitions for item in partition_sizes]\n\n # Club them to form input vector\n return input_hyperparams + input_tiling + input_loop_order + input_partitions" ]
[ [ "numpy.array" ] ]
Krishna00111/Machine-Learning-from-Scratch
[ "5d6f5b1a2096acbb57a060385e471123b77b9a68" ]
[ "mlfromscratch/supervised_learning/bayesian_regression.py" ]
[ "from __future__ import print_function, division\r\nimport numpy as np\r\nfrom scipy.stats import chi2, multivariate_normal\r\nfrom mlfromscratch.utils import mean_squared_error, train_test_split, polynomial_features\r\n\r\n\r\n\r\nclass BayesianRegression(object):\r\n \"\"\"Bayesian regression model. If poly_degree is specified the features will\r\n be transformed to with a polynomial basis function, which allows for polynomial\r\n regression. Assumes Normal prior and likelihood for the weights and scaled inverse\r\n chi-squared prior and likelihood for the variance of the weights.\r\n\r\n Parameters:\r\n -----------\r\n n_draws: float\r\n The number of simulated draws from the posterior of the parameters.\r\n mu0: array\r\n The mean values of the prior Normal distribution of the parameters.\r\n omega0: array\r\n The precision matrix of the prior Normal distribution of the parameters.\r\n nu0: float\r\n The degrees of freedom of the prior scaled inverse chi squared distribution.\r\n sigma_sq0: float\r\n The scale parameter of the prior scaled inverse chi squared distribution.\r\n poly_degree: int\r\n The polynomial degree that the features should be transformed to. Allows\r\n for polynomial regression.\r\n cred_int: float\r\n The credible interval (ETI in this impl.). 95 => 95% credible interval of the posterior\r\n of the parameters.\r\n\r\n Reference:\r\n https://github.com/mattiasvillani/BayesLearnCourse/raw/master/Slides/BayesLearnL5.pdf\r\n \"\"\"\r\n def __init__(self, n_draws, mu0, omega0, nu0, sigma_sq0, poly_degree=0, cred_int=95):\r\n self.w = None\r\n self.n_draws = n_draws\r\n self.poly_degree = poly_degree\r\n self.cred_int = cred_int\r\n\r\n # Prior parameters\r\n self.mu0 = mu0\r\n self.omega0 = omega0\r\n self.nu0 = nu0\r\n self.sigma_sq0 = sigma_sq0\r\n\r\n # Allows for simulation from the scaled inverse chi squared\r\n # distribution. Assumes the variance is distributed according to\r\n # this distribution.\r\n # Reference:\r\n # https://en.wikipedia.org/wiki/Scaled_inverse_chi-squared_distribution\r\n def _draw_scaled_inv_chi_sq(self, n, df, scale):\r\n X = chi2.rvs(size=n, df=df)\r\n sigma_sq = df * scale / X\r\n return sigma_sq\r\n\r\n def fit(self, X, y):\r\n\r\n # If polynomial transformation\r\n if self.poly_degree:\r\n X = polynomial_features(X, degree=self.poly_degree)\r\n\r\n n_samples, n_features = np.shape(X)\r\n\r\n X_X = X.T.dot(X)\r\n\r\n # Least squares approximate of beta\r\n beta_hat = np.linalg.pinv(X_X).dot(X.T).dot(y)\r\n\r\n # The posterior parameters can be determined analytically since we assume\r\n # conjugate priors for the likelihoods.\r\n\r\n # Normal prior / likelihood => Normal posterior\r\n mu_n = np.linalg.pinv(X_X + self.omega0).dot(X_X.dot(beta_hat)+self.omega0.dot(self.mu0))\r\n omega_n = X_X + self.omega0\r\n # Scaled inverse chi-squared prior / likelihood => Scaled inverse chi-squared posterior\r\n nu_n = self.nu0 + n_samples\r\n sigma_sq_n = (1.0/nu_n)*(self.nu0*self.sigma_sq0 + \\\r\n (y.T.dot(y) + self.mu0.T.dot(self.omega0).dot(self.mu0) - mu_n.T.dot(omega_n.dot(mu_n))))\r\n\r\n # Simulate parameter values for n_draws\r\n beta_draws = np.empty((self.n_draws, n_features))\r\n for i in range(self.n_draws):\r\n sigma_sq = self._draw_scaled_inv_chi_sq(n=1, df=nu_n, scale=sigma_sq_n)\r\n beta = multivariate_normal.rvs(size=1, mean=mu_n[:,0], cov=sigma_sq*np.linalg.pinv(omega_n))\r\n # Save parameter draws\r\n beta_draws[i, :] = beta\r\n\r\n # Select the mean of the simulated variables as the ones used to make predictions\r\n self.w = np.mean(beta_draws, axis=0)\r\n\r\n # Lower and upper boundary of the credible interval\r\n l_eti = 50 - self.cred_int/2\r\n u_eti = 50 + self.cred_int/2\r\n self.eti = np.array([[np.percentile(beta_draws[:,i], q=l_eti), np.percentile(beta_draws[:,i], q=u_eti)] \\\r\n for i in range(n_features)])\r\n\r\n def predict(self, X, eti=False):\r\n\r\n # If polynomial transformation\r\n if self.poly_degree:\r\n X = polynomial_features(X, degree=self.poly_degree)\r\n\r\n y_pred = X.dot(self.w)\r\n # If the lower and upper boundaries for the 95%\r\n # equal tail interval should be returned\r\n if eti:\r\n lower_w = self.eti[:, 0]\r\n upper_w = self.eti[:, 1]\r\n y_lower_pred = X.dot(lower_w)\r\n y_upper_pred = X.dot(upper_w)\r\n return y_pred, y_lower_pred, y_upper_pred\r\n\r\n return y_pred\r\n" ]
[ [ "numpy.empty", "numpy.shape", "numpy.linalg.pinv", "scipy.stats.chi2.rvs", "numpy.percentile", "numpy.mean" ] ]
matthew-brett/statsmodels
[ "915c9dc2d762c5592ac17a7cf5f1cc957fcbde1c", "915c9dc2d762c5592ac17a7cf5f1cc957fcbde1c" ]
[ "scikits/statsmodels/datasets/stackloss/data.py", "scikits/statsmodels/nonparametric/bandwidths.py" ]
[ "\"\"\"Stack loss data\"\"\"\n\n__all__ = ['COPYRIGHT','TITLE','SOURCE','DESCRSHORT','DESCRLONG','NOTE', 'load']\n\n\n__docformat__ = 'restructuredtext'\n\nCOPYRIGHT = \"\"\"This is public domain. \"\"\"\nTITLE = __doc__\nSOURCE = \"\"\"\nBrownlee, K. A. (1965), \"Statistical Theory and Methodology in\nScience and Engineering\", 2nd edition, New York:Wiley.\n\"\"\"\n\nDESCRSHORT = \"\"\"Stack loss plant data of Brownlee (1965)\"\"\"\n\nDESCRLONG = \"\"\"The stack loss plant data of Brownlee (1965) contains\n21 days of measurements from a plant's oxidation of ammonia to nitric acid.\nThe nitric oxide pollutants are captured in an absorption tower.\"\"\"\n\nNOTE = \"\"\"\nNumber of Observations - 21\n\nNumber of Variables - 4\n\nVariable name definitions::\n\n STACKLOSS - 10 times the percentage of ammonia going into the plant that\n escapes from the absoroption column\n AIRFLOW - Rate of operation of the plant\n WATERTEMP - Cooling water temperature in the absorption tower\n ACIDCONC - Acid concentration of circulating acid minus 50 times 10.\n\"\"\"\n\nfrom numpy import recfromtxt, column_stack, array\nfrom scikits.statsmodels.datasets import Dataset\nfrom os.path import dirname, abspath\n\ndef load():\n \"\"\"\n Load the stack loss data and returns a Dataset class instance.\n\n Returns\n --------\n Dataset instance:\n See DATASET_PROPOSAL.txt for more information.\n \"\"\"\n filepath = dirname(abspath(__file__))\n data = recfromtxt(open(filepath + '/stackloss.csv',\"rb\"), delimiter=\",\",\n names=True, dtype=float)\n names = list(data.dtype.names)\n endog = array(data[names[0]], dtype=float)\n endog_name = names[0]\n exog = column_stack(data[i] for i in names[1:]).astype(float)\n exog_name = names[1:]\n dataset = Dataset(data=data, names=names, endog=endog, exog=exog,\n endog_name = endog_name, exog_name=exog_name)\n return dataset\n", "import numpy as np\nfrom scipy.stats import scoreatpercentile as sap\n\n#from scipy.stats import norm\n\ndef _select_sigma(X):\n \"\"\"\n Returns the smaller of std(X, ddof=1) or normalized IQR(X) over axis 0.\n\n References\n ----------\n Silverman (1986) p.47\n \"\"\"\n# normalize = norm.ppf(.75) - norm.ppf(.25)\n normalize = 1.349\n# IQR = np.subtract.reduce(percentile(X, [75,25],\n# axis=axis), axis=axis)/normalize\n IQR = (sap(X, 75) - sap(X, 25))/normalize\n return np.minimum(np.std(X, axis=0, ddof=1), IQR)\n\n\n## Univariate Rule of Thumb Bandwidths ##\ndef bw_scott(x):\n \"\"\"\n Scott's Rule of Thumb\n\n Parameter\n ---------\n x : array-like\n Array for which to get the bandwidth\n\n Returns\n -------\n bw : float\n The estimate of the bandwidth\n\n Notes\n -----\n Returns 1.059 * A * n ** (-1/5.)\n\n A = min(std(x, ddof=1), IQR/1.349)\n IQR = np.subtract.reduce(np.percentile(x, [75,25]))\n\n References\n ---------- ::\n\n Scott, D.W. (1992) `Multivariate Density Estimation: Theory, Practice, and\n Visualization.`\n \"\"\"\n A = _select_sigma(x)\n n = len(x)\n return 1.059 * A * n ** -.2\n\ndef bw_silverman(x):\n \"\"\"f\n Silverman's Rule of Thumb\n\n Parameter\n ---------\n x : array-like\n Array for which to get the bandwidth\n\n Returns\n -------\n bw : float\n The estimate of the bandwidth\n\n Notes\n -----\n Returns .9 * A * n ** (-1/5.)\n\n A = min(std(x, ddof=1), IQR/1.349)\n IQR = np.subtract.reduce(np.percentile(x, [75,25]))\n\n References\n ---------- ::\n\n Silverman, B.W. (1986) `Density Estimation.`\n \"\"\"\n A = _select_sigma(x)\n n = len(x)\n return .9 * A * n ** -.2\n\n## Plug-In Methods ##\n\n## Least Squares Cross-Validation ##\n\n## Helper Functions ##\n\nbandwidth_funcs = dict(scott=bw_scott,silverman=bw_silverman)\n\ndef select_bandwidth(X, bw, kernel):\n \"\"\"\n Selects bandwidth\n \"\"\"\n bw = bw.lower()\n if bw not in [\"scott\",\"silverman\"]:\n raise ValueError(\"Bandwidth %s not understood\" % bw)\n#TODO: uncomment checks when we have non-rule of thumb bandwidths for diff. kernels\n# if kernel == \"gauss\":\n return bandwidth_funcs[bw](X)\n# else:\n# raise ValueError(\"Only Gaussian Kernels are currently supported\")\n\n" ]
[ [ "numpy.array", "numpy.column_stack" ], [ "scipy.stats.scoreatpercentile", "numpy.std" ] ]
vutuanhai237/QuantumTomographyProject
[ "78058e3faece2209e46c9f9e16a1c38cdb33e7e2" ]
[ "codes/qtm/qcompilation.py" ]
[ "import qtm.base\nimport qtm.optimizer\nimport qtm.loss\nimport qtm.utilities\nimport numpy as np\nimport typing, types\nimport qiskit\nimport matplotlib.pyplot as plt\n\nclass QuantumCompilation():\n def __init__(self) -> None:\n self.u = None\n self.vdagger = None\n self.is_trained = False\n self.optimizer = None\n self.loss_func = None\n self.thetas = None\n self.thetass = []\n self.loss_values = []\n self.fidelities = []\n self.traces = []\n self.kwargs = None\n return\n\n def __init__(self, u: typing.Union[types.FunctionType, qiskit.QuantumCircuit], vdagger: typing.Union[types.FunctionType, qiskit.QuantumCircuit], optimizer: typing.Union[types.FunctionType, str], loss_func: typing.Union[types.FunctionType, str], thetas: np.ndarray = np.array([]), **kwargs):\n \"\"\"_summary_\n\n Args:\n - u (typing.Union[types.FunctionType, qiskit.QuantumCircuit]): In quantum state preparation problem, this is the ansatz. In tomography, this is the circuit that generate random Haar state.\n - vdagger (typing.Union[types.FunctionType, qiskit.QuantumCircuit]): In quantum tomography problem, this is the ansatz. In state preparation, this is the circuit that generate random Haar state.\n - optimizer (typing.Union[types.FunctionType, str]): You can put either string or function here. If type string, qcompilation produces some famous optimizers such as: 'sgd', 'adam', 'qng-fubini-study', 'qng-qfim', 'qng-adam'.\n - loss_func (typing.Union[types.FunctionType, str]): You can put either string or function here. If type string, qcompilation produces some famous optimizers such as: 'loss_basic' (1 - p0) and 'loss_fubini_study' (\\sqrt{(1 - p0)}).\n - thetas (np.ndarray, optional): initial parameters. Note that it must fit with your ansatz. Defaults to np.array([]).\n \"\"\"\n self.set_u(u)\n self.set_vdagger(vdagger)\n self.set_optimizer(optimizer)\n self.set_loss_func(loss_func)\n self.set_kwargs(**kwargs)\n self.set_thetas(thetas)\n return\n\n def set_u(self, _u: typing.Union[types.FunctionType, qiskit.QuantumCircuit]):\n \"\"\"In quantum state preparation problem, this is the ansatz. In tomography, this is the circuit that generate random Haar state.\n\n Args:\n - _u (typing.Union[types.FunctionType, qiskit.QuantumCircuit]): init circuit\n \"\"\"\n if callable(_u) or isinstance(_u, qiskit.QuantumCircuit):\n self.u = _u\n else:\n raise ValueError('The U part must be a function f: thetas -> qiskit.QuantumCircuit or a determined quantum circuit')\n return\n\n def set_vdagger(self, _vdagger):\n \"\"\"In quantum state tomography problem, this is the ansatz. In state preparation, this is the circuit that generate random Haar state.\n\n Args:\n - _vdagger (typing.Union[types.FunctionType, qiskit.QuantumCircuit]): init circuit\n \"\"\"\n if callable(_vdagger) or isinstance(_vdagger, qiskit.QuantumCircuit):\n self.vdagger = _vdagger\n else:\n raise ValueError('The V dagger part must be a function f: thetas -> qiskit.QuantumCircuit or a determined quantum circuit')\n return\n\n def set_loss_func(self, _loss_func: typing.Union[types.FunctionType, str]):\n \"\"\"Set the loss function for compiler\n\n Args:\n - _loss_func (typing.Union[types.FunctionType, str])\n\n Raises:\n ValueError: when you pass wrong type\n \"\"\"\n if callable(_loss_func):\n self.loss_func = _loss_func\n elif isinstance(_loss_func, str):\n if _loss_func == 'loss-basic':\n self.loss_func = qtm.loss.loss_basis\n elif _loss_func == 'loss-fubini-study':\n self.loss_func = qtm.loss.loss_fubini_study\n else:\n raise ValueError('The loss function must be a function f: measurement value -> loss value or string in [\"loss_basic\", \"loss_fubini_study\"]')\n return\n\n def set_optimizer(self, _optimizer: typing.Union[types.FunctionType, str]):\n \"\"\"Change the optimizer of the compiler\n\n Args:\n - _optimizer (typing.Union[types.FunctionType, str])\n\n Raises:\n ValueError: when you pass wrong type\n \"\"\"\n if callable(_optimizer):\n self.optimizer = _optimizer\n elif isinstance(_optimizer,str):\n if _optimizer == 'sgd':\n self.optimizer = qtm.optimizer.sgd\n elif _optimizer == 'adam':\n self.optimizer = qtm.optimizer.adam\n elif _optimizer == 'qng-fubini-study':\n self.optimizer = qtm.optimizer.qng_fubini_study\n elif _optimizer == 'qng-qfim':\n self.optimizer = qtm.optimizer.qng_qfim\n elif _optimizer == 'qng-adam':\n self.optimizer = qtm.optimizer.qng_adam\n else:\n raise ValueError('The optimizer must be a function f: thetas -> thetas or string in [\"sgd\", \"adam\", \"qng_qfim\", \"qng_fubini_study\", \"qng_adam\"]')\n return\n \n def set_num_step(self, _num_step: int):\n \"\"\"Set the number of iteration for compiler\n\n Args:\n - _num_step (int): number of iterations\n\n Raises:\n ValueError: when you pass a nasty value\n \"\"\"\n if _num_step > 0 and isinstance(_num_step, int):\n self.num_step = _num_step\n else:\n raise ValueError('Number of iterations must be a integer, such that 10 or 100.')\n return\n\n def set_thetas(self, _thetas: np.ndarray):\n \"\"\"Set parameter, it will be updated at each iteration\n\n Args:\n _thetas (np.ndarray): parameter for u or vdagger\n \"\"\"\n if isinstance(_thetas, np.ndarray):\n self.thetas = _thetas\n else:\n raise ValueError('The parameter must be numpy array')\n return\n\n def set_kwargs(self, **kwargs):\n \"\"\"Arguments supported for u or vdagger only. Ex: number of layer\n \"\"\"\n self.__dict__.update(**kwargs)\n self.kwargs = kwargs\n return\n\n def fit(self, num_steps: int = 100, verbose: int = 0):\n \"\"\"Optimize the thetas parameters\n\n Args:\n - num_steps: number of iterations\n - verbose (int, optional): 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per 10 steps. Verbose 1 is good for timing training time, verbose 2 if you want to log loss values to a file. Please install package tdqm if you want to use verbose 1. \n \n \"\"\"\n self.thetass, self.loss_values = qtm.base.fit(\n self.u, self.vdagger, self.thetas, num_steps, self.loss_func, self.optimizer, verbose, is_return_all_thetas=True, **self.kwargs)\n self.is_trained = True\n if callable(self.u):\n self.traces, self.fidelities = qtm.utilities.calculate_state_preparation_metrics(self.u, self.vdagger, self.thetass, **self.kwargs)\n else:\n self.traces, self.fidelities = qtm.utilities.calculate_state_tomography_metrics(self.u, self.vdagger, self.thetass, **self.kwargs)\n return\n\n def save(self, metric: str = \"\", text = \"\", path = './', save_all: bool = False):\n \"\"\"_summary_\n\n Args:\n - metric (str)\n - text (str): Defaults to './'. Additional file name string\n - path (str, optional): Defaults to './'.\n - save_all (bool, optional): Save thetass, fidelity, trace and loss_value if save_all = True\n\n Raises:\n ValueError: if save_all = False and metric is not right.\n \"\"\"\n if save_all:\n np.savetxt(path + \"/thetass\" + text + \".csv\", self.thetass, delimiter=\",\")\n np.savetxt(path + \"/fidelities\"+ text + \".csv\", self.fidelities, delimiter=\",\")\n np.savetxt(path + \"/traces\" + text + \".csv\", self.traces, delimiter=\",\")\n np.savetxt(path + \"/loss_values\" + text + \".csv\", self.loss_values, delimiter=\",\")\n else:\n if metric == 'thetas':\n np.savetxt(path + \"/thetass\" + text + \".csv\", self.thetass, delimiter=\",\")\n elif metric == 'fidelity':\n np.savetxt(path + \"/fidelities\" + text + \".csv\", self.fidelities, delimiter=\",\")\n elif metric == 'trace':\n np.savetxt(path + \"/traces\" + text + \".csv\", self.traces, delimiter=\",\")\n elif metric == 'loss_value':\n np.savetxt(path + \"/loss_values\" + text + \".csv\", self.loss_values, delimiter=\",\")\n else:\n raise ValueError('The metric must be thetas, fidelity, trace or loss_value')\n print(\"Saved \" + metric + \" at \" + path)\n return\n\n def reset(self):\n \"\"\"Delete all current property of compiler\n \"\"\"\n self.u = None\n self.vdagger = None\n self.is_trained = False\n self.optimizer = None\n self.loss_func = None\n self.num_step = 0\n self.thetas = None\n self.thetass = []\n self.loss_values = []\n return\n" ]
[ [ "numpy.array", "numpy.savetxt" ] ]
snoopycrimecop/scripts
[ "7ec5df31e83f1fda7efc02aca3f3426174547308" ]
[ "omero/util_scripts/Combine_Images.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n-----------------------------------------------------------------------------\n Copyright (C) 2006-2014 University of Dundee. All rights reserved.\n\n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\n------------------------------------------------------------------------------\n\nThis script takes a number of images (or Z-stacks) and merges them to create\nadditional C, T, Z dimensions.\n\n@author Will Moore &nbsp;&nbsp;&nbsp;&nbsp;\n<a href=\"mailto:[email protected]\">[email protected]</a>\n@version 3.0\n<small>\n(<b>Internal version:</b> $Revision: $Date: $)\n</small>\n@since 3.0-Beta4.2\n\n\"\"\"\n\nimport re\nfrom numpy import zeros\n\nimport omero\nimport omero.scripts as scripts\nfrom omero.gateway import BlitzGateway\nimport omero.constants\nfrom omero.rtypes import rstring, rlong, robject\nimport omero.util.script_utils as script_utils\n\nCOLOURS = script_utils.COLOURS\n\nDEFAULT_T_REGEX = \"_T\"\nDEFAULT_Z_REGEX = \"_Z\"\nDEFAULT_C_REGEX = \"_C\"\n\nchannel_regexes = {\n DEFAULT_C_REGEX: r'_C(?P<C>.+?)(_|$)',\n \"C\": r'C(?P<C>\\w+?)',\n \"_c\": r'_c(?P<C>\\w+?)',\n \"_w\": r'_w(?P<C>\\w+?)',\n \"None (single channel)\": False}\n\nz_regexes = {\n DEFAULT_Z_REGEX: r'_Z(?P<Z>\\d+)',\n \"Z\": r'Z(?P<Z>\\d+)',\n \"_z\": r'_z(?P<Z>\\d+)',\n \"None (single z section)\": False}\n\ntime_regexes = {\n DEFAULT_T_REGEX: r'_T(?P<T>\\d+)',\n \"T\": r'T(?P<T>\\d+)',\n \"_t\": r'_t(?P<T>\\d+)',\n \"None (single time point)\": False}\n\n\ndef get_plane(raw_pixel_store, pixels, the_z, the_c, the_t):\n \"\"\"\n This method downloads the specified plane of the OMERO image and returns\n it as a numpy array.\n\n @param session The OMERO session\n @param imageId The ID of the image to download\n @param pixels The pixels object, with pixelsType\n @param imageName The name of the image to write. If no path, saved in\n the current directory.\n \"\"\"\n\n # get the plane\n pixels_id = pixels.getId().getValue()\n raw_pixel_store.setPixelsId(pixels_id, True)\n return script_utils.download_plane(\n raw_pixel_store, pixels, the_z, the_c, the_t)\n\n\ndef manually_assign_images(parameter_map, image_ids, source_z):\n\n size_z = source_z\n size_c = 1\n size_t = 1\n\n dims = []\n dim_sizes = [1, 1, 1] # at least 1 in each dimension\n dim_map = {\"C\": \"Size_C\", \"Z\": \"Size_Z\", \"T\": \"Size_T\"}\n dimension_params = [\"Dimension_1\", \"Dimension_2\", \"Dimension_3\"]\n\n for i, d in enumerate(dimension_params):\n if d in parameter_map and len(parameter_map[d]) > 0:\n # First letter of 'Channel' or 'Time' or 'Z'\n dim = parameter_map[d][0]\n dims.append(dim)\n if dim == \"Z\" and source_z > 1:\n continue\n size_param = dim_map[dim]\n if size_param in parameter_map:\n dim_sizes[i] = parameter_map[size_param]\n else:\n dim_sizes[i] = len(image_ids) // \\\n (dim_sizes[0] * dim_sizes[1] * dim_sizes[2])\n\n index = 0\n\n image_map = {} # map of (z,c,t) : imageId\n\n for dim3 in range(dim_sizes[2]):\n for dim2 in range(dim_sizes[1]):\n for dim1 in range(dim_sizes[0]):\n if index >= len(image_ids):\n break\n z, c, t = (0, 0, 0)\n ddd = (dim1, dim2, dim3)\n # bit of a hack, but this somehow does my head in!!\n for i, d in enumerate(dims):\n if d == \"C\":\n c = ddd[i]\n size_c = max(size_c, c+1)\n elif d == \"T\":\n t = ddd[i]\n size_t = max(size_t, t+1)\n elif d == \"Z\":\n z = ddd[i]\n size_z = max(size_z, z+1)\n # handle Z stacks...\n if source_z > 1:\n for src_z in range(source_z):\n image_map[(src_z, c, t)] = (image_ids[index], src_z)\n else:\n image_map[(z, c, t)] = (image_ids[index], 0)\n index += 1\n\n return (size_z, size_c, size_t, image_map)\n\n\ndef assign_images_by_regex(parameter_map, image_ids, query_service, source_z,\n id_name_map=None):\n\n c = None\n regex_channel = channel_regexes[parameter_map[\"Channel_Name_Pattern\"]]\n if regex_channel:\n c = re.compile(regex_channel)\n\n t = None\n regex_t = time_regexes[parameter_map[\"Time_Name_Pattern\"]]\n if regex_t:\n t = re.compile(regex_t)\n\n z = None\n regex_z = z_regexes[parameter_map[\"Z_Name_Pattern\"]]\n if regex_z:\n z = re.compile(regex_z)\n\n # other parameters we need to determine\n size_z = source_z\n size_t = 1\n z_start = None # could be 0 or 1 ?\n t_start = None\n\n image_map = {} # map of (z,c,t) : imageId\n channels = []\n\n if id_name_map is None:\n id_name_map = get_image_names(query_service, image_ids)\n\n # assign each (imageId,zPlane) to combined image (z,c,t) by name.\n for iid in image_ids:\n name = id_name_map[iid]\n if t:\n t_search = t.search(name)\n if c:\n c_search = c.search(name)\n\n if t is None or t_search is None:\n the_t = 0\n else:\n the_t = int(t_search.group('T'))\n\n if c is None or c_search is None:\n c_name = \"0\"\n else:\n c_name = c_search.group('C')\n if c_name in channels:\n the_c = channels.index(c_name)\n else:\n the_c = len(channels)\n channels.append(c_name)\n\n size_t = max(size_t, the_t+1)\n if t_start is None:\n t_start = the_t\n else:\n t_start = min(t_start, the_t)\n\n # we have T and C now. Need to check if source images are Z stacks\n if source_z > 1:\n z_start = 0\n for src_z in range(source_z):\n image_map[(src_z, the_c, the_t)] = (iid, src_z)\n else:\n if z:\n z_search = z.search(name)\n\n if z is None or z_search is None:\n the_z = 0\n else:\n the_z = int(z_search.group('Z'))\n\n size_z = max(size_z, the_z+1)\n if z_start is None:\n z_start = the_z\n else:\n z_start = min(z_start, the_z)\n\n # every plane comes from z=0\n image_map[(the_z, the_c, the_t)] = (iid, 0)\n\n # if indexes were 1-based (or higher), need to shift indexes accordingly.\n if t_start > 0 or z_start > 0:\n size_t = size_t-t_start\n size_z = size_z-z_start\n i_map = {}\n for key, value in image_map.items():\n z, c, t = key\n i_map[(z-z_start, c, t-t_start)] = value\n else:\n i_map = image_map\n\n c_names = {}\n for c, name in enumerate(channels):\n c_names[c] = name\n return (size_z, c_names, size_t, i_map)\n\n\ndef get_image_names(query_service, image_ids):\n id_string = \",\".join([str(i) for i in image_ids])\n query_string = \"select i from Image i where i.id in (%s)\" % id_string\n images = query_service.findAllByQuery(query_string, None)\n id_map = {}\n for i in images:\n iid = i.getId().getValue()\n name = i.getName().getValue()\n id_map[iid] = name\n return id_map\n\n\ndef pick_pixel_sizes(pixel_sizes):\n \"\"\"\n Process a list of pixel sizes and pick sizes to set for new image.\n If we have different sizes from different images, return None\n \"\"\"\n pix_size = None\n for px in pixel_sizes:\n if px is None:\n continue\n if pix_size is None:\n pix_size = px\n else:\n # compare - if different, return None\n if (pix_size.getValue() != px.getValue() or\n pix_size.getUnit() != px.getUnit()):\n return None\n return pix_size\n\n\ndef make_single_image(services, parameter_map, image_ids, dataset, colour_map):\n \"\"\"\n This takes the images specified by image_ids, sorts them in to Z,C,T\n dimensions according to parameters in the parameter_map, assembles them\n into a new Image, which is saved in dataset.\n \"\"\"\n\n if len(image_ids) == 0:\n return\n\n rendering_engine = services[\"renderingEngine\"]\n query_service = services[\"queryService\"]\n pixels_service = services[\"pixelsService\"]\n raw_pixel_store = services[\"rawPixelStore\"]\n raw_pixel_store_upload = services[\"rawPixelStoreUpload\"]\n update_service = services[\"updateService\"]\n container_service = services[\"containerService\"]\n\n # Filter images by name if user has specified filter.\n id_name_map = None\n if \"Filter_Names\" in parameter_map:\n filter_string = parameter_map[\"Filter_Names\"]\n if len(filter_string) > 0:\n id_name_map = get_image_names(query_service, image_ids)\n image_ids = [i for i in image_ids\n if id_name_map[i].find(filter_string) > -1]\n\n image_id = image_ids[0]\n\n # get pixels, with pixelsType, from the first image\n query_string = \"select p from Pixels p join fetch p.image i join \"\\\n \"fetch p.pixelsType pt where i.id='%d'\" % image_id\n pixels = query_service.findByQuery(query_string, None)\n # use the pixels type object we got from the first image.\n pixels_type = pixels.getPixelsType()\n\n # combined image will have same X and Y sizes...\n size_x = pixels.getSizeX().getValue()\n size_y = pixels.getSizeY().getValue()\n # if we have a Z stack, use this in new image (don't combine Z)\n source_z = pixels.getSizeZ().getValue()\n\n # Now we need to find where our planes are coming from.\n # imageMap is a map of destination:source, defined as (newX, newY,\n # newZ):(imageId, z)\n if \"Manually_Define_Dimensions\" in parameter_map and \\\n parameter_map[\"Manually_Define_Dimensions\"]:\n size_z, size_c, size_t, image_map = manually_assign_images(\n parameter_map, image_ids, source_z)\n c_names = {}\n else:\n size_z, c_names, size_t, image_map = assign_images_by_regex(\n parameter_map, image_ids, query_service, source_z, id_name_map)\n size_c = len(c_names)\n\n if \"Channel_Names\" in parameter_map:\n for c, name in enumerate(parameter_map[\"Channel_Names\"]):\n c_names[c] = name\n\n image_name = \"combinedImage\"\n description = \"created from image Ids: %s\" % image_ids\n\n channel_list = range(size_c)\n iid = pixels_service.createImage(size_x, size_y, size_z, size_t,\n channel_list, pixels_type, image_name,\n description)\n image = container_service.getImages(\"Image\", [iid.getValue()], None)[0]\n\n pixels_id = image.getPrimaryPixels().getId().getValue()\n raw_pixel_store_upload.setPixelsId(pixels_id, True)\n\n pixel_sizes = {'x': [], 'y': []}\n for the_c in range(size_c):\n min_value = 0\n max_value = 0\n for the_z in range(size_z):\n for the_t in range(size_t):\n if (the_z, the_c, the_t) in image_map:\n image_id, plane_z = image_map[(the_z, the_c, the_t)]\n query_string = \"select p from Pixels p join fetch \"\\\n \"p.image i join fetch p.pixelsType pt where \"\\\n \"i.id='%d'\" % image_id\n pixels = query_service.findByQuery(query_string,\n None)\n plane_2d = get_plane(raw_pixel_store, pixels, plane_z,\n 0, 0)\n # Note pixels sizes (may be None)\n pixel_sizes['x'].append(pixels.getPhysicalSizeX())\n pixel_sizes['y'].append(pixels.getPhysicalSizeY())\n else:\n plane_2d = zeros((size_y, size_x))\n script_utils.upload_plane(raw_pixel_store_upload,\n plane_2d, the_z, the_c, the_t)\n min_value = min(min_value, plane_2d.min())\n max_value = max(max_value, plane_2d.max())\n pixels_service.setChannelGlobalMinMax(pixels_id, the_c,\n float(min_value),\n float(max_value))\n rgba = COLOURS[\"White\"]\n if the_c in colour_map:\n rgba = colour_map[the_c]\n script_utils.reset_rendering_settings(rendering_engine, pixels_id,\n the_c, min_value, max_value,\n rgba)\n\n # rename new channels\n pixels = rendering_engine.getPixels()\n # has channels loaded - (getting Pixels from image doesn't)\n i = 0\n for c in pixels.iterateChannels():\n # c is an instance of omero.model.ChannelI\n if i >= len(c_names):\n break\n lc = c.getLogicalChannel() # returns omero.model.LogicalChannelI\n lc.setName(rstring(c_names[i]))\n update_service.saveObject(lc)\n i += 1\n\n # Set pixel sizes if known\n pix_size_x = pick_pixel_sizes(pixel_sizes['x'])\n pix_size_y = pick_pixel_sizes(pixel_sizes['y'])\n if pix_size_x is not None or pix_size_y is not None:\n # reload to avoid OptimisticLockException\n pixels = services[\"queryService\"].get('Pixels',\n pixels.getId().getValue())\n if pix_size_x is not None:\n pixels.setPhysicalSizeX(pix_size_x)\n if pix_size_y is not None:\n pixels.setPhysicalSizeY(pix_size_y)\n services[\"updateService\"].saveObject(pixels)\n\n # put the image in dataset, if specified.\n if dataset and dataset.canLink():\n link = omero.model.DatasetImageLinkI()\n link.parent = omero.model.DatasetI(dataset.getId(), False)\n link.child = omero.model.ImageI(image.getId().getValue(), False)\n update_service.saveAndReturnObject(link)\n else:\n link = None\n\n return image, link\n\n\ndef combine_images(conn, parameter_map):\n\n # get the services we need\n services = {}\n services[\"containerService\"] = conn.getContainerService()\n services[\"renderingEngine\"] = conn.createRenderingEngine()\n services[\"queryService\"] = conn.getQueryService()\n services[\"pixelsService\"] = conn.getPixelsService()\n services[\"rawPixelStore\"] = conn.c.sf.createRawPixelsStore()\n services[\"rawPixelStoreUpload\"] = conn.c.sf.createRawPixelsStore()\n services[\"updateService\"] = conn.getUpdateService()\n services[\"rawFileStore\"] = conn.createRawFileStore()\n\n query_service = services[\"queryService\"]\n\n colour_map = {}\n if \"Channel_Colours\" in parameter_map:\n for c, colour in enumerate(parameter_map[\"Channel_Colours\"]):\n if colour in COLOURS:\n colour_map[c] = COLOURS[colour]\n\n # Get images or datasets\n message = \"\"\n objects, log_message = script_utils.get_objects(conn, parameter_map)\n message += log_message\n if not objects:\n return None, message\n\n # get the images IDs from list (in order) or dataset (sorted by name)\n output_images = []\n links = []\n\n data_type = parameter_map[\"Data_Type\"]\n if data_type == \"Image\":\n dataset = None\n objects.sort(key=lambda x: (x.getName())) # Sort images by name\n image_ids = [image.id for image in objects]\n # get dataset from first image\n query_string = \"select i from Image i join fetch i.datasetLinks idl\"\\\n \" join fetch idl.parent where i.id in (%s)\" % image_ids[0]\n image = query_service.findByQuery(query_string, None)\n if image:\n for link in image.iterateDatasetLinks():\n ds = link.parent\n dataset = conn.getObject(\"Dataset\", ds.getId().getValue())\n break # only use 1st dataset\n new_img, link = make_single_image(services, parameter_map, image_ids,\n dataset, colour_map)\n if new_img:\n output_images.append(new_img)\n if link:\n links.append(link)\n else:\n for dataset in objects:\n images = list(dataset.listChildren())\n if not images:\n continue\n images.sort(key=lambda x: (x.getName()))\n image_ids = [i.getId() for i in images]\n new_img, link = make_single_image(services, parameter_map,\n image_ids, dataset, colour_map)\n if new_img:\n output_images.append(new_img)\n if link:\n links.append(link)\n\n # try and close any stateful services\n for s in services:\n try:\n s.close()\n except Exception:\n pass\n\n if output_images:\n if len(output_images) > 1:\n message += \"%s new images created\" % len(output_images)\n else:\n message += \"New image created\"\n if not links or not len(links) == len(output_images):\n message += \" but could not be attached\"\n else:\n message += \"No image created\"\n message += \".\"\n\n return output_images, message\n\n\ndef run_script():\n \"\"\"\n The main entry point of the script, as called by the client via the\n scripting service, passing the required parameters.\n \"\"\"\n ckeys = list(COLOURS.keys())\n ckeys.sort()\n c_options = [rstring(col) for col in ckeys]\n data_types = [rstring('Dataset'), rstring('Image')]\n first_dim = [rstring('Time'), rstring('Channel'), rstring('Z')]\n extra_dims = [rstring(''), rstring('Time'), rstring('Channel'),\n rstring('Z')]\n channel_regs = [rstring(r) for r in channel_regexes.keys()]\n z_regs = [rstring(r) for r in z_regexes.keys()]\n t_regs = [rstring(r) for r in time_regexes.keys()]\n\n client = scripts.client(\n 'Combine_Images.py',\n \"\"\"Combine several single-plane images (or Z-stacks) into one with \\\ngreater Z, C, T dimensions.\nSee http://help.openmicroscopy.org/scripts.html\"\"\",\n\n scripts.String(\n \"Data_Type\", optional=False, grouping=\"1\",\n description=\"Use all the images in specified 'Datasets' or choose\"\n \" individual 'Images'.\", values=data_types, default=\"Image\"),\n\n scripts.List(\n \"IDs\", optional=False, grouping=\"2\",\n description=\"List of Dataset IDs or Image IDs to \"\n \"combine.\").ofType(rlong(0)),\n\n scripts.String(\n \"Filter_Names\", grouping=\"2.1\",\n description=\"Filter the images by names that contain this value\"),\n\n scripts.Bool(\n \"Auto_Define_Dimensions\", grouping=\"3\", default=True,\n description=\"\"\"Choose new dimensions with respect to the order of\"\n \" the input images. See URL above.\"\"\"),\n\n scripts.String(\n \"Channel_Name_Pattern\", grouping=\"3.1\", default=DEFAULT_C_REGEX,\n values=channel_regs,\n description=\"\"\"Auto-pick images by channel in the image name\"\"\"),\n\n scripts.String(\n \"Z_Name_Pattern\", grouping=\"3.2\",\n default=DEFAULT_Z_REGEX, values=z_regs,\n description=\"\"\"Auto-pick images by Z-index in the image name\"\"\"),\n\n scripts.String(\n \"Time_Name_Pattern\", grouping=\"3.3\", default=DEFAULT_T_REGEX,\n values=t_regs,\n description=\"\"\"Auto-pick images by T-index in the image name\"\"\"),\n\n scripts.Bool(\n \"Manually_Define_Dimensions\", grouping=\"4\", default=False,\n description=\"\"\"Choose new dimensions with respect to the order of\"\n \" the input images. See URL above.\"\"\"),\n\n scripts.String(\n \"Dimension_1\", grouping=\"4.1\",\n description=\"The first Dimension to change\", values=first_dim),\n\n scripts.String(\n \"Dimension_2\", grouping=\"4.2\", values=extra_dims, default=\"\",\n description=\"The second Dimension to change. Only specify this if\"\n \" combining multiple dimensions.\"),\n\n scripts.String(\n \"Dimension_3\", grouping=\"4.3\", values=extra_dims, default=\"\",\n description=\"The third Dimension to change. Only specify this if\"\n \" combining multiple dimensions.\"),\n\n scripts.Int(\n \"Size_Z\", grouping=\"4.4\",\n description=\"Number of Z planes in new image\", min=1),\n\n scripts.Int(\n \"Size_C\", grouping=\"4.5\",\n description=\"Number of channels in new image\", min=1),\n\n scripts.Int(\n \"Size_T\", grouping=\"4.6\",\n description=\"Number of time-points in new image\", min=1),\n\n scripts.List(\n \"Channel_Colours\", grouping=\"7\",\n description=\"List of Colors for channels.\", default=\"White\",\n values=c_options).ofType(rstring(\"\")),\n\n scripts.List(\n \"Channel_Names\", grouping=\"8\",\n description=\"List of Names for channels in the new image.\"),\n\n version=\"4.2.0\",\n authors=[\"William Moore\", \"OME Team\"],\n institutions=[\"University of Dundee\"],\n contact=\"[email protected]\",\n )\n\n try:\n parameter_map = client.getInputs(unwrap=True)\n\n conn = BlitzGateway(client_obj=client)\n\n # create the combined image\n images, message = combine_images(conn, parameter_map)\n\n client.setOutput(\"Message\", rstring(message))\n if images:\n if len(images) == 1:\n client.setOutput(\"Combined_Image\", robject(images[0]))\n elif len(images) > 1:\n client.setOutput(\"First_Image\", robject(images[0]))\n\n finally:\n client.closeSession()\n\n\nif __name__ == \"__main__\":\n run_script()\n" ]
[ [ "numpy.zeros" ] ]
yecharlie/keras-retinanet
[ "abcc99ecb75293b895b4e1be274ddc84e76f9c84" ]
[ "keras_retinanet/bin/evaluate.py" ]
[ "#!/usr/bin/env python\n\n\"\"\"\nCopyright 2017-2018 Fizyr (https://fizyr.com)\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport argparse\nimport os\nimport sys\nimport numpy as np\n\nimport yaml\nimport keras\nimport tensorflow as tf\n\n# Allow relative imports when being executed as script.\nif __name__ == \"__main__\" and __package__ is None:\n sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))\n import keras_retinanet.bin # noqa: F401\n __package__ = \"keras_retinanet.bin\"\n\n# Change these to absolute imports if you copy this script outside the keras_retinanet package.\nfrom keras_retinanet import models\nfrom keras_retinanet.preprocessing.csv_generator import CSVGenerator\nfrom keras_retinanet.preprocessing.pascal_voc import PascalVocGenerator\nfrom keras_retinanet.utils.eval import evaluate\nfrom keras_retinanet.utils.keras_version import check_keras_version\nfrom keras_retinanet.models.retinanet import AnchorParameters\n\n\ndef get_session():\n \"\"\" Construct a modified tf session.\n \"\"\"\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n return tf.Session(config=config)\n\n#def get_absolute_name(name,prefix):\n# return name if os.path.exists(name) else os.path.join(prefix,name)\n\ndef get_anchors_params(anchors_in=None):\n if anchors_in:\n anchors_in = open(anchors_in,'r')\n anchors_params = yaml.load(anchors_in)\n anchors_params.update(ratios=np.array(anchors_params['ratios'],keras.backend.floatx())) \n anchors_params.update(scales=np.array(anchors_params['scales'],keras.backend.floatx())) \n else:\n #just use the default params.\n anchors_params = {'sizes':AnchorParameters.default.sizes,\n 'ratios':AnchorParameters.default.ratios,\n 'scales':AnchorParameters.default.scales,\n 'strides':AnchorParameters.default.strides}\n \n return anchors_params\n\ndef create_generator(args):\n \"\"\" Create generators for evaluation.\n \"\"\"\n if args.dataset_type == 'coco':\n # import here to prevent unnecessary dependency on cocoapi\n from ..preprocessing.coco import CocoGenerator\n\n validation_generator = CocoGenerator(\n args.coco_path,\n 'val2017',\n image_min_side=args.image_min_side,\n image_max_side=args.image_max_side\n )\n elif args.dataset_type == 'pascal':\n validation_generator = PascalVocGenerator(\n args.pascal_path,\n 'test',\n image_min_side=args.image_min_side,\n image_max_side=args.image_max_side\n )\n elif args.dataset_type == 'csv':\n validation_generator = CSVGenerator(\n args.annotations,\n args.classes,\n image_min_side=args.image_min_side,\n image_max_side=args.image_max_side,\n )\n else:\n raise ValueError('Invalid data type received: {}'.format(args.dataset_type))\n\n return validation_generator\n\ndef parse_args(args):\n \"\"\" Parse the arguments.\n \"\"\"\n parser = argparse.ArgumentParser(description='Evaluation script for a RetinaNet network.')\n subparsers = parser.add_subparsers(help='Arguments for specific dataset types.', dest='dataset_type')\n subparsers.required = True\n\n coco_parser = subparsers.add_parser('coco')\n coco_parser.add_argument('coco_path', help='Path to dataset directory (ie. /tmp/COCO).')\n\n pascal_parser = subparsers.add_parser('pascal')\n pascal_parser.add_argument('pascal_path', help='Path to dataset directory (ie. /tmp/VOCdevkit).')\n\n csv_parser = subparsers.add_parser('csv')\n csv_parser.add_argument('annotations', help='Path to CSV file containing annotations for evaluation.')\n csv_parser.add_argument('classes', help='Path to a CSV file containing class label mapping.')\n\n parser.add_argument('model', help='Path to RetinaNet model.')\n\n parser.add_argument(\"--convert-model\", help='Convert the model to an inference model (ie. the input is a training model).', action='store_true')\n parser.add_argument('--backbone', help='The backbone of the model.', default='resnet50')\n parser.add_argument('--gpu', help='Id of the GPU to use (as reported by nvidia-smi).')\n parser.add_argument('--score-threshold', help='Threshold on score to filter detections with (defaults to 0.05).', default=0.05, type=float)\n parser.add_argument('--iou-threshold', help='IoU Threshold to count for a positive detection (defaults to 0.5).', default=0.5, type=float)\n parser.add_argument('--max-detections', help='Max Detections per image (defaults to 100).', default=100, type=int)\n parser.add_argument('--save-path', help='Path for saving images with detections (doesn\\'t work for COCO).')\n parser.add_argument('--image-min-side', help='Rescale the image so the smallest side is min_side.', type=int, default=800)\n parser.add_argument('--image-max-side', help='Rescale the image if the largest side is larger than max_side.', type=int, default=1333)\n parser.add_argument('--anchors', help='Load anchors parameters by a yaml file.',default=None)\n\n return parser.parse_args(args)\n\ndef main(args=None):\n # parse arguments\n if args is None:\n args = sys.argv[1:]\n args = parse_args(args)\n\n # make sure keras is the minimum required version\n check_keras_version()\n\n # optionally choose specific GPU\n if args.gpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n keras.backend.tensorflow_backend.set_session(get_session())\n\n # make save path if it doesn't exist\n if args.save_path is not None and not os.path.exists(args.save_path):\n os.makedirs(args.save_path)\n \n if not args.anchors:\n #automatically search the snapshot path for anchors configure\n #if it doesn't exist, then default anchors paramaters are assumed.\n anchors_path = os.path.join(os.path.dirname(args.model),\"anchors.yaml\")\n anchors_path = anchors_path if os.path.exists(anchors_path) else None\n else:\n anchors_path = args.anchors\n anchors_dict = get_anchors_params(anchors_path)\n anchors_params = AnchorParameters(**anchors_dict)\n\n # create the generator\n #(It's ok not to update anchors args, as we only use the generator for load images and annotations.)\n generator = create_generator(args)\n\n # load the model\n print('Loading model, this may take a second...')\n model = models.load_model(args.model, backbone_name=args.backbone, convert=args.convert_model,anchor_parameters = anchors_params)\n\n # print model summary\n # print(model.summary())\n\n # start evaluation\n if args.dataset_type == 'coco':\n from ..utils.coco_eval import evaluate_coco\n evaluate_coco(generator, model, args.score_threshold)\n else:\n average_precisions = evaluate(\n generator,\n model,\n iou_threshold=args.iou_threshold,\n score_threshold=args.score_threshold,\n max_detections=args.max_detections,\n save_path=args.save_path\n )\n\n # print evaluation\n present_classes = 0\n precision = 0\n for label, (average_precision, num_annotations) in average_precisions.items():\n print('{:.0f} instances of class'.format(num_annotations),\n generator.label_to_name(label), 'with average precision: {:.4f}'.format(average_precision))\n if num_annotations > 0:\n present_classes += 1\n precision += average_precision\n print('mAP: {:.4f}'.format(precision / present_classes))\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "tensorflow.ConfigProto", "tensorflow.Session" ] ]
ishatserka/MachineLearningAndDataAnalysisCoursera
[ "c54661f13857d5bcb0095ba2fb12f5a403a4a70f" ]
[ "venv/Lib/site-packages/pybrain2/rl/learners/valuebased/interface.py" ]
[ "__author__ = 'Thomas Rueckstiess, [email protected]'\n\nfrom pybrain.utilities import abstractMethod\nfrom pybrain.structure.modules import Table, Module, TanhLayer, LinearLayer, BiasUnit\nfrom pybrain.structure.connections import FullConnection\nfrom pybrain.structure.networks import FeedForwardNetwork\nfrom pybrain.structure.parametercontainer import ParameterContainer\nfrom pybrain.tools.shortcuts import buildNetwork\nfrom pybrain.utilities import one_to_n\n\nfrom scipy import argmax, array, r_, asarray, where\nfrom random import choice\n\n\nclass ActionValueInterface(object):\n \"\"\" Interface for different ActionValue modules, like the\n ActionValueTable or the ActionValueNetwork.\n \"\"\"\n\n numActions = None\n\n def getMaxAction(self, state):\n abstractMethod()\n\n def getActionValues(self, state):\n abstractMethod()\n\n\nclass ActionValueTable(Table, ActionValueInterface):\n \"\"\" A special table that is used for Value Estimation methods\n in Reinforcement Learning. This table is used for value-based\n TD algorithms like Q or SARSA.\n \"\"\"\n\n def __init__(self, numStates, numActions, name=None):\n Module.__init__(self, 1, 1, name)\n ParameterContainer.__init__(self, numStates * numActions)\n self.numRows = numStates\n self.numColumns = numActions\n\n @property\n def numActions(self):\n return self.numColumns\n\n def _forwardImplementation(self, inbuf, outbuf):\n \"\"\" Take a vector of length 1 (the state coordinate) and return\n the action with the maximum value over all actions for this state.\n \"\"\"\n outbuf[0] = self.getMaxAction(inbuf[0])\n\n def getMaxAction(self, state):\n \"\"\" Return the action with the maximal value for the given state. \"\"\"\n values = self.params.reshape(self.numRows, self.numColumns)[state, :].flatten()\n action = where(values == max(values))[0]\n action = choice(action)\n return action\n\n def getActionValues(self, state):\n return self.params.reshape(self.numRows, self.numColumns)[state, :].flatten()\n\n def initialize(self, value=0.0):\n \"\"\" Initialize the whole table with the given value. \"\"\"\n self._params[:] = value\n\n\nclass ActionValueNetwork(Module, ActionValueInterface):\n \"\"\" A network that approximates action values for continuous state /\n discrete action RL environments. To receive the maximum action\n for a given state, a forward pass is executed for all discrete\n actions, and the maximal action is returned. This network is used\n for the NFQ algorithm. \"\"\"\n\n def __init__(self, dimState, numActions, name=None):\n Module.__init__(self, dimState, 1, name)\n self.network = buildNetwork(dimState + numActions, dimState + numActions, 1)\n self.numActions = numActions\n\n def _forwardImplementation(self, inbuf, outbuf):\n \"\"\" takes the state vector and return the discrete action with\n the maximum value over all actions for this state.\n \"\"\"\n outbuf[0] = self.getMaxAction(asarray(inbuf))\n\n def getMaxAction(self, state):\n \"\"\" Return the action with the maximal value for the given state. \"\"\"\n return argmax(self.getActionValues(state))\n\n def getActionValues(self, state):\n \"\"\" Run forward activation for each of the actions and returns all values. \"\"\"\n values = array([self.network.activate(r_[state, one_to_n(i, self.numActions)]) for i in range(self.numActions)])\n return values\n\n def getValue(self, state, action):\n return self.network.activate(r_[state, one_to_n(action, self.numActions)])" ]
[ [ "scipy.asarray" ] ]
joshz123/tensorflow
[ "7841ca029060ab78e221e757d4b1ee6e3e0ffaa4", "7841ca029060ab78e221e757d4b1ee6e3e0ffaa4" ]
[ "tensorflow/python/keras/layers/serialization.py", "tensorflow/python/ops/linalg/linalg_impl.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\"\"\"Layer serialization/deserialization functions.\n\"\"\"\n# pylint: disable=wildcard-import\n# pylint: disable=unused-import\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport threading\n\nfrom tensorflow.python import tf2\nfrom tensorflow.python.keras.engine import base_layer\nfrom tensorflow.python.keras.engine import input_layer\nfrom tensorflow.python.keras.engine import input_spec\nfrom tensorflow.python.keras.layers import advanced_activations\nfrom tensorflow.python.keras.layers import convolutional\nfrom tensorflow.python.keras.layers import convolutional_recurrent\nfrom tensorflow.python.keras.layers import core\nfrom tensorflow.python.keras.layers import cudnn_recurrent\nfrom tensorflow.python.keras.layers import dense_attention\nfrom tensorflow.python.keras.layers import embeddings\nfrom tensorflow.python.keras.layers import local\nfrom tensorflow.python.keras.layers import merge\nfrom tensorflow.python.keras.layers import noise\nfrom tensorflow.python.keras.layers import normalization\nfrom tensorflow.python.keras.layers import normalization_v2\nfrom tensorflow.python.keras.layers import pooling\nfrom tensorflow.python.keras.layers import recurrent\nfrom tensorflow.python.keras.layers import recurrent_v2\nfrom tensorflow.python.keras.layers import rnn_cell_wrapper_v2\nfrom tensorflow.python.keras.layers import wrappers\nfrom tensorflow.python.keras.layers.preprocessing import image_preprocessing\nfrom tensorflow.python.keras.layers.preprocessing import normalization as preprocessing_normalization\nfrom tensorflow.python.keras.layers.preprocessing import normalization_v1 as preprocessing_normalization_v1\nfrom tensorflow.python.keras.utils import generic_utils\nfrom tensorflow.python.util import tf_inspect as inspect\nfrom tensorflow.python.util.tf_export import keras_export\n\n\nALL_MODULES = (\n base_layer,\n input_layer,\n advanced_activations,\n convolutional,\n convolutional_recurrent,\n core,\n cudnn_recurrent,\n dense_attention,\n embeddings,\n local,\n merge,\n noise,\n normalization,\n pooling,\n image_preprocessing,\n preprocessing_normalization_v1,\n recurrent,\n wrappers\n)\nALL_V2_MODULES = (\n rnn_cell_wrapper_v2,\n normalization_v2,\n recurrent_v2,\n preprocessing_normalization\n)\nFEATURE_COLUMN_V1_OBJECTS = {}\nFEATURE_COLUMN_V2_OBJECTS = {}\n# ALL_OBJECTS is meant to be a global mutable. Hence we need to make it\n# thread-local to avoid concurrent mutations.\nLOCAL = threading.local()\n\n\ndef inject_feature_column_v1_objects(name, cls):\n global FEATURE_COLUMN_V1_OBJECTS\n FEATURE_COLUMN_V1_OBJECTS[name] = cls\n\n\ndef inject_feature_column_v2_objects(name, cls):\n global FEATURE_COLUMN_V2_OBJECTS\n FEATURE_COLUMN_V2_OBJECTS[name] = cls\n\n\ndef populate_deserializable_objects():\n \"\"\"Populates dict ALL_OBJECTS with every built-in layer.\n \"\"\"\n global LOCAL\n if not hasattr(LOCAL, 'ALL_OBJECTS'):\n LOCAL.ALL_OBJECTS = {}\n LOCAL.GENERATED_WITH_V2 = None\n\n if LOCAL.ALL_OBJECTS and LOCAL.GENERATED_WITH_V2 == tf2.enabled():\n # Objects dict is already generated for the proper TF version:\n # do nothing.\n return\n\n LOCAL.ALL_OBJECTS = {}\n LOCAL.GENERATED_WITH_V2 = tf2.enabled()\n\n base_cls = base_layer.Layer\n generic_utils.populate_dict_with_module_objects(\n LOCAL.ALL_OBJECTS,\n ALL_MODULES,\n obj_filter=lambda x: inspect.isclass(x) and issubclass(x, base_cls))\n\n # Overwrite certain V1 objects with V2 versions\n if tf2.enabled():\n generic_utils.populate_dict_with_module_objects(\n LOCAL.ALL_OBJECTS,\n ALL_V2_MODULES,\n obj_filter=lambda x: inspect.isclass(x) and issubclass(x, base_cls))\n\n # These deserialization aliases are added for backward compatibility,\n # as in TF 1.13, \"BatchNormalizationV1\" and \"BatchNormalizationV2\"\n # were used as class name for v1 and v2 version of BatchNormalization,\n # respectively. Here we explicitly convert them to their canonical names.\n LOCAL.ALL_OBJECTS['BatchNormalizationV1'] = normalization.BatchNormalization\n LOCAL.ALL_OBJECTS[\n 'BatchNormalizationV2'] = normalization_v2.BatchNormalization\n\n # Prevent circular dependencies.\n from tensorflow.python.keras import models # pylint: disable=g-import-not-at-top\n from tensorflow.python.keras.premade.linear import LinearModel # pylint: disable=g-import-not-at-top\n from tensorflow.python.keras.premade.wide_deep import WideDeepModel # pylint: disable=g-import-not-at-top\n\n LOCAL.ALL_OBJECTS['Input'] = input_layer.Input\n LOCAL.ALL_OBJECTS['InputSpec'] = input_spec.InputSpec\n LOCAL.ALL_OBJECTS['Network'] = models.Network\n LOCAL.ALL_OBJECTS['Model'] = models.Model\n LOCAL.ALL_OBJECTS['Sequential'] = models.Sequential\n LOCAL.ALL_OBJECTS['LinearModel'] = LinearModel\n LOCAL.ALL_OBJECTS['WideDeepModel'] = WideDeepModel\n\n if tf2.enabled():\n LOCAL.ALL_OBJECTS.update(FEATURE_COLUMN_V2_OBJECTS)\n else:\n LOCAL.ALL_OBJECTS.update(FEATURE_COLUMN_V1_OBJECTS)\n\n # Merge layers, function versions.\n LOCAL.ALL_OBJECTS['add'] = merge.add\n LOCAL.ALL_OBJECTS['subtract'] = merge.subtract\n LOCAL.ALL_OBJECTS['multiply'] = merge.multiply\n LOCAL.ALL_OBJECTS['average'] = merge.average\n LOCAL.ALL_OBJECTS['maximum'] = merge.maximum\n LOCAL.ALL_OBJECTS['minimum'] = merge.minimum\n LOCAL.ALL_OBJECTS['concatenate'] = merge.concatenate\n LOCAL.ALL_OBJECTS['dot'] = merge.dot\n\n\n@keras_export('keras.layers.serialize')\ndef serialize(layer):\n return generic_utils.serialize_keras_object(layer)\n\n\n@keras_export('keras.layers.deserialize')\ndef deserialize(config, custom_objects=None):\n \"\"\"Instantiates a layer from a config dictionary.\n\n Arguments:\n config: dict of the form {'class_name': str, 'config': dict}\n custom_objects: dict mapping class names (or function names)\n of custom (non-Keras) objects to class/functions\n\n Returns:\n Layer instance (may be Model, Sequential, Network, Layer...)\n \"\"\"\n populate_deserializable_objects()\n return generic_utils.deserialize_keras_object(\n config,\n module_objects=LOCAL.ALL_OBJECTS,\n custom_objects=custom_objects,\n printable_module_name='layer')\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Operations for linear algebra.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import check_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gen_linalg_ops\nfrom tensorflow.python.ops import linalg_ops\nfrom tensorflow.python.ops import map_fn\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import special_math_ops\nfrom tensorflow.python.util import dispatch\nfrom tensorflow.python.util.tf_export import tf_export\n\n# Linear algebra ops.\nband_part = array_ops.matrix_band_part\ncholesky = linalg_ops.cholesky\ncholesky_solve = linalg_ops.cholesky_solve\ndet = linalg_ops.matrix_determinant\nslogdet = gen_linalg_ops.log_matrix_determinant\ntf_export('linalg.slogdet')(slogdet)\ndiag = array_ops.matrix_diag\ndiag_part = array_ops.matrix_diag_part\neigh = linalg_ops.self_adjoint_eig\neigvalsh = linalg_ops.self_adjoint_eigvals\neinsum = special_math_ops.einsum\neye = linalg_ops.eye\ninv = linalg_ops.matrix_inverse\nlogm = gen_linalg_ops.matrix_logarithm\nlu = gen_linalg_ops.lu\ntf_export('linalg.logm')(logm)\nlstsq = linalg_ops.matrix_solve_ls\nnorm = linalg_ops.norm\nqr = linalg_ops.qr\nset_diag = array_ops.matrix_set_diag\nsolve = linalg_ops.matrix_solve\nsqrtm = linalg_ops.matrix_square_root\nsvd = linalg_ops.svd\ntensordot = math_ops.tensordot\ntrace = math_ops.trace\ntranspose = array_ops.matrix_transpose\ntriangular_solve = linalg_ops.matrix_triangular_solve\n\n\n@tf_export('linalg.logdet')\[email protected]_dispatch_support\ndef logdet(matrix, name=None):\n \"\"\"Computes log of the determinant of a hermitian positive definite matrix.\n\n ```python\n # Compute the determinant of a matrix while reducing the chance of over- or\n underflow:\n A = ... # shape 10 x 10\n det = tf.exp(tf.linalg.logdet(A)) # scalar\n ```\n\n Args:\n matrix: A `Tensor`. Must be `float16`, `float32`, `float64`, `complex64`,\n or `complex128` with shape `[..., M, M]`.\n name: A name to give this `Op`. Defaults to `logdet`.\n\n Returns:\n The natural log of the determinant of `matrix`.\n\n @compatibility(numpy)\n Equivalent to numpy.linalg.slogdet, although no sign is returned since only\n hermitian positive definite matrices are supported.\n @end_compatibility\n \"\"\"\n # This uses the property that the log det(A) = 2*sum(log(real(diag(C))))\n # where C is the cholesky decomposition of A.\n with ops.name_scope(name, 'logdet', [matrix]):\n chol = gen_linalg_ops.cholesky(matrix)\n return 2.0 * math_ops.reduce_sum(\n math_ops.log(math_ops.real(array_ops.matrix_diag_part(chol))),\n axis=[-1])\n\n\n@tf_export('linalg.adjoint')\[email protected]_dispatch_support\ndef adjoint(matrix, name=None):\n \"\"\"Transposes the last two dimensions of and conjugates tensor `matrix`.\n\n For example:\n\n ```python\n x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j],\n [4 + 4j, 5 + 5j, 6 + 6j]])\n tf.linalg.adjoint(x) # [[1 - 1j, 4 - 4j],\n # [2 - 2j, 5 - 5j],\n # [3 - 3j, 6 - 6j]]\n ```\n\n Args:\n matrix: A `Tensor`. Must be `float16`, `float32`, `float64`, `complex64`,\n or `complex128` with shape `[..., M, M]`.\n name: A name to give this `Op` (optional).\n\n Returns:\n The adjoint (a.k.a. Hermitian transpose a.k.a. conjugate transpose) of\n matrix.\n \"\"\"\n with ops.name_scope(name, 'adjoint', [matrix]):\n matrix = ops.convert_to_tensor(matrix, name='matrix')\n return array_ops.matrix_transpose(matrix, conjugate=True)\n\n\n# This section is ported nearly verbatim from Eigen's implementation:\n# https://eigen.tuxfamily.org/dox/unsupported/MatrixExponential_8h_source.html\ndef _matrix_exp_pade3(matrix):\n \"\"\"3rd-order Pade approximant for matrix exponential.\"\"\"\n b = [120.0, 60.0, 12.0]\n b = [constant_op.constant(x, matrix.dtype) for x in b]\n ident = linalg_ops.eye(\n array_ops.shape(matrix)[-2],\n batch_shape=array_ops.shape(matrix)[:-2],\n dtype=matrix.dtype)\n matrix_2 = math_ops.matmul(matrix, matrix)\n tmp = matrix_2 + b[1] * ident\n matrix_u = math_ops.matmul(matrix, tmp)\n matrix_v = b[2] * matrix_2 + b[0] * ident\n return matrix_u, matrix_v\n\n\ndef _matrix_exp_pade5(matrix):\n \"\"\"5th-order Pade approximant for matrix exponential.\"\"\"\n b = [30240.0, 15120.0, 3360.0, 420.0, 30.0]\n b = [constant_op.constant(x, matrix.dtype) for x in b]\n ident = linalg_ops.eye(\n array_ops.shape(matrix)[-2],\n batch_shape=array_ops.shape(matrix)[:-2],\n dtype=matrix.dtype)\n matrix_2 = math_ops.matmul(matrix, matrix)\n matrix_4 = math_ops.matmul(matrix_2, matrix_2)\n tmp = matrix_4 + b[3] * matrix_2 + b[1] * ident\n matrix_u = math_ops.matmul(matrix, tmp)\n matrix_v = b[4] * matrix_4 + b[2] * matrix_2 + b[0] * ident\n return matrix_u, matrix_v\n\n\ndef _matrix_exp_pade7(matrix):\n \"\"\"7th-order Pade approximant for matrix exponential.\"\"\"\n b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0, 56.0]\n b = [constant_op.constant(x, matrix.dtype) for x in b]\n ident = linalg_ops.eye(\n array_ops.shape(matrix)[-2],\n batch_shape=array_ops.shape(matrix)[:-2],\n dtype=matrix.dtype)\n matrix_2 = math_ops.matmul(matrix, matrix)\n matrix_4 = math_ops.matmul(matrix_2, matrix_2)\n matrix_6 = math_ops.matmul(matrix_4, matrix_2)\n tmp = matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 + b[1] * ident\n matrix_u = math_ops.matmul(matrix, tmp)\n matrix_v = b[6] * matrix_6 + b[4] * matrix_4 + b[2] * matrix_2 + b[0] * ident\n return matrix_u, matrix_v\n\n\ndef _matrix_exp_pade9(matrix):\n \"\"\"9th-order Pade approximant for matrix exponential.\"\"\"\n b = [\n 17643225600.0, 8821612800.0, 2075673600.0, 302702400.0, 30270240.0,\n 2162160.0, 110880.0, 3960.0, 90.0\n ]\n b = [constant_op.constant(x, matrix.dtype) for x in b]\n ident = linalg_ops.eye(\n array_ops.shape(matrix)[-2],\n batch_shape=array_ops.shape(matrix)[:-2],\n dtype=matrix.dtype)\n matrix_2 = math_ops.matmul(matrix, matrix)\n matrix_4 = math_ops.matmul(matrix_2, matrix_2)\n matrix_6 = math_ops.matmul(matrix_4, matrix_2)\n matrix_8 = math_ops.matmul(matrix_6, matrix_2)\n tmp = (\n matrix_8 + b[7] * matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 +\n b[1] * ident)\n matrix_u = math_ops.matmul(matrix, tmp)\n matrix_v = (\n b[8] * matrix_8 + b[6] * matrix_6 + b[4] * matrix_4 + b[2] * matrix_2 +\n b[0] * ident)\n return matrix_u, matrix_v\n\n\ndef _matrix_exp_pade13(matrix):\n \"\"\"13th-order Pade approximant for matrix exponential.\"\"\"\n b = [\n 64764752532480000.0, 32382376266240000.0, 7771770303897600.0,\n 1187353796428800.0, 129060195264000.0, 10559470521600.0, 670442572800.0,\n 33522128640.0, 1323241920.0, 40840800.0, 960960.0, 16380.0, 182.0\n ]\n b = [constant_op.constant(x, matrix.dtype) for x in b]\n ident = linalg_ops.eye(\n array_ops.shape(matrix)[-2],\n batch_shape=array_ops.shape(matrix)[:-2],\n dtype=matrix.dtype)\n matrix_2 = math_ops.matmul(matrix, matrix)\n matrix_4 = math_ops.matmul(matrix_2, matrix_2)\n matrix_6 = math_ops.matmul(matrix_4, matrix_2)\n tmp_u = (\n math_ops.matmul(matrix_6, matrix_6 + b[11] * matrix_4 + b[9] * matrix_2) +\n b[7] * matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 + b[1] * ident)\n matrix_u = math_ops.matmul(matrix, tmp_u)\n tmp_v = b[12] * matrix_6 + b[10] * matrix_4 + b[8] * matrix_2\n matrix_v = (\n math_ops.matmul(matrix_6, tmp_v) + b[6] * matrix_6 + b[4] * matrix_4 +\n b[2] * matrix_2 + b[0] * ident)\n return matrix_u, matrix_v\n\n\n@tf_export('linalg.expm')\ndef matrix_exponential(input, name=None): # pylint: disable=redefined-builtin\n r\"\"\"Computes the matrix exponential of one or more square matrices.\n\n exp(A) = \\sum_{n=0}^\\infty A^n/n!\n\n The exponential is computed using a combination of the scaling and squaring\n method and the Pade approximation. Details can be found in:\n Nicholas J. Higham, \"The scaling and squaring method for the matrix\n exponential revisited,\" SIAM J. Matrix Anal. Applic., 26:1179-1193, 2005.\n\n The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions\n form square matrices. The output is a tensor of the same shape as the input\n containing the exponential for all input submatrices `[..., :, :]`.\n\n Args:\n input: A `Tensor`. Must be `float16`, `float32`, `float64`, `complex64`, or\n `complex128` with shape `[..., M, M]`.\n name: A name to give this `Op` (optional).\n\n Returns:\n the matrix exponential of the input.\n\n Raises:\n ValueError: An unsupported type is provided as input.\n\n @compatibility(scipy)\n Equivalent to scipy.linalg.expm\n @end_compatibility\n \"\"\"\n with ops.name_scope(name, 'matrix_exponential', [input]):\n matrix = ops.convert_to_tensor(input, name='input')\n if matrix.shape[-2:] == [0, 0]:\n return matrix\n batch_shape = matrix.shape[:-2]\n if not batch_shape.is_fully_defined():\n batch_shape = array_ops.shape(matrix)[:-2]\n\n # reshaping the batch makes the where statements work better\n matrix = array_ops.reshape(\n matrix, array_ops.concat(([-1], array_ops.shape(matrix)[-2:]), axis=0))\n l1_norm = math_ops.reduce_max(\n math_ops.reduce_sum(\n math_ops.abs(matrix),\n axis=array_ops.size(array_ops.shape(matrix)) - 2),\n axis=-1)[..., array_ops.newaxis, array_ops.newaxis]\n const = lambda x: constant_op.constant(x, l1_norm.dtype)\n\n def _nest_where(vals, cases):\n assert len(vals) == len(cases) - 1\n if len(vals) == 1:\n return array_ops.where_v2(\n math_ops.less(l1_norm, const(vals[0])), cases[0], cases[1])\n else:\n return array_ops.where_v2(\n math_ops.less(l1_norm, const(vals[0])), cases[0],\n _nest_where(vals[1:], cases[1:]))\n\n if matrix.dtype in [dtypes.float16, dtypes.float32, dtypes.complex64]:\n maxnorm = const(3.925724783138660)\n squarings = math_ops.maximum(\n math_ops.floor(\n math_ops.log(l1_norm / maxnorm) / math_ops.log(const(2.0))), 0)\n u3, v3 = _matrix_exp_pade3(matrix)\n u5, v5 = _matrix_exp_pade5(matrix)\n u7, v7 = _matrix_exp_pade7(\n matrix /\n math_ops.cast(math_ops.pow(const(2.0), squarings), matrix.dtype))\n conds = (4.258730016922831e-001, 1.880152677804762e+000)\n u = _nest_where(conds, (u3, u5, u7))\n v = _nest_where(conds, (v3, v5, v7))\n elif matrix.dtype in [dtypes.float64, dtypes.complex128]:\n maxnorm = const(5.371920351148152)\n squarings = math_ops.maximum(\n math_ops.floor(\n math_ops.log(l1_norm / maxnorm) / math_ops.log(const(2.0))), 0)\n u3, v3 = _matrix_exp_pade3(matrix)\n u5, v5 = _matrix_exp_pade5(matrix)\n u7, v7 = _matrix_exp_pade7(matrix)\n u9, v9 = _matrix_exp_pade9(matrix)\n u13, v13 = _matrix_exp_pade13(\n matrix /\n math_ops.cast(math_ops.pow(const(2.0), squarings), matrix.dtype))\n conds = (1.495585217958292e-002, 2.539398330063230e-001,\n 9.504178996162932e-001, 2.097847961257068e+000)\n u = _nest_where(conds, (u3, u5, u7, u9, u13))\n v = _nest_where(conds, (v3, v5, v7, v9, v13))\n else:\n raise ValueError('tf.linalg.expm does not support matrices of type %s' %\n matrix.dtype)\n numer = u + v\n denom = -u + v\n result = linalg_ops.matrix_solve(denom, numer)\n max_squarings = math_ops.reduce_max(squarings)\n\n i = const(0.0)\n c = lambda i, r: math_ops.less(i, max_squarings)\n\n def b(i, r):\n return i + 1, array_ops.where_v2(\n math_ops.less(i, squarings), math_ops.matmul(r, r), r)\n\n _, result = control_flow_ops.while_loop(c, b, [i, result])\n if not matrix.shape.is_fully_defined():\n return array_ops.reshape(\n result,\n array_ops.concat((batch_shape, array_ops.shape(result)[-2:]), axis=0))\n return array_ops.reshape(result, batch_shape.concatenate(result.shape[-2:]))\n\n\n@tf_export('linalg.tridiagonal_solve')\ndef tridiagonal_solve(diagonals,\n rhs,\n diagonals_format='compact',\n transpose_rhs=False,\n conjugate_rhs=False,\n name=None,\n partial_pivoting=True):\n r\"\"\"Solves tridiagonal systems of equations.\n\n The input can be supplied in various formats: `matrix`, `sequence` and\n `compact`, specified by the `diagonals_format` arg.\n\n In `matrix` format, `diagonals` must be a tensor of shape `[..., M, M]`, with\n two inner-most dimensions representing the square tridiagonal matrices.\n Elements outside of the three diagonals will be ignored.\n\n In `sequence` format, `diagonals` are supplied as a tuple or list of three\n tensors of shapes `[..., N]`, `[..., M]`, `[..., N]` representing\n superdiagonals, diagonals, and subdiagonals, respectively. `N` can be either\n `M-1` or `M`; in the latter case, the last element of superdiagonal and the\n first element of subdiagonal will be ignored.\n\n In `compact` format the three diagonals are brought together into one tensor\n of shape `[..., 3, M]`, with last two dimensions containing superdiagonals,\n diagonals, and subdiagonals, in order. Similarly to `sequence` format,\n elements `diagonals[..., 0, M-1]` and `diagonals[..., 2, 0]` are ignored.\n\n The `compact` format is recommended as the one with best performance. In case\n you need to cast a tensor into a compact format manually, use `tf.gather_nd`.\n An example for a tensor of shape [m, m]:\n\n ```python\n rhs = tf.constant([...])\n matrix = tf.constant([[...]])\n m = matrix.shape[0]\n dummy_idx = [0, 0] # An arbitrary element to use as a dummy\n indices = [[[i, i + 1] for i in range(m - 1)] + [dummy_idx], # Superdiagonal\n [[i, i] for i in range(m)], # Diagonal\n [dummy_idx] + [[i + 1, i] for i in range(m - 1)]] # Subdiagonal\n diagonals=tf.gather_nd(matrix, indices)\n x = tf.linalg.tridiagonal_solve(diagonals, rhs)\n ```\n\n Regardless of the `diagonals_format`, `rhs` is a tensor of shape `[..., M]` or\n `[..., M, K]`. The latter allows to simultaneously solve K systems with the\n same left-hand sides and K different right-hand sides. If `transpose_rhs`\n is set to `True` the expected shape is `[..., M]` or `[..., K, M]`.\n\n The batch dimensions, denoted as `...`, must be the same in `diagonals` and\n `rhs`.\n\n The output is a tensor of the same shape as `rhs`: either `[..., M]` or\n `[..., M, K]`.\n\n The op isn't guaranteed to raise an error if the input matrix is not\n invertible. `tf.debugging.check_numerics` can be applied to the output to\n detect invertibility problems.\n\n **Note**: with large batch sizes, the computation on the GPU may be slow, if\n either `partial_pivoting=True` or there are multiple right-hand sides\n (`K > 1`). If this issue arises, consider if it's possible to disable pivoting\n and have `K = 1`, or, alternatively, consider using CPU.\n\n On CPU, solution is computed via Gaussian elimination with or without partial\n pivoting, depending on `partial_pivoting` parameter. On GPU, Nvidia's cuSPARSE\n library is used: https://docs.nvidia.com/cuda/cusparse/index.html#gtsv\n\n Args:\n diagonals: A `Tensor` or tuple of `Tensor`s describing left-hand sides. The\n shape depends of `diagonals_format`, see description above. Must be\n `float32`, `float64`, `complex64`, or `complex128`.\n rhs: A `Tensor` of shape [..., M] or [..., M, K] and with the same dtype as\n `diagonals`. Note that if the shape of `rhs` and/or `diags` isn't known\n statically, `rhs` will be treated as a matrix rather than a vector.\n diagonals_format: one of `matrix`, `sequence`, or `compact`. Default is\n `compact`.\n transpose_rhs: If `True`, `rhs` is transposed before solving (has no effect\n if the shape of rhs is [..., M]).\n conjugate_rhs: If `True`, `rhs` is conjugated before solving.\n name: A name to give this `Op` (optional).\n partial_pivoting: whether to perform partial pivoting. `True` by default.\n Partial pivoting makes the procedure more stable, but slower. Partial\n pivoting is unnecessary in some cases, including diagonally dominant and\n symmetric positive definite matrices (see e.g. theorem 9.12 in [1]).\n\n Returns:\n A `Tensor` of shape [..., M] or [..., M, K] containing the solutions.\n\n Raises:\n ValueError: An unsupported type is provided as input, or when the input\n tensors have incorrect shapes.\n UnimplementedError: Whenever `partial_pivoting` is true and the backend is\n XLA.\n\n [1] Nicholas J. Higham (2002). Accuracy and Stability of Numerical Algorithms:\n Second Edition. SIAM. p. 175. ISBN 978-0-89871-802-7.\n\n \"\"\"\n if diagonals_format == 'compact':\n return _tridiagonal_solve_compact_format(diagonals, rhs, transpose_rhs,\n conjugate_rhs, partial_pivoting,\n name)\n\n if diagonals_format == 'sequence':\n if not isinstance(diagonals, (tuple, list)) or len(diagonals) != 3:\n raise ValueError('Expected diagonals to be a sequence of length 3.')\n\n superdiag, maindiag, subdiag = diagonals\n if (not subdiag.shape[:-1].is_compatible_with(maindiag.shape[:-1]) or\n not superdiag.shape[:-1].is_compatible_with(maindiag.shape[:-1])):\n raise ValueError(\n 'Tensors representing the three diagonals must have the same shape,'\n 'except for the last dimension, got {}, {}, {}'.format(\n subdiag.shape, maindiag.shape, superdiag.shape))\n\n m = tensor_shape.dimension_value(maindiag.shape[-1])\n\n def pad_if_necessary(t, name, last_dim_padding):\n n = tensor_shape.dimension_value(t.shape[-1])\n if not n or n == m:\n return t\n if n == m - 1:\n paddings = ([[0, 0] for _ in range(len(t.shape) - 1)] +\n [last_dim_padding])\n return array_ops.pad(t, paddings)\n raise ValueError('Expected {} to be have length {} or {}, got {}.'.format(\n name, m, m - 1, n))\n\n subdiag = pad_if_necessary(subdiag, 'subdiagonal', [1, 0])\n superdiag = pad_if_necessary(superdiag, 'superdiagonal', [0, 1])\n\n diagonals = array_ops.stack((superdiag, maindiag, subdiag), axis=-2)\n return _tridiagonal_solve_compact_format(diagonals, rhs, transpose_rhs,\n conjugate_rhs, partial_pivoting,\n name)\n\n if diagonals_format == 'matrix':\n m1 = tensor_shape.dimension_value(diagonals.shape[-1])\n m2 = tensor_shape.dimension_value(diagonals.shape[-2])\n if m1 and m2 and m1 != m2:\n raise ValueError(\n 'Expected last two dimensions of diagonals to be same, got {} and {}'\n .format(m1, m2))\n m = m1 or m2\n diagonals = array_ops.matrix_diag_part(\n diagonals, k=(-1, 1), padding_value=0., align='LEFT_RIGHT')\n return _tridiagonal_solve_compact_format(\n diagonals, rhs, transpose_rhs, conjugate_rhs, partial_pivoting, name)\n\n raise ValueError('Unrecognized diagonals_format: {}'.format(diagonals_format))\n\n\ndef _tridiagonal_solve_compact_format(diagonals, rhs, transpose_rhs,\n conjugate_rhs, partial_pivoting, name):\n \"\"\"Helper function used after the input has been cast to compact form.\"\"\"\n diags_rank, rhs_rank = diagonals.shape.rank, rhs.shape.rank\n\n # If we know the rank of the diagonal tensor, do some static checking.\n if diags_rank:\n if diags_rank < 2:\n raise ValueError(\n 'Expected diagonals to have rank at least 2, got {}'.format(\n diags_rank))\n if rhs_rank and rhs_rank != diags_rank and rhs_rank != diags_rank - 1:\n raise ValueError('Expected the rank of rhs to be {} or {}, got {}'.format(\n diags_rank - 1, diags_rank, rhs_rank))\n if (rhs_rank and not diagonals.shape[:-2].is_compatible_with(\n rhs.shape[:diags_rank - 2])):\n raise ValueError('Batch shapes {} and {} are incompatible'.format(\n diagonals.shape[:-2], rhs.shape[:diags_rank - 2]))\n\n if diagonals.shape[-2] and diagonals.shape[-2] != 3:\n raise ValueError('Expected 3 diagonals got {}'.format(diagonals.shape[-2]))\n\n def check_num_lhs_matches_num_rhs():\n if (diagonals.shape[-1] and rhs.shape[-2] and\n diagonals.shape[-1] != rhs.shape[-2]):\n raise ValueError('Expected number of left-hand sided and right-hand '\n 'sides to be equal, got {} and {}'.format(\n diagonals.shape[-1], rhs.shape[-2]))\n\n if rhs_rank and diags_rank and rhs_rank == diags_rank - 1:\n # Rhs provided as a vector, ignoring transpose_rhs\n if conjugate_rhs:\n rhs = math_ops.conj(rhs)\n rhs = array_ops.expand_dims(rhs, -1)\n check_num_lhs_matches_num_rhs()\n return array_ops.squeeze(\n linalg_ops.tridiagonal_solve(diagonals, rhs, partial_pivoting, name),\n -1)\n\n if transpose_rhs:\n rhs = array_ops.matrix_transpose(rhs, conjugate=conjugate_rhs)\n elif conjugate_rhs:\n rhs = math_ops.conj(rhs)\n\n check_num_lhs_matches_num_rhs()\n return linalg_ops.tridiagonal_solve(diagonals, rhs, partial_pivoting, name)\n\n\n@tf_export('linalg.tridiagonal_matmul')\ndef tridiagonal_matmul(diagonals, rhs, diagonals_format='compact', name=None):\n r\"\"\"Multiplies tridiagonal matrix by matrix.\n\n `diagonals` is representation of 3-diagonal NxN matrix, which depends on\n `diagonals_format`.\n\n In `matrix` format, `diagonals` must be a tensor of shape `[..., M, M]`, with\n two inner-most dimensions representing the square tridiagonal matrices.\n Elements outside of the three diagonals will be ignored.\n\n If `sequence` format, `diagonals` is list or tuple of three tensors:\n `[superdiag, maindiag, subdiag]`, each having shape [..., M]. Last element\n of `superdiag` first element of `subdiag` are ignored.\n\n In `compact` format the three diagonals are brought together into one tensor\n of shape `[..., 3, M]`, with last two dimensions containing superdiagonals,\n diagonals, and subdiagonals, in order. Similarly to `sequence` format,\n elements `diagonals[..., 0, M-1]` and `diagonals[..., 2, 0]` are ignored.\n\n The `sequence` format is recommended as the one with the best performance.\n\n `rhs` is matrix to the right of multiplication. It has shape `[..., M, N]`.\n\n Example:\n\n ```python\n superdiag = tf.constant([-1, -1, 0], dtype=tf.float64)\n maindiag = tf.constant([2, 2, 2], dtype=tf.float64)\n subdiag = tf.constant([0, -1, -1], dtype=tf.float64)\n diagonals = [superdiag, maindiag, subdiag]\n rhs = tf.constant([[1, 1], [1, 1], [1, 1]], dtype=tf.float64)\n x = tf.linalg.tridiagonal_matmul(diagonals, rhs, diagonals_format='sequence')\n ```\n\n Args:\n diagonals: A `Tensor` or tuple of `Tensor`s describing left-hand sides. The\n shape depends of `diagonals_format`, see description above. Must be\n `float32`, `float64`, `complex64`, or `complex128`.\n rhs: A `Tensor` of shape [..., M, N] and with the same dtype as `diagonals`.\n diagonals_format: one of `sequence`, or `compact`. Default is `compact`.\n name: A name to give this `Op` (optional).\n\n Returns:\n A `Tensor` of shape [..., M, N] containing the result of multiplication.\n\n Raises:\n ValueError: An unsupported type is provided as input, or when the input\n tensors have incorrect shapes.\n \"\"\"\n if diagonals_format == 'compact':\n superdiag = diagonals[..., 0, :]\n maindiag = diagonals[..., 1, :]\n subdiag = diagonals[..., 2, :]\n elif diagonals_format == 'sequence':\n superdiag, maindiag, subdiag = diagonals\n elif diagonals_format == 'matrix':\n m1 = tensor_shape.dimension_value(diagonals.shape[-1])\n m2 = tensor_shape.dimension_value(diagonals.shape[-2])\n if m1 and m2 and m1 != m2:\n raise ValueError(\n 'Expected last two dimensions of diagonals to be same, got {} and {}'\n .format(m1, m2))\n diags = array_ops.matrix_diag_part(\n diagonals, k=(-1, 1), padding_value=0., align='LEFT_RIGHT')\n superdiag = diags[..., 0, :]\n maindiag = diags[..., 1, :]\n subdiag = diags[..., 2, :]\n else:\n raise ValueError('Unrecognized diagonals_format: %s' % diagonals_format)\n\n # C++ backend requires matrices.\n # Converting 1-dimensional vectors to matrices with 1 row.\n superdiag = array_ops.expand_dims(superdiag, -2)\n maindiag = array_ops.expand_dims(maindiag, -2)\n subdiag = array_ops.expand_dims(subdiag, -2)\n\n return linalg_ops.tridiagonal_mat_mul(superdiag, maindiag, subdiag, rhs, name)\n\n\ndef _maybe_validate_matrix(a, validate_args):\n \"\"\"Checks that input is a `float` matrix.\"\"\"\n assertions = []\n if not a.dtype.is_floating:\n raise TypeError('Input `a` must have `float`-like `dtype` '\n '(saw {}).'.format(a.dtype.name))\n if a.shape is not None and a.shape.rank is not None:\n if a.shape.rank < 2:\n raise ValueError('Input `a` must have at least 2 dimensions '\n '(saw: {}).'.format(a.shape.rank))\n elif validate_args:\n assertions.append(\n check_ops.assert_rank_at_least(\n a, rank=2, message='Input `a` must have at least 2 dimensions.'))\n return assertions\n\n\n@tf_export('linalg.matrix_rank')\ndef matrix_rank(a, tol=None, validate_args=False, name=None):\n \"\"\"Compute the matrix rank of one or more matrices.\n\n Arguments:\n a: (Batch of) `float`-like matrix-shaped `Tensor`(s) which are to be\n pseudo-inverted.\n tol: Threshold below which the singular value is counted as 'zero'.\n Default value: `None` (i.e., `eps * max(rows, cols) * max(singular_val)`).\n validate_args: When `True`, additional assertions might be embedded in the\n graph.\n Default value: `False` (i.e., no graph assertions are added).\n name: Python `str` prefixed to ops created by this function.\n Default value: 'matrix_rank'.\n\n Returns:\n matrix_rank: (Batch of) `int32` scalars representing the number of non-zero\n singular values.\n \"\"\"\n with ops.name_scope(name or 'matrix_rank'):\n a = ops.convert_to_tensor(a, dtype_hint=dtypes.float32, name='a')\n assertions = _maybe_validate_matrix(a, validate_args)\n if assertions:\n with ops.control_dependencies(assertions):\n a = array_ops.identity(a)\n s = svd(a, compute_uv=False)\n if tol is None:\n if (a.shape[-2:]).is_fully_defined():\n m = np.max(a.shape[-2:].as_list())\n else:\n m = math_ops.reduce_max(array_ops.shape(a)[-2:])\n eps = np.finfo(a.dtype.as_numpy_dtype).eps\n tol = (\n eps * math_ops.cast(m, a.dtype) *\n math_ops.reduce_max(s, axis=-1, keepdims=True))\n return math_ops.reduce_sum(math_ops.cast(s > tol, dtypes.int32), axis=-1)\n\n\n@tf_export('linalg.pinv')\ndef pinv(a, rcond=None, validate_args=False, name=None):\n \"\"\"Compute the Moore-Penrose pseudo-inverse of one or more matrices.\n\n Calculate the [generalized inverse of a matrix](\n https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse) using its\n singular-value decomposition (SVD) and including all large singular values.\n\n The pseudo-inverse of a matrix `A`, is defined as: 'the matrix that 'solves'\n [the least-squares problem] `A @ x = b`,' i.e., if `x_hat` is a solution, then\n `A_pinv` is the matrix such that `x_hat = A_pinv @ b`. It can be shown that if\n `U @ Sigma @ V.T = A` is the singular value decomposition of `A`, then\n `A_pinv = V @ inv(Sigma) U^T`. [(Strang, 1980)][1]\n\n This function is analogous to [`numpy.linalg.pinv`](\n https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.pinv.html).\n It differs only in default value of `rcond`. In `numpy.linalg.pinv`, the\n default `rcond` is `1e-15`. Here the default is\n `10. * max(num_rows, num_cols) * np.finfo(dtype).eps`.\n\n Args:\n a: (Batch of) `float`-like matrix-shaped `Tensor`(s) which are to be\n pseudo-inverted.\n rcond: `Tensor` of small singular value cutoffs. Singular values smaller\n (in modulus) than `rcond` * largest_singular_value (again, in modulus) are\n set to zero. Must broadcast against `tf.shape(a)[:-2]`.\n Default value: `10. * max(num_rows, num_cols) * np.finfo(a.dtype).eps`.\n validate_args: When `True`, additional assertions might be embedded in the\n graph.\n Default value: `False` (i.e., no graph assertions are added).\n name: Python `str` prefixed to ops created by this function.\n Default value: 'pinv'.\n\n Returns:\n a_pinv: (Batch of) pseudo-inverse of input `a`. Has same shape as `a` except\n rightmost two dimensions are transposed.\n\n Raises:\n TypeError: if input `a` does not have `float`-like `dtype`.\n ValueError: if input `a` has fewer than 2 dimensions.\n\n #### Examples\n\n ```python\n import tensorflow as tf\n import tensorflow_probability as tfp\n\n a = tf.constant([[1., 0.4, 0.5],\n [0.4, 0.2, 0.25],\n [0.5, 0.25, 0.35]])\n tf.matmul(tf.linalg..pinv(a), a)\n # ==> array([[1., 0., 0.],\n [0., 1., 0.],\n [0., 0., 1.]], dtype=float32)\n\n a = tf.constant([[1., 0.4, 0.5, 1.],\n [0.4, 0.2, 0.25, 2.],\n [0.5, 0.25, 0.35, 3.]])\n tf.matmul(tf.linalg..pinv(a), a)\n # ==> array([[ 0.76, 0.37, 0.21, -0.02],\n [ 0.37, 0.43, -0.33, 0.02],\n [ 0.21, -0.33, 0.81, 0.01],\n [-0.02, 0.02, 0.01, 1. ]], dtype=float32)\n ```\n\n #### References\n\n [1]: G. Strang. 'Linear Algebra and Its Applications, 2nd Ed.' Academic Press,\n Inc., 1980, pp. 139-142.\n \"\"\"\n with ops.name_scope(name or 'pinv'):\n a = ops.convert_to_tensor(a, name='a')\n\n assertions = _maybe_validate_matrix(a, validate_args)\n if assertions:\n with ops.control_dependencies(assertions):\n a = array_ops.identity(a)\n\n dtype = a.dtype.as_numpy_dtype\n\n if rcond is None:\n\n def get_dim_size(dim):\n dim_val = tensor_shape.dimension_value(a.shape[dim])\n if dim_val is not None:\n return dim_val\n return array_ops.shape(a)[dim]\n\n num_rows = get_dim_size(-2)\n num_cols = get_dim_size(-1)\n if isinstance(num_rows, int) and isinstance(num_cols, int):\n max_rows_cols = float(max(num_rows, num_cols))\n else:\n max_rows_cols = math_ops.cast(\n math_ops.maximum(num_rows, num_cols), dtype)\n rcond = 10. * max_rows_cols * np.finfo(dtype).eps\n\n rcond = ops.convert_to_tensor(rcond, dtype=dtype, name='rcond')\n\n # Calculate pseudo inverse via SVD.\n # Note: if a is Hermitian then u == v. (We might observe additional\n # performance by explicitly setting `v = u` in such cases.)\n [\n singular_values, # Sigma\n left_singular_vectors, # U\n right_singular_vectors, # V\n ] = svd(\n a, full_matrices=False, compute_uv=True)\n\n # Saturate small singular values to inf. This has the effect of make\n # `1. / s = 0.` while not resulting in `NaN` gradients.\n cutoff = rcond * math_ops.reduce_max(singular_values, axis=-1)\n singular_values = array_ops.where_v2(\n singular_values > array_ops.expand_dims_v2(cutoff, -1), singular_values,\n np.array(np.inf, dtype))\n\n # By the definition of the SVD, `a == u @ s @ v^H`, and the pseudo-inverse\n # is defined as `pinv(a) == v @ inv(s) @ u^H`.\n a_pinv = math_ops.matmul(\n right_singular_vectors / array_ops.expand_dims_v2(singular_values, -2),\n left_singular_vectors,\n adjoint_b=True)\n\n if a.shape is not None and a.shape.rank is not None:\n a_pinv.set_shape(a.shape[:-2].concatenate([a.shape[-1], a.shape[-2]]))\n\n return a_pinv\n\n\n@tf_export('linalg.lu_solve')\ndef lu_solve(lower_upper, perm, rhs, validate_args=False, name=None):\n \"\"\"Solves systems of linear eqns `A X = RHS`, given LU factorizations.\n\n Note: this function does not verify the implied matrix is actually invertible\n nor is this condition checked even when `validate_args=True`.\n\n Args:\n lower_upper: `lu` as returned by `tf.linalg.lu`, i.e., if `matmul(P,\n matmul(L, U)) = X` then `lower_upper = L + U - eye`.\n perm: `p` as returned by `tf.linag.lu`, i.e., if `matmul(P, matmul(L, U)) =\n X` then `perm = argmax(P)`.\n rhs: Matrix-shaped float `Tensor` representing targets for which to solve;\n `A X = RHS`. To handle vector cases, use: `lu_solve(..., rhs[...,\n tf.newaxis])[..., 0]`.\n validate_args: Python `bool` indicating whether arguments should be checked\n for correctness. Note: this function does not verify the implied matrix is\n actually invertible, even when `validate_args=True`.\n Default value: `False` (i.e., don't validate arguments).\n name: Python `str` name given to ops managed by this object.\n Default value: `None` (i.e., 'lu_solve').\n\n Returns:\n x: The `X` in `A @ X = RHS`.\n\n #### Examples\n\n ```python\n import numpy as np\n import tensorflow as tf\n import tensorflow_probability as tfp\n\n x = [[[1., 2],\n [3, 4]],\n [[7, 8],\n [3, 4]]]\n inv_x = tf.linalg.lu_solve(*tf.linalg.lu(x), rhs=tf.eye(2))\n tf.assert_near(tf.matrix_inverse(x), inv_x)\n # ==> True\n ```\n\n \"\"\"\n\n with ops.name_scope(name or 'lu_solve'):\n lower_upper = ops.convert_to_tensor(\n lower_upper, dtype_hint=dtypes.float32, name='lower_upper')\n perm = ops.convert_to_tensor(perm, dtype_hint=dtypes.int32, name='perm')\n rhs = ops.convert_to_tensor(rhs, dtype_hint=lower_upper.dtype, name='rhs')\n\n assertions = _lu_solve_assertions(lower_upper, perm, rhs, validate_args)\n if assertions:\n with ops.control_dependencies(assertions):\n lower_upper = array_ops.identity(lower_upper)\n perm = array_ops.identity(perm)\n rhs = array_ops.identity(rhs)\n\n if (rhs.shape.rank == 2 and perm.shape.rank == 1):\n # Both rhs and perm have scalar batch_shape.\n permuted_rhs = array_ops.gather(rhs, perm, axis=-2)\n else:\n # Either rhs or perm have non-scalar batch_shape or we can't determine\n # this information statically.\n rhs_shape = array_ops.shape(rhs)\n broadcast_batch_shape = array_ops.broadcast_dynamic_shape(\n rhs_shape[:-2],\n array_ops.shape(perm)[:-1])\n d, m = rhs_shape[-2], rhs_shape[-1]\n rhs_broadcast_shape = array_ops.concat([broadcast_batch_shape, [d, m]],\n axis=0)\n\n # Tile out rhs.\n broadcast_rhs = array_ops.broadcast_to(rhs, rhs_broadcast_shape)\n broadcast_rhs = array_ops.reshape(broadcast_rhs, [-1, d, m])\n\n # Tile out perm and add batch indices.\n broadcast_perm = array_ops.broadcast_to(perm, rhs_broadcast_shape[:-1])\n broadcast_perm = array_ops.reshape(broadcast_perm, [-1, d])\n broadcast_batch_size = math_ops.reduce_prod(broadcast_batch_shape)\n broadcast_batch_indices = array_ops.broadcast_to(\n math_ops.range(broadcast_batch_size)[:, array_ops.newaxis],\n [broadcast_batch_size, d])\n broadcast_perm = array_ops.stack(\n [broadcast_batch_indices, broadcast_perm], axis=-1)\n\n permuted_rhs = array_ops.gather_nd(broadcast_rhs, broadcast_perm)\n permuted_rhs = array_ops.reshape(permuted_rhs, rhs_broadcast_shape)\n\n lower = set_diag(\n band_part(lower_upper, num_lower=-1, num_upper=0),\n array_ops.ones(\n array_ops.shape(lower_upper)[:-1], dtype=lower_upper.dtype))\n return triangular_solve(\n lower_upper, # Only upper is accessed.\n triangular_solve(lower, permuted_rhs),\n lower=False)\n\n\n@tf_export('linalg.lu_matrix_inverse')\ndef lu_matrix_inverse(lower_upper, perm, validate_args=False, name=None):\n \"\"\"Computes the inverse given the LU decomposition(s) of one or more matrices.\n\n This op is conceptually identical to,\n\n ```python\n inv_X = tf.lu_matrix_inverse(*tf.linalg.lu(X))\n tf.assert_near(tf.matrix_inverse(X), inv_X)\n # ==> True\n ```\n\n Note: this function does not verify the implied matrix is actually invertible\n nor is this condition checked even when `validate_args=True`.\n\n Args:\n lower_upper: `lu` as returned by `tf.linalg.lu`, i.e., if `matmul(P,\n matmul(L, U)) = X` then `lower_upper = L + U - eye`.\n perm: `p` as returned by `tf.linag.lu`, i.e., if `matmul(P, matmul(L, U)) =\n X` then `perm = argmax(P)`.\n validate_args: Python `bool` indicating whether arguments should be checked\n for correctness. Note: this function does not verify the implied matrix is\n actually invertible, even when `validate_args=True`.\n Default value: `False` (i.e., don't validate arguments).\n name: Python `str` name given to ops managed by this object.\n Default value: `None` (i.e., 'lu_matrix_inverse').\n\n Returns:\n inv_x: The matrix_inv, i.e.,\n `tf.matrix_inverse(tf.linalg.lu_reconstruct(lu, perm))`.\n\n #### Examples\n\n ```python\n import numpy as np\n import tensorflow as tf\n import tensorflow_probability as tfp\n\n x = [[[3., 4], [1, 2]],\n [[7., 8], [3, 4]]]\n inv_x = tf.linalg.lu_matrix_inverse(*tf.linalg.lu(x))\n tf.assert_near(tf.matrix_inverse(x), inv_x)\n # ==> True\n ```\n\n \"\"\"\n\n with ops.name_scope(name or 'lu_matrix_inverse'):\n lower_upper = ops.convert_to_tensor(\n lower_upper, dtype_hint=dtypes.float32, name='lower_upper')\n perm = ops.convert_to_tensor(perm, dtype_hint=dtypes.int32, name='perm')\n assertions = lu_reconstruct_assertions(lower_upper, perm, validate_args)\n if assertions:\n with ops.control_dependencies(assertions):\n lower_upper = array_ops.identity(lower_upper)\n perm = array_ops.identity(perm)\n shape = array_ops.shape(lower_upper)\n return lu_solve(\n lower_upper,\n perm,\n rhs=eye(shape[-1], batch_shape=shape[:-2], dtype=lower_upper.dtype),\n validate_args=False)\n\n\n@tf_export('linalg.lu_reconstruct')\ndef lu_reconstruct(lower_upper, perm, validate_args=False, name=None):\n \"\"\"The reconstruct one or more matrices from their LU decomposition(s).\n\n Args:\n lower_upper: `lu` as returned by `tf.linalg.lu`, i.e., if `matmul(P,\n matmul(L, U)) = X` then `lower_upper = L + U - eye`.\n perm: `p` as returned by `tf.linag.lu`, i.e., if `matmul(P, matmul(L, U)) =\n X` then `perm = argmax(P)`.\n validate_args: Python `bool` indicating whether arguments should be checked\n for correctness.\n Default value: `False` (i.e., don't validate arguments).\n name: Python `str` name given to ops managed by this object.\n Default value: `None` (i.e., 'lu_reconstruct').\n\n Returns:\n x: The original input to `tf.linalg.lu`, i.e., `x` as in,\n `lu_reconstruct(*tf.linalg.lu(x))`.\n\n #### Examples\n\n ```python\n import numpy as np\n import tensorflow as tf\n import tensorflow_probability as tfp\n\n x = [[[3., 4], [1, 2]],\n [[7., 8], [3, 4]]]\n x_reconstructed = tf.linalg.lu_reconstruct(*tf.linalg.lu(x))\n tf.assert_near(x, x_reconstructed)\n # ==> True\n ```\n\n \"\"\"\n with ops.name_scope(name or 'lu_reconstruct'):\n lower_upper = ops.convert_to_tensor(\n lower_upper, dtype_hint=dtypes.float32, name='lower_upper')\n perm = ops.convert_to_tensor(perm, dtype_hint=dtypes.int32, name='perm')\n\n assertions = lu_reconstruct_assertions(lower_upper, perm, validate_args)\n if assertions:\n with ops.control_dependencies(assertions):\n lower_upper = array_ops.identity(lower_upper)\n perm = array_ops.identity(perm)\n\n shape = array_ops.shape(lower_upper)\n\n lower = set_diag(\n band_part(lower_upper, num_lower=-1, num_upper=0),\n array_ops.ones(shape[:-1], dtype=lower_upper.dtype))\n upper = band_part(lower_upper, num_lower=0, num_upper=-1)\n x = math_ops.matmul(lower, upper)\n\n if (lower_upper.shape is None or lower_upper.shape.rank is None or\n lower_upper.shape.rank != 2):\n # We either don't know the batch rank or there are >0 batch dims.\n batch_size = math_ops.reduce_prod(shape[:-2])\n d = shape[-1]\n x = array_ops.reshape(x, [batch_size, d, d])\n perm = array_ops.reshape(perm, [batch_size, d])\n perm = map_fn.map_fn(array_ops.invert_permutation, perm)\n batch_indices = array_ops.broadcast_to(\n math_ops.range(batch_size)[:, array_ops.newaxis], [batch_size, d])\n x = array_ops.gather_nd(x, array_ops.stack([batch_indices, perm],\n axis=-1))\n x = array_ops.reshape(x, shape)\n else:\n x = array_ops.gather(x, array_ops.invert_permutation(perm))\n\n x.set_shape(lower_upper.shape)\n return x\n\n\ndef lu_reconstruct_assertions(lower_upper, perm, validate_args):\n \"\"\"Returns list of assertions related to `lu_reconstruct` assumptions.\"\"\"\n assertions = []\n\n message = 'Input `lower_upper` must have at least 2 dimensions.'\n if lower_upper.shape.rank is not None and lower_upper.shape.rank < 2:\n raise ValueError(message)\n elif validate_args:\n assertions.append(\n check_ops.assert_rank_at_least_v2(lower_upper, rank=2, message=message))\n\n message = '`rank(lower_upper)` must equal `rank(perm) + 1`'\n if lower_upper.shape.rank is not None and perm.shape.rank is not None:\n if lower_upper.shape.rank != perm.shape.rank + 1:\n raise ValueError(message)\n elif validate_args:\n assertions.append(\n check_ops.assert_rank(\n lower_upper, rank=array_ops.rank(perm) + 1, message=message))\n\n message = '`lower_upper` must be square.'\n if lower_upper.shape[:-2].is_fully_defined():\n if lower_upper.shape[-2] != lower_upper.shape[-1]:\n raise ValueError(message)\n elif validate_args:\n m, n = array_ops.split(\n array_ops.shape(lower_upper)[-2:], num_or_size_splits=2)\n assertions.append(check_ops.assert_equal(m, n, message=message))\n\n return assertions\n\n\ndef _lu_solve_assertions(lower_upper, perm, rhs, validate_args):\n \"\"\"Returns list of assertions related to `lu_solve` assumptions.\"\"\"\n assertions = lu_reconstruct_assertions(lower_upper, perm, validate_args)\n\n message = 'Input `rhs` must have at least 2 dimensions.'\n if rhs.shape.ndims is not None:\n if rhs.shape.ndims < 2:\n raise ValueError(message)\n elif validate_args:\n assertions.append(\n check_ops.assert_rank_at_least(rhs, rank=2, message=message))\n\n message = '`lower_upper.shape[-1]` must equal `rhs.shape[-1]`.'\n if (lower_upper.shape[-1] is not None and rhs.shape[-2] is not None):\n if lower_upper.shape[-1] != rhs.shape[-2]:\n raise ValueError(message)\n elif validate_args:\n assertions.append(\n check_ops.assert_equal(\n array_ops.shape(lower_upper)[-1],\n array_ops.shape(rhs)[-2],\n message=message))\n\n return assertions\n" ]
[ [ "tensorflow.python.keras.utils.generic_utils.deserialize_keras_object", "tensorflow.python.keras.utils.generic_utils.serialize_keras_object", "tensorflow.python.util.tf_inspect.isclass", "tensorflow.python.util.tf_export.keras_export", "tensorflow.python.tf2.enabled" ], [ "tensorflow.python.ops.linalg_ops.matrix_solve", "tensorflow.python.ops.array_ops.gather_nd", "tensorflow.python.ops.math_ops.maximum", "tensorflow.python.ops.array_ops.pad", "tensorflow.python.ops.array_ops.expand_dims", "tensorflow.python.ops.array_ops.matrix_transpose", "tensorflow.python.framework.tensor_shape.dimension_value", "tensorflow.python.ops.array_ops.matrix_diag_part", "tensorflow.python.ops.array_ops.invert_permutation", "tensorflow.python.ops.array_ops.expand_dims_v2", "tensorflow.python.ops.array_ops.broadcast_to", "tensorflow.python.framework.constant_op.constant", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.ops.math_ops.matmul", "tensorflow.python.ops.math_ops.range", "tensorflow.python.ops.math_ops.reduce_prod", "tensorflow.python.ops.array_ops.rank", "tensorflow.python.ops.map_fn.map_fn", "tensorflow.python.ops.math_ops.less", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.control_flow_ops.while_loop", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.ops.check_ops.assert_rank_at_least", "tensorflow.python.framework.ops.convert_to_tensor", "numpy.finfo", "tensorflow.python.ops.array_ops.ones", "tensorflow.python.ops.check_ops.assert_rank_at_least_v2", "tensorflow.python.ops.array_ops.gather", "tensorflow.python.ops.math_ops.reduce_max", "tensorflow.python.ops.math_ops.abs", "tensorflow.python.ops.linalg_ops.tridiagonal_solve", "tensorflow.python.ops.gen_linalg_ops.cholesky", "tensorflow.python.ops.math_ops.log", "tensorflow.python.ops.check_ops.assert_equal", "tensorflow.python.ops.linalg_ops.tridiagonal_mat_mul", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.array_ops.stack", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.ops.array_ops.reshape", "numpy.array", "tensorflow.python.ops.math_ops.conj" ] ]
zanzibar7/python-skyfield
[ "332038d49ea5814061336cd70cad1d819e630f2b" ]
[ "skyfield/tests/test_earth_satellites.py" ]
[ "# -*- coding: utf-8 -*-\n\nfrom numpy import array\nfrom skyfield import api\nfrom skyfield.api import EarthSatellite, load\nfrom skyfield.constants import AU_KM, AU_M\nfrom skyfield.sgp4lib import TEME_to_ITRF\nfrom skyfield.timelib import julian_date\n\nline1 = '1 25544U 98067A 18184.80969102 .00001614 00000-0 31745-4 0 9993'\nline2 = '2 25544 51.6414 295.8524 0003435 262.6267 204.2868 15.54005638121106'\n\n# Here are numbers from HORIZONS, which I copied into the test below:\n#\n#Ephemeris / WWW_USER Wed Jul 4 19:16:45 2018 Pasadena, USA / Horizons\n#...\n#2458303.500000000 = A.D. 2018-Jul-04 00:00:00.0000 TDB\n# X = 2.633404251158200E-05 Y = 1.015087620439817E-05 Z = 3.544778677556393E-05\n# VX=-1.751248694205384E-03 VY= 4.065407557020968E-03 VZ= 1.363540232307603E-04\n#2458304.500000000 = A.D. 2018-Jul-05 00:00:00.0000 TDB\n# X =-2.136440257814821E-05 Y =-2.084170814514480E-05 Z =-3.415494123796893E-05\n# VX= 2.143876266215405E-03 VY=-3.752167957502106E-03 VZ= 9.484159290242074E-04\n\n# TODO: try with array of dates\n\ndef test_iss_against_horizons():\n ts = api.load.timescale()\n s = EarthSatellite(line1, line2)\n\n hp = array([\n [2.633404251158200E-5, 1.015087620439817E-5, 3.544778677556393E-5],\n [-2.136440257814821E-5, -2.084170814514480E-5, -3.415494123796893E-5],\n ]).T\n hv = array([\n [-1.751248694205384E-3, 4.065407557020968E-3, 1.363540232307603E-4],\n [2.143876266215405E-3, -3.752167957502106E-3, 9.484159290242074E-4],\n ]).T\n\n two_meters = 2.0 / AU_M\n three_km_per_hour = 3.0 * 24.0 / AU_KM\n\n t = ts.tdb(2018, 7, 4)\n p = s.at(t)\n assert abs(p.position.au - hp[:,0]).max() < two_meters\n assert abs(p.velocity.au_per_d - hv[:,0]).max() < three_km_per_hour\n\n t = ts.tdb(2018, 7, [4, 5])\n p = s.at(t)\n assert abs(p.position.au - hp).max() < two_meters\n assert abs(p.velocity.au_per_d - hv).max() < three_km_per_hour\n\n# The following tests are based on the text of\n# http://www.celestrak.com/publications/AIAA/2006-6753/AIAA-2006-6753-Rev2.pdf\n\nappendix_c_example = \"\"\"\\\nTEME EXAMPLE\n1 00005U 58002B 00179.78495062 .00000023 00000-0 28098-4 0 4753\n2 00005 34.2682 348.7242 1859667 331.7664 19.3264 10.82419157413667\n\"\"\"\n\nfrom ..constants import DEG2RAD\n\narcminute = DEG2RAD / 60.0\narcsecond = arcminute / 60.0\nseconds_per_day = 86400.0\n\n# Note that the following test is based specifically on Revision 2 of\n# \"Revisiting Spacetrack Report #3\" AIAA 2006-6753 (earlier versions of\n# the PDF use different numbers):\n#\n# http://ww.celestrak.com/publications/AIAA/2006-6753/AIAA-2006-6753-Rev2.pdf\n\ndef test_appendix_c_conversion_from_TEME_to_ITRF():\n rTEME = array([5094.18016210, 6127.64465950, 6380.34453270])\n vTEME = array([-4.746131487, 0.785818041, 5.531931288])\n vTEME = vTEME * 24.0 * 60.0 * 60.0 # km/s to km/day\n\n jd_utc = julian_date(2004, 4, 6, 7, 51, 28.386)\n d_ut1 = -0.439961\n jd_ut1 = jd_utc + d_ut1 / 86400.0\n\n xp = -0.140682 * arcsecond\n yp = 0.333309 * arcsecond\n\n rITRF, vITRF = TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp, yp)\n\n epsilon = 5e-8 # Why not 1e-8, which would match all of their digits?\n\n assert abs(-1033.47938300 - rITRF[0]) < epsilon\n assert abs(+7901.29527540 - rITRF[1]) < epsilon\n assert abs(+6380.35659580 - rITRF[2]) < epsilon\n\n vITRF_per_second = vITRF / seconds_per_day\n\n epsilon = 7e-8 # Why not 1e-9, which would match all of their digits?\n\n assert abs(-3.225636520 - vITRF_per_second[0]) < epsilon\n assert abs(-2.872451450 - vITRF_per_second[1]) < epsilon\n assert abs(+5.531924446 - vITRF_per_second[2]) < epsilon\n\ndef test_appendix_c_satellite():\n lines = appendix_c_example.splitlines()\n ts = api.load.timescale()\n sat = EarthSatellite(lines[1], lines[2], lines[0], ts)\n t = ts.tt_jd(sat.epoch.whole + 3.0, sat.epoch.tt_fraction)\n\n # First, a crucial sanity check (which is, technically, a test of\n # the `sgp4` package and not of Skyfield): are the right coordinates\n # being produced by our Python SGP4 propagator for this satellite?\n\n rTEME, vTEME, error = sat._position_and_velocity_TEME_km(t)\n\n # TODO: This used to be accurate to within 1e-8 but lost precision\n # with the move to SGP4 2.0. Is the difference an underlying change\n # in the algorithm and its results? Or something else?\n epsilon = 1e-4\n assert abs(-9060.47373569 - rTEME[0]) < epsilon\n assert abs(4658.70952502 - rTEME[1]) < epsilon\n assert abs(813.68673153 - rTEME[2]) < epsilon\n\n # TODO: Similar to the above, this used to be 1e-9.\n epsilon = 1e-8\n assert abs(-2.232832783 - vTEME[0]) < epsilon\n assert abs(-4.110453490 - vTEME[1]) < epsilon\n assert abs(-3.157345433 - vTEME[2]) < epsilon\n\ndef test_epoch_date():\n # Example from https://celestrak.com/columns/v04n03/\n s = appendix_c_example.replace('00179.78495062', '98001.00000000')\n lines = s.splitlines()\n sat = EarthSatellite(lines[1], lines[2], lines[0])\n assert sat.epoch.utc_jpl() == 'A.D. 1998-Jan-01 00:00:00.0000 UT'\n\ndef test_target_number():\n s = EarthSatellite(line1, line2)\n assert s.target == -125544\n\ndef test_is_sunlit():\n # Yes, a positionlib method; but it made sense to test it here.\n ts = api.load.timescale()\n t = ts.utc(2018, 7, 3, 0, range(0, 60, 10))\n s = EarthSatellite(line1, line2)\n eph = load('de421.bsp')\n expected = [True, False, False, False, True, True]\n assert list(s.at(t).is_sunlit(eph)) == expected\n\n # What if we observe from a topos rather than the geocenter?\n topos = api.Topos('40.8939 N', '83.8917 W')\n assert list((s - topos).at(t).is_sunlit(eph)) == expected\n\ndef test_is_venus_behind_earth():\n # Like the previous test: a satellite-focused positionlib method.\n # Just for fun, we ask whether the Sun is behind the earth, so this\n # measures the same celestial circumstance as the previous test.\n ts = api.load.timescale()\n t = ts.utc(2018, 7, 3, 0, range(0, 60, 10))\n s = EarthSatellite(line1, line2)\n eph = load('de421.bsp')\n expected = [False, True, True, True, False, False]\n p = (eph['earth'] + s).at(t).observe(eph['sun']).apparent()\n assert list(p.is_behind_earth()) == expected\n\ndef test_is_another_satellite_behind_earth():\n # See if the method works with a pure geometric difference.\n ts = api.load.timescale()\n t = ts.utc(2018, 7, 3, 0, range(0, 60, 10))\n s = EarthSatellite(line1, line2)\n # The \"other satellite\" is fictitious: the ISS offset by one day.\n s2 = EarthSatellite(line1.replace('184.80969102', '185.80969102'), line2)\n expected = [True, True, True, True, True, True]\n p = (s - s2).at(t)\n assert list(p.is_behind_earth()) == expected\n" ]
[ [ "numpy.array" ] ]
yamasampo/alignmentrs
[ "5f963d13ac2db72f4ef23b462de0836526f590b7" ]
[ "alignmentrs/aln/mixins/serde.py" ]
[ "from collections import OrderedDict, ChainMap\nfrom copy import deepcopy\nimport os\nimport json\nimport pickle\nimport re\nimport io\n\nimport pandas\n\nfrom libalignmentrs.alignment import SeqMatrix\nfrom libalignmentrs.readers import fasta_to_dict\nfrom alignmentrs.utils import to_intlist\n\n\n__all__ = [\n 'FastaSerdeMixin', 'DictSerdeMixin', 'JsonSerdeMixin', \n 'PickleSerdeMixin', 'CsvSerdeMixin', 'RecordsSerdeMixin',\n 'col_metadata_to_str', 'col_metadata_str_formatter',\n]\n\n\n_whitespace_regexp = re.compile(r'\\s+')\n_column_metadata_string_regexp = re.compile(r'meta\\|(\\S+)\\=(\\S+)')\n\n\nclass FastaSerdeMixin:\n \"\"\"Adds ability to read/write an Alignment object\n from a FASTA formatted file.\n \"\"\"\n @classmethod\n def from_fasta(\n cls, path, name=None, \n # parse_row_metadata=True,\n parse_description=True, \n # column_metadata_decoders=None,\n column_metadata_regexp='c\\|([A-Za-z0-9\\s\\.]+)=(\\[[A-Za-z0-9\\.\\s,\\\"\\']+\\])',\n column_index_regexp='ci\\|([A-Za-z0-9\\s\\.]+)=(\\[[A-Za-z0-9\\.\\s,\\\"\\']+\\])',\n store_history=True, **kwargs):\n \"\"\"Create an Alignment object from a FASTA-formatted file.\n\n Parameters\n ----------\n path : str\n Path to FASTA file.\n name : str, optional\n Name of the new alignment.\n (default is None, takes the name from the comments\n or uses the filename)\n parse_description : function, optional\n Function that takes a list of comment lines as input\n and outputs a dictionary that organizes comments into\n keys and values. (default is None, lines starting with \n a semicolon \";\" are ignored.)\n\n Returns\n -------\n Alignment\n Creates a new Alignment object based on the identifiers,\n descriptions, and sequences in the FASTA file.\n\n \"\"\"\n matrix, metadata = fasta_to_dict(path)\n row_meta, col_meta = None, None\n if parse_description:\n # Parses metadata['descriptions'] and removes parsed info\n offset = 0\n match_locations = []\n col_d = {}\n col_idx = None\n # Parses column index\n match = re.search(column_index_regexp, metadata['descriptions'][0])\n if match:\n key, value = match.groups()\n # Convert text into a list using eval\n try:\n value = cls._parse_str_to_list(value, 'infer')\n except SyntaxError:\n raise ValueError('Cannot construct Alignment from the given FASTA file: column index is malformed'.format(key))\n # Put key-value pair into the dictionary\n col_idx = value\n\n # Parses column metadata\n for match in re.finditer(column_metadata_regexp,\n metadata['descriptions'][0]):\n match_locations.append(match.span())\n key, value = match.groups()\n # Convert text into a list using eval\n try:\n value = cls._parse_str_to_list(value, 'infer')\n except SyntaxError:\n raise ValueError('Cannot construct Alignment from the given FASTA file: column metadata {} is malformed'.format(key))\n # Put key-value pair into the dictionary\n col_d[key] = value\n # Constructs column metadata DataFrame from dictionary and index\n if (col_idx is not None) or col_d:\n col_meta = pandas.DataFrame(col_d, index=col_idx)\n\n if name is None:\n name = os.path.basename(path)\n return cls(matrix, name,\n row_metadata=row_meta,\n # row_ids and row_descriptions are ignored\n # if row_meta is not None\n row_ids=metadata['ids'],\n row_descriptions=metadata['descriptions'],\n # col_meta is None unless parse_column_metadata is True\n col_metadata=col_meta,\n aln_metadata=metadata['comments'],\n store_history=store_history, **kwargs)\n\n def to_fasta(self, path=None, include_column_metadata=None, column_metadata_encoders=None, column_metadata_template='c|{}={}', **kwargs):\n \"\"\"Saves the alignment as a FASTA-formatted file.\n Some metadata may not be lost.\n\n Parameters\n ----------\n path : str, optional\n Path to save the alignment to.\n include_column_metadata : list of str, optional\n List of keys of columns in column metadata to include\n (default is None, information are not written as FASTA comments\n to ensure maximum compatibility)\n column_metadata_encoders : dict of callable, optional\n Dictionary of functions used to transform values of included\n column metadata.\n Keys are expected to match specified column names.\n (default is None, all included columns will be transformed using the\n `str` string constructor)\n\n \"\"\"\n # Default values if not specified\n if include_column_metadata is None:\n include_column_metadata = []\n if column_metadata_encoders is None:\n column_metadata_encoders = {}\n\n # Transform col metadata DataFrame into a stringed representation\n # of columns and values.\n col_meta_str = col_metadata_to_str(\n self.column_metadata, include_column_metadata,\n column_metadata_encoders, column_metadata_template\n )\n # Creates a generator that writes each entry as a string\n # in the FASTA format:\n # >{sid} {desc}\n # {seq}\n info_generator = (\n (vals[0], vals[1]['description'], self.data.data[i]) \n for i, vals in enumerate(self.row_metadata.iterrows())\n )\n fasta_str = '\\n'.join([\n self._fasta_entry_formatter(*params, col_meta_str)\n if i == 0 else\n self._fasta_entry_formatter(*params, '')\n for i, params in enumerate(info_generator)\n ])\n\n # Write the FASTA string to file\n if path is None:\n return fasta_str\n dirpath = os.path.dirname(os.path.abspath(path))\n if not os.path.isdir(dirpath):\n raise OSError('{} does not exist'.format(dirpath))\n with open(path, 'w') as writer:\n print(fasta_str, file=writer)\n\n @staticmethod\n def _parse_str_to_list(string: str, item_type: type = 'infer'):\n \"\"\" Returns a list by parsing a given string. The input string has to\n expressed as like Python list syntax.\n \n Parameters\n ----------\n string: str\n A string to be converted into a list. Format should be Python\n syntax of list object like \"[1, 2, 3]\". It has to starts with \"[\"\n and ends with \"]\" and items have to be separated by \",\".\n item_type: type (default: str)\n Type in which items in str-like list will be converted. For example,\n \"[1, 2, 3]\" and int are passed to string and item_type variables \n respectively, \"[1, 2, 3]\" will converted into [1, 2, 3] not\n [\"1\", \"2\", \"3\"].\n\n Return\n ------\n A list version of the input string.\n\n \"\"\"\n # Check if item_type variable is \"type\" type\n if item_type != 'infer' and not isinstance(item_type, type):\n raise TypeError('Invalid type: object constructor type should be '\\\n 'passed to \"item_type\" variable.')\n\n # Check if sring is str\n if not isinstance(string, str):\n raise TypeError('Invalid type: \"string\" variable has to be str type.')\n\n # Check string format\n if not string.startswith('['):\n raise SyntaxError(f'Invalid syntax for conversion to a list. '\\\n '{string} does not start with \"[\".')\n if not string.endswith(']'):\n raise SyntaxError(f'Invalid syntax for conversion to a list. '\\\n '{string} does not end with \"]\".')\n \n # Convert into a list\n if item_type == 'infer':\n out_l = []\n for item in string.split('[')[1].split(']')[0].split(','):\n try:\n dat = int(item)\n # e.g. int('1.1') gives \"ValueError: invalid literal for int() \n # with base 10: '1.1'\"\n except ValueError:\n dat = float(item)\n # e.g. float('a') gives \"ValueError: could not convert string \n # to float: 'a'\"\n except:\n dat = item\n\n out_l.append(dat)\n return out_l\n\n return [item_type(item) for item \n in string.split('[')[1].split(']')[0].split(',')]\n\n @staticmethod\n def _fasta_entry_formatter(sid, desc, seq, col_meta):\n # Formats the ID, description, stringed metadata, and sequence\n # to follow the FASTA format.\n # There are 4 possible scenarios, note that the identifier string\n # is always expected to have a non-empty value:\n # - all information exists\n # - col_meta is an empty string\n # - description is an empty string\n # - both col_meta and description are empty strings\n\n # Checks if ID is empty\n if len(sid) < 1:\n raise ValueError('Cannot create FASTA file: identifier string cannot be empty.')\n # Description is not empty\n if len(desc) > 0:\n if len(col_meta) > 0:\n return '>{} {} {}\\n{}'.format(sid, desc, col_meta, seq)\n return '>{} {}\\n{}'.format(sid, desc, seq)\n # Description is empty but column metadata is not empty\n if len(col_meta) > 0:\n return '>{} {}\\n{}'.format(sid, col_meta, seq)\n # Decription and column metadata are empty\n return '>{}\\n{}'.format(sid, seq)\n\n\nclass DictSerdeMixin:\n \"\"\"Adds ability to read/write an Alignment object from a dictionary.\n \"\"\"\n @classmethod\n def from_dict(cls, d, store_history=True, **kwargs):\n \"\"\"Creates an Alignment object from a dictionary.\n\n Parameters\n ----------\n d : dict\n Dictionary containing the alignment information and relevant\n metadata.\n\n Returns\n -------\n Alignment\n\n \"\"\"\n return cls(d['data'],\n name=d['name'],\n row_ids=d['row_metadata_index'],\n row_descriptions=d['row_metadata'],\n col_ids=d['column_metadata_index'],\n col_descriptions=d['column_metadata'],\n aln_metadata=d['alignment_metadata'],\n store_history=store_history,\n **kwargs)\n\n def to_dict(self, row_metadata=True, column_metadata=True):\n \"\"\"Returns the dictionary representation of the alignment.\n Contents of the dictionary use builtin types to maximize\n compatibility.\n\n Parameters\n ----------\n row_metadata : bool, optional\n Whether or not to include row metadata information. (default is True, row metadata is included)\n column_metadata : bool, optional\n Whether or not to include column metadata information. (default is True, column metadata is included)\n\n Returns\n -------\n dict\n\n \"\"\"\n d = {\n 'name': self.name,\n 'data': self.data.data,\n 'alignment_metadata': self.alignment_metadata,\n }\n if row_metadata:\n d['row_metadata'] = self.row_metadata.to_dict(orient='list')\n d['row_metadata_index'] = self.row_metadata.index.tolist()\n if column_metadata:\n d['column_metadata'] = self.column_metadata.to_dict(orient='list')\n d['column_metadata_index'] = self.column_metadata.index.tolist()\n return d\n\nclass JsonSerdeMixin(DictSerdeMixin):\n \"\"\"Adds ability to read/write an Alignment object from a JSON file.\n\n The underlying organization of the JSON encoding is based on the dictionary \n created using the DictSerdeMixin dictionary mixin.\n \"\"\"\n @classmethod\n def from_json(cls, path, store_history=True, **kwargs):\n \"\"\"Create an alignment from a JSON file.\n \n Parameters\n ----------\n path : io.IOBase or str\n File stream using a file handler or a string to the path.\n \n Returns\n -------\n Alignment\n\n \"\"\"\n if isinstance(path, io.IOBase):\n # json.load requires a file handler to read the file.\n # io.IOBase is the abstract base class for all kinds of\n # I/O file streaming.\n d = json.load(path)\n elif isinstance(path, str):\n # The user can also input the path where the json file is located.\n # To handle this, the path will have to be opened as a file handler\n with open(path, 'r') as reader:\n d = json.load(reader)\n # JSON structure is based on to_dict and so it is dependent\n # on DictSerdeMixin.\n return cls.from_dict(d, store_history=store_history, **kwargs)\n\n def to_json(self, path=None, row_metadata=True, column_metadata=True):\n \"\"\"Saves the alignment as a JSON file.\n\n Parameters\n ----------\n path : str, optional\n Path to save the alignment to.\n row_metadata : bool, optional\n Whether or not to include row metadata information. (default is True, row metadata is included)\n column_metadata : bool, optional\n Whether or not to include column metadata information. (default is True, column metadata is included)\n\n Returns\n -------\n str\n If path is None, returns the JSON-formatted text as a string.\n\n \"\"\"\n # to_json uses to_dict to transform the alignment data\n # into a representation that uses only builtins to maximize\n # compatibility.\n # The resulting dictionary is encoded into JSON.\n d = self.to_dict(\n row_metadata=row_metadata,\n column_metadata=column_metadata)\n json_str = json.dumps(d)\n # If the save path is not specified, the encoded JSON text\n # is returned as a string\n if path is None:\n return json_str\n # If the save path is specified, the JSON encoded text\n # is written as a text file.\n dirpath = os.path.dirname(os.path.abspath(path))\n if not os.path.isdir(dirpath):\n raise OSError('{} does not exist'.format(dirpath))\n with open(path, 'w') as writer:\n print(json_str, file=writer)\n\n\nclass PickleSerdeMixin:\n \"\"\"Adds ability to pickle/unpickle an Alignment object.\n \"\"\"\n @classmethod\n def from_pickle(cls, path, store_history=True, **kwargs):\n \"\"\"Converts a pickled alignment back into an Alignment object.\n\n Parameters\n ----------\n path : io.IOBase or str\n File handler for the pickled alignment or a string to the path.\n\n Returns\n -------\n Alignment\n\n \"\"\"\n if isinstance(path, io.IOBase):\n obj = pickle.load(path)\n elif isinstance(path, str):\n with open(path, 'rb') as reader:\n obj = pickle.load(reader)\n return obj\n\n def to_pickle(self, path=None, **kwargs):\n \"\"\"Pickles the current alignment.\n\n Parameters\n ----------\n path : str, optional\n Path to save the alignment to.\n\n Returns\n -------\n bytestring\n If path is None, returns the bytestring representation of the\n pickled alignment.\n\n \"\"\"\n # Pickles the alignment. Underlying methods that do the pickling are\n # __getstate__ and __setstate__.\n pickled = pickle.dumps(self)\n # If path is not provided, the bytestring of the pickle is returned.\n if path is None:\n return pickled\n # If path is provided, the pickle is written to file.\n dirpath = os.path.dirname(os.path.abspath(path))\n if not os.path.isdir(dirpath):\n raise OSError('{} does not exist'.format(dirpath))\n with open(path, 'wb') as writer:\n writer.write(pickled)\n\n def __getstate__(self):\n # This method gets called when the Alignment object\n # is being pickled.\n d = {k: v for k, v in self.__dict__.items() if k != 'data'}\n d['data'] = self.data.data\n return d\n\n def __setstate__(self, d):\n # This method gets called when the pickled object\n # is being unpickled back into an Alignment object.\n d['data'] = SeqMatrix(d['data'])\n self.__dict__ = d\n\n\nclass NexusSerdeMixin:\n pass\n\n\nclass PhylipSerdeMixin:\n pass\n\n\ndef col_metadata_to_str(column_metadata, included_keys, encoders=None, template='c|{}={}', index_template='ci|{}={}'):\n \"\"\"Transforms the column metadata DataFrame into a string representation.\n \n Parameters\n ----------\n column_metadata : pandas.DataFrame\n Column metadata\n included_keys : list of str\n List of column metadata column names that to be included in the\n string representation.\n encoders : dict of callable, optional\n Dictionary of functions used to transform column metadata values.\n Keys are expected to match the column names of the column metadata\n DataFrame. (default is None, all columns will be transformed using the\n `str` string constructor)\n template : str, optional\n Template used for formatting the string. Template should have 2\n slots for the key and the column value.\n \n Returns\n -------\n str\n Column metadata categories and values represented as a string.\n\n \"\"\"\n # Creates a tuple generator giving the filtered set of column metadata\n # Each tuple generated consists of the column name and the list of values\n # for that column. \n included_values = (\n (k, v) for k, v in column_metadata.to_dict(orient='list').items()\n if k in included_keys\n )\n if encoders is None:\n encoders = dict()\n # Creates a list of stringed column metadata where each string is the\n # contains the stringed data of a column metadata category (column)\n # The metadata column is transformed into a string by consuming\n # the `included_values` generator and calling `col_metadata_str_formatter`\n # for each item yielded.\n str_list = [\n col_metadata_str_formatter(\n k, v, encoders[k] if k in encoders.keys() else None, template)\n for k, v in included_values\n ]\n str_index = [col_metadata_str_formatter(\n 'index', column_metadata.index.tolist(),\n encoders['index'] if 'index' in encoders.keys() else None, \n index_template)\n ]\n # Each column's string representation is separated by a whitespace\n return ' '.join(str_index + str_list)\n\ndef col_metadata_str_formatter(key, value, encoder:callable=None, template='c|{}={}'):\n \"\"\"Returns the string representation of a column metadata category.\n \n Parameters\n ----------\n key : str\n Name of column metadata category (column name in the DataFrame).\n value : list\n Column metadata category values.\n encoder : callable\n Function used to transform the list of values into a string.\n template : str, optional\n Template used for formatting the string. Template should have 2\n slots for the key and the column value.\n\n Returns\n -------\n str\n String representation of the column metadata category and its values.\n\n \"\"\"\n if encoder is None:\n encoder = lambda x: _whitespace_regexp.sub('', str(x))\n return template.format(key, encoder(value))\n\ndef make_col_meta_dict(description, decoders):\n matches = _column_metadata_string_regexp.findall(description)\n return {\n k: (decoders[k](v) if k in decoders.keys() else eval(v))\n for k, v in matches\n }\n" ]
[ [ "pandas.DataFrame" ] ]
lmmentel/mendeleev
[ "f6ac866c831e3041910ae97a7177301b1be5b3e7" ]
[ "mendeleev/vis/seaborn.py" ]
[ "from typing import Tuple\nimport seaborn as sns\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndef heatmap(\n elements: pd.DataFrame,\n prop: str,\n style: str = \"whitegrid\",\n figsize: Tuple[int] = (16, 10),\n cmap: str = \"RdBu_r\",\n lw: int = 1,\n output: str = None,\n **kwargs\n):\n \"\"\"\n Plot a heatmap of the given property\n\n Args:\n elements: DataFrame with data about elements\n prop : Name of the attribute of Element object that is available from the\n elements table\n style : Seaborn style option, default='whitegrid\n figsize : Size of the plot, default=(16, 10)\n cmap : Colormap to use, default='RdBu_r'\n lw : Seaborn heatmap `linewidths` argumentm default=1,\n see http://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.heatmap.html\n output : File name to save the plot, by default nothing is saved\n \"\"\"\n\n # add lanthanides and actinides\n\n keys = [\"period\", \"group_id\", prop]\n els = elements[keys].dropna()\n elements_rect = els.pivot(*keys)\n\n sns.set(font_scale=1.5, style=style, rc={\"figure.figsize\": figsize})\n mask = np.asarray(elements_rect.isnull())\n ax = sns.heatmap(elements_rect, cmap=cmap, mask=mask, linewidths=lw, **kwargs)\n n = len(ax.xaxis.get_ticklabels())\n ax.set_yticklabels(elements_rect.index[::-1], rotation=0)\n ax.set_xticklabels(list(range(1, n + 1)))\n ax.xaxis.tick_top()\n ax.xaxis.set_label_position(\"top\")\n ax.set_xlabel(\"Group\")\n ax.set_ylabel(\"Period\")\n if output is not None:\n plt.savefig(output)\n return ax\n" ]
[ [ "matplotlib.pyplot.savefig" ] ]
baoy-nlp/DSS-VAE
[ "855f5722301b2d22aef622e7bb8fef74a759f9de" ]
[ "dss_vae/structs/distance_tree.py" ]
[ "import re\n\nimport nltk\nimport numpy\n\nword_tags = ['CC', 'CD', 'DT', 'EX', 'FW', 'IN', 'JJ', 'JJR',\n 'JJS', 'LS', 'MD', 'NN', 'NNS', 'NNP', 'NNPS', 'PDT',\n 'POS', 'PRP', 'PRP$', 'RB', 'RBR', 'RBS', 'RP',\n 'SYM', 'TO', 'UH', 'VB', 'VBD', 'VBG', 'VBN', 'VBP',\n 'VBZ', 'WDT', 'WP', 'WP$', 'WRB']\ncurrency_tags_words = ['#', '$', 'C$', 'A$']\neclipse = ['*', '*?*', '0', '*T*', '*ICH*', '*U*', '*RNR*', '*EXP*', '*PPA*', '*NOT*']\npunctuation_tags = ['.', ',', ':', '-LRB-', '-RRB-', '\\'\\'', '``']\npunctuation_words = ['.', ',', ':', '-LRB-', '-RRB-', '\\'\\'', '``',\n '--', ';', '-', '?', '!', '...', '-LCB-',\n '-RCB-']\ndeleted_tags = ['TOP', '-NONE-', ',', ':', '``', '\\'\\'']\n\n\ndef process_arc(label):\n labels = label.split('+')\n new_arc = []\n for sub_labels in labels:\n if sub_labels == 'ADVP':\n sub_labels = 'PRT'\n new_arc.append(sub_labels)\n label = '+'.join(new_arc)\n return label\n\n\ndef process_none(tree):\n if isinstance(tree, nltk.Tree):\n label = tree.label()\n if label == '-NONE-':\n return None\n else:\n tr = []\n for node in tree:\n new_node = process_none(node)\n if new_node is not None:\n tr.append(new_node)\n if len(tr) == 0:\n return None\n else:\n return nltk.Tree(label, tr)\n else:\n return tree\n\n\ndef build_nltk_tree(depth, arc, tag, sen, arc_dict, tag_dict, stag_dict, stags=None):\n \"\"\"\n stags are the stanford predicted tags present in the train/valid/test files.\n \"\"\"\n assert len(sen) > 0\n assert len(depth) == len(sen) - 1, (\"%s_%s\" % (len(depth), len(sen)))\n if stags:\n assert len(stags) == len(tag)\n\n if len(sen) == 1:\n tag_list = str(tag_dict[tag[0]]).split('+')\n tag_list.reverse()\n # if stags, put the real stanford pos TAG for the word and leave the\n # unary chain on top.\n if stags is not None:\n assert len(stags) > 0\n tag_list.insert(0, str(stag_dict[stags[0]]))\n word = str(sen[0])\n for t in tag_list:\n word = nltk.Tree(t, [word])\n assert isinstance(word, nltk.Tree)\n return word\n else:\n idx = numpy.argmax(depth)\n node0 = build_nltk_tree(\n depth[:idx], arc[:idx], tag[:idx + 1], sen[:idx + 1],\n arc_dict, tag_dict, stag_dict, stags[:idx + 1] if stags else None)\n node1 = build_nltk_tree(\n depth[idx + 1:], arc[idx + 1:], tag[idx + 1:], sen[idx + 1:],\n arc_dict, tag_dict, stag_dict, stags[idx + 1:] if stags else None)\n\n if node0.label() != '<empty>' and node1.label() != '<empty>':\n tr = [node0, node1]\n elif node0.label() == '<empty>' and node1.label() != '<empty>':\n tr = [c for c in node0] + [node1]\n elif node0.label() != '<empty>' and node1.label() == '<empty>':\n tr = [node0] + [c for c in node1]\n elif node0.label() == '<empty>' and node1.label() == '<empty>':\n tr = [c for c in node0] + [c for c in node1]\n\n arc_list = str(arc_dict[arc[idx]]).split('+')\n arc_list.reverse()\n for a in arc_list:\n if isinstance(tr, nltk.Tree):\n tr = [tr]\n tr = nltk.Tree(a, tr)\n\n return tr\n\n\ndef mrg(tr):\n if isinstance(tr, str):\n return '( %s )' % tr\n # return tr + ' '\n else:\n s = '('\n for subtr in tr:\n s += mrg(subtr) + ' '\n s += ')'\n return s\n\n\ndef get_brackets(tree, start_idx=0, root=False):\n assert isinstance(tree, nltk.Tree)\n label = tree.label()\n label = label.replace('ADVP', 'PRT')\n\n brackets = set()\n if isinstance(tree[0], nltk.Tree):\n end_idx = start_idx\n for node in tree:\n node_brac, next_idx = get_brackets(node, end_idx)\n brackets.update(node_brac)\n end_idx = next_idx\n if not root:\n brackets.add((start_idx, end_idx, label))\n else:\n end_idx = start_idx + 1\n\n return brackets, end_idx\n\n\ndef normalize(x):\n return x / (sum(x) + 1e-8)\n\n\ndef tree2list(tree, parent_arc=[]):\n if isinstance(tree, nltk.Tree):\n label = tree.label()\n if isinstance(tree[0], nltk.Tree):\n label = re.split('-|=', tree.label())[0]\n root_arc_list = parent_arc + [label]\n root_arc = '+'.join(root_arc_list)\n if len(tree) == 1:\n root, arc, tag = tree2list(tree[0], parent_arc=root_arc_list)\n elif len(tree) == 2:\n c0, arc0, tag0 = tree2list(tree[0])\n c1, arc1, tag1 = tree2list(tree[1])\n root = [c0, c1]\n arc = arc0 + [root_arc] + arc1\n tag = tag0 + tag1\n else:\n c0, arc0, tag0 = tree2list(tree[0])\n c1, arc1, tag1 = tree2list(nltk.Tree('<empty>', tree[1:]))\n if bin == 0:\n root = [c0] + c1\n else:\n root = [c0, c1]\n arc = arc0 + [root_arc] + arc1\n tag = tag0 + tag1\n return root, arc, tag\n else:\n if len(parent_arc) == 1:\n parent_arc.insert(0, '<empty>')\n # parent_arc[-1] = '<POS>'\n del parent_arc[-1]\n return str(tree), [], ['+'.join(parent_arc)]\n\n\ndef get_distance(root):\n if isinstance(root, list):\n dist_list = []\n depth_list = []\n for child in root:\n dist, depth = get_distance(child)\n dist_list.append(dist)\n depth_list.append(depth)\n\n max_depth = max(depth_list)\n\n out = dist_list[0]\n for dist in dist_list[1:]:\n out.append(max_depth)\n out.extend(dist)\n return out, max_depth + 1\n else:\n return [], 1\n" ]
[ [ "numpy.argmax" ] ]
AlexLJC/MLTetris
[ "dc47321746bcd67989cb7190941827c317036d6b" ]
[ "python/TetrisDRL.py" ]
[ "# Import\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nfrom collections import deque\nimport random\n\nimport tetris as tetris\n\n\n# Hyperparameter \n\nnum_episodes = 500\nnum_exploration_episodes = 100\nmax_len_episode = 1000\nbatch_size = 40\nlearning_rate = 0.005\ngamma = 0.95\ninitial_epsilon = 1.0\nfinal_epsilon = 0.01\n\neps_decay = 0.995\neps_min = 0.01\n\n\nclass QNetwork(tf.keras.Model):\n def __init__(self):\n super().__init__()\n self.state_dim = 216\n self.action_dim = 36\n self.epsilon = 1.\n self.dense1 = tf.keras.layers.Dense(units=216, input_dim=216,activation=tf.nn.relu)\n self.dense2 = tf.keras.layers.Dense(units=116, activation=tf.nn.relu)\n self.dense3 = tf.keras.layers.Dense(units=36, activation=tf.nn.relu)\n self.dense4 = tf.keras.layers.Dense(units=self.action_dim)\n \n \n \n self.model = self.create_model()\n \n def call(self, inputs):\n x = self.dense1(inputs)\n x = self.dense2(x)\n x = self.dense3(x)\n return x\n \n def create_model(self):\n# model = tf.keras.Sequential([\n# Input((self.state_dim,)),\n# Dense(32, activation='relu'),\n# Dense(16, activation='relu'),\n# Dense(self.action_dim)\n# ])\n model = tf.keras.models.Sequential()\n model.add(self.dense1)\n model.add(self.dense2)\n model.add(self.dense3)\n model.add(self.dense4)\n model.compile(loss='mse', optimizer=tf.keras.optimizers.Adam(learning_rate))\n return model\n \n def predict(self, state):\n return self.model.predict(state)\n \n def get_action(self, state):\n state = np.reshape(state, [1, self.state_dim])\n self.epsilon *= eps_decay\n self.epsilon = max(self.epsilon, eps_min)\n q_value = self.predict(state)[0]\n if np.random.random() < self.epsilon:\n return random.randint(0, 35)\n \n \n return np.argmax(q_value)\n \n def train(self, states, targets):\n self.model.fit(states, targets, epochs=1, verbose=0)\nclass ReplayBuffer:\n def __init__(self, capacity=100000):\n self.buffer = deque(maxlen=capacity)\n \n def put(self, state, action, reward, next_state, done):\n self.buffer.append([state, action, reward, next_state, done])\n \n def sample(self):\n sample = random.sample(self.buffer, batch_size)\n states, actions, rewards, next_states, done = map(np.asarray, zip(*sample))\n states = np.array(states).reshape(batch_size, -1)\n next_states = np.array(next_states).reshape(batch_size, -1)\n return states, actions, rewards, next_states, done\n \n def size(self):\n return len(self.buffer)\n \nclass Agent:\n def __init__(self, env):\n self.env = env\n self.state_dim = 216\n self.action_dim = 36 # move 0 - 8 rotate 0 - 3 = 9*4\n\n self.model = QNetwork()\n self.target_model = QNetwork()\n self.target_update()\n\n self.buffer = ReplayBuffer()\n \n self.max_score_now = 0\n def target_update(self):\n weights = self.model.model.get_weights()\n self.target_model.model.set_weights(weights)\n \n def replay(self):\n for _ in range(10):\n states, actions, rewards, next_states, done = self.buffer.sample()\n targets = self.target_model.predict(states)\n next_q_values = self.target_model.predict(next_states).max(axis=1)\n #print(states, actions, rewards, next_states, done,next_q_values )\n targets[range(batch_size), actions] = rewards + (1-done) * next_q_values * gamma\n self.model.train(states, targets)\n \n def train(self, max_episodes=1000):\n print(\"Start.\")\n for ep in range(max_episodes):\n done, total_reward = False, 0\n state = self.env.reset()\n while not done:\n action = self.model.get_action(state)\n #print(type(action),action)\n next_state, reward, done, info = self.env.step_action(int(action))\n self.buffer.put(state, action, reward, next_state, done)\n total_reward += reward\n state = next_state\n \n \n \n if self.buffer.size() >= batch_size:\n self.replay()\n self.target_update()\n if self.env.score > self.max_score_now:\n self.max_score_now = self.env.score\n for i in range(len(self.env.pannel)):\n print(self.env.pannel[i])\n print(\"Total Steps\",self.env.total_steps,\"Score\",self.env.score,\"Max Score\",self.max_score_now)\n print('EP{} EpisodeReward={}'.format(ep, total_reward))\n print(\"===========================================================\")\n #wandb.log({'Reward': total_reward})\n\n\ndef main():\n \n env = tetris.Tertris(10,20)\n agent = Agent(env)\n agent.train(max_episodes=100000)\n\nif __name__ == \"__main__\":\n main()" ]
[ [ "tensorflow.keras.models.Sequential", "tensorflow.keras.optimizers.Adam", "numpy.reshape", "numpy.argmax", "numpy.random.random", "tensorflow.keras.layers.Dense", "numpy.array" ] ]
rocketbot-cl/recognition
[ "cca8a87070ccaca3a26e37345c36ab1bf836e258" ]
[ "libs/imutils/feature/rootsift.py" ]
[ "# import the necessary packages\r\nfrom __future__ import absolute_import\r\nimport numpy as np\r\nimport cv2\r\nfrom ..convenience import is_cv2\r\n\r\nclass RootSIFT:\r\n\tdef __init__(self):\r\n\t\t# initialize the SIFT feature extractor for OpenCV 2.4\r\n\t\tif is_cv2():\r\n\t\t\tself.extractor = cv2.DescriptorExtractor_create(\"SIFT\")\r\n\r\n\t\t# otherwise initialize the SIFT feature extractor for OpenCV 3+\r\n\t\telse:\r\n\t\t\tself.extractor = cv2.xfeatures2d.SIFT_create()\r\n\r\n\tdef compute(self, image, kps, eps=1e-7):\r\n\t\t# compute SIFT descriptors\r\n\t\t(kps, descs) = self.extractor.compute(image, kps)\r\n\r\n\t\t# if there are no keypoints or descriptors, return an empty tuple\r\n\t\tif len(kps) == 0:\r\n\t\t\treturn ([], None)\r\n\r\n\t\t# apply the Hellinger kernel by first L1-normalizing and taking the\r\n\t\t# square-root\r\n\t\tdescs /= (descs.sum(axis=1, keepdims=True) + eps)\r\n\t\tdescs = np.sqrt(descs)\r\n\r\n\t\t# return a tuple of the keypoints and descriptors\r\n\t\treturn (kps, descs)" ]
[ [ "numpy.sqrt" ] ]
Purple-PI/rlstructures
[ "9b201b083715bbda2f3534b010c84e11dfc0a1c7" ]
[ "rlstructures/deprecated/batchers/buffers.py" ]
[ "#\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\n\nimport torch\nimport torch.multiprocessing as mp\nfrom rlstructures import TemporalDictTensor, DictTensor\n\n\nclass Buffer:\n def get_free_slots(self, k):\n raise NotImplementedError\n\n def set_free_slots(self, s):\n raise NotImplementedError\n\n def write(self, slots, variables):\n raise NotImplementedError\n\n def close(self):\n raise NotImplementedError\n\n def get_trajectories(self, trajectories, erase=True):\n raise NotImplementedError\n\n\nclass LocalBuffer(Buffer):\n \"\"\"\n Defines a shared buffer to store trajectories / transitions\n The buffer is structured as nslots of size s_slots for each possible variable\n \"\"\"\n\n def __init__(\n self,\n n_slots=None,\n s_slots=None,\n specs_agent_state=None,\n specs_agent_output=None,\n specs_environment=None,\n device=torch.device(\"cpu\"),\n ):\n \"\"\"\n Init a new buffer\n\n Args:\n n_slots (int): the number of slots\n s_slots (int): the size of each slot (temporal dimension)\n specs (dict): The description of the variable to store in the buffer\n \"\"\"\n self._device = device\n self.buffers = {}\n self.n_slots = n_slots\n self.s_slots = s_slots\n\n # Creation of the storage buffers\n nspecs_agent_state = {\"_\" + k: specs_agent_state[k] for k in specs_agent_state}\n nspecs_env = {\"_\" + k: specs_environment[k] for k in specs_environment}\n specs = {\n **specs_agent_state,\n **specs_agent_output,\n **specs_environment,\n **nspecs_agent_state,\n **nspecs_env,\n \"position_in_slot\": {\"size\": torch.Size([]), \"dtype\": torch.int64},\n }\n\n for n in specs:\n size = (n_slots, s_slots) + specs[n][\"size\"]\n print(\n \"Creating buffer for '\"\n + n\n + \"' of size \"\n + str(size)\n + \" and type \"\n + str(specs[n][\"dtype\"])\n )\n assert not n in self.buffers, \"Same key is used by the agent and the env\"\n self.buffers[n] = (\n torch.zeros(size, dtype=specs[n][\"dtype\"])\n .to(self._device)\n .share_memory_()\n )\n self.position_in_slot = (\n torch.zeros(n_slots).to(self._device).long().share_memory_()\n )\n self._free_slots_queue = mp.Queue()\n self._free_slots_queue.cancel_join_thread()\n for i in range(n_slots):\n self._free_slots_queue.put(i, block=True)\n self._full_slots_queue = mp.Queue()\n self._full_slots_queue.cancel_join_thread()\n\n def device(self):\n return self._device\n\n def get_free_slots(self, k):\n \"\"\"\n Returns k available slots. Wait until enough slots are free\n \"\"\"\n assert k > 0\n x = [self._free_slots_queue.get() for i in range(k)]\n for i in x:\n self.position_in_slot[i] = 0\n return x\n\n def set_free_slots(self, s):\n \"\"\"\n Tells the buffer that it can reuse the given slots\n :param s may be one slot (int) or multiple slots (list of int)\n \"\"\"\n assert not s is None\n if isinstance(s, int):\n self._free_slots_queue.put(s)\n else:\n for ss in s:\n self._free_slots_queue.put(ss)\n # logging.getLogger(\"buffer\").debug(\"SET FREE \" + str(s))\n\n def write(self, slots, variables):\n if not variables.device() == self._device:\n variables = variables.to(self._device)\n\n slots = torch.tensor(slots).to(self._device)\n assert variables.n_elems() == len(slots)\n positions = self.position_in_slot[slots]\n a = torch.arange(len(slots)).to(self._device)\n for n in variables.keys():\n # assert variables[n].size()[0] == 1\n # print(self.buffers[n][slots].size())\n self.buffers[n][slots, positions] = variables[n][a].detach()\n self.position_in_slot[slots] += 1\n\n def is_slot_full(self, slot):\n \"\"\"\n Returns True of a slot is full\n \"\"\"\n return self.position_in_slot[slot] == self.s_slots\n\n def get_single(self, slots, position):\n assert isinstance(slots, list)\n assert isinstance(slots[0], int)\n idx = torch.tensor(slots).to(self._device).long()\n d = {k: self.buffers[k][idx, position] for k in self.buffers}\n return DictTensor(d)\n\n def close(self):\n \"\"\"\n Close the buffer\n \"\"\"\n self._free_slots_queue.close()\n self._full_slots_queue.close()\n\n def get_single_slots(self, slots, erase=True):\n assert isinstance(slots, list)\n assert isinstance(slots[0], int)\n idx = torch.tensor(slots).to(self._device).long()\n lengths = self.position_in_slot[idx]\n ml = lengths.max().item()\n v = {k: self.buffers[k][idx, :ml].clone() for k in self.buffers}\n if erase:\n self.set_free_slots(slots)\n return TemporalDictTensor(v, lengths)\n\n def get_multiple_slots(self, trajectories, erase=True):\n \"\"\"\n Return the concatenation of multiple slots. This function is not well optimized and could be fasten\n \"\"\"\n assert isinstance(trajectories, list) or isinstance(trajectories, tuple)\n assert isinstance(trajectories[0], list)\n assert isinstance(trajectories[0][0], int)\n # 1: Unify the size of all trajectories....\n max_l = 0\n for traj in trajectories:\n max_l = max(max_l, len(traj))\n ntrajectories = []\n for traj in trajectories:\n while not len(traj) == max_l:\n traj.append(None)\n ntrajectories.append(traj)\n\n # 2: Copy the content\n length = torch.zeros(len(ntrajectories)).to(self._device).long()\n tensors = []\n for k in range(max_l):\n idxs = [traj[k] for traj in ntrajectories]\n nidxs = []\n for _id in idxs:\n if _id is None:\n nidxs.append(0)\n else:\n nidxs.append(_id)\n nidxs = torch.tensor(nidxs).to(self._device)\n v = {k: self.buffers[k][nidxs] for k in self.buffers}\n pis = self.position_in_slot[nidxs]\n # Check that slots are full\n if k < max_l - 1:\n for i in range(len(pis)):\n if not ntrajectories[i][k + 1] is None:\n assert pis[i] == self.s_slots\n\n for i in range(len(pis)):\n if not ntrajectories[i][k] is None:\n length[i] = length[i] + pis[i]\n\n tensors.append(v)\n ftrajectories = {\n k: torch.cat([t[k] for t in tensors], dim=1) for k in self.buffers\n }\n if erase:\n for k in trajectories:\n for kk in k:\n if not kk is None:\n self.set_free_slots(kk)\n\n return TemporalDictTensor(ftrajectories, length).shorten()\n" ]
[ [ "torch.Size", "torch.tensor", "torch.multiprocessing.Queue", "torch.zeros", "torch.device", "torch.cat" ] ]
pvaneck/tfjs-converter
[ "074ed3252fab3d913679d5415a5e530efd4966b3" ]
[ "python/tensorflowjs/converters/keras_h5_conversion_test.py" ]
[ "# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# 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\"\"\"Unit tests for artifact conversion to and from Python Keras.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport os\nimport shutil\nimport tempfile\nimport unittest\n\nimport h5py\nimport keras\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflowjs.converters import keras_h5_conversion as conversion\n\n\nclass ConvertH5WeightsTest(unittest.TestCase):\n\n def setUp(self):\n self._tmp_dir = tempfile.mkdtemp()\n super(ConvertH5WeightsTest, self).setUp()\n\n def tearDown(self):\n if os.path.isdir(self._tmp_dir):\n shutil.rmtree(self._tmp_dir)\n super(ConvertH5WeightsTest, self).tearDown()\n\n def testConvertWeightsFromSimpleModelNoSplitByLayer(self):\n input_tensor = keras.layers.Input((3,))\n dense1 = keras.layers.Dense(\n 4, use_bias=True, kernel_initializer='ones', bias_initializer='zeros',\n name='MyDense10')(input_tensor)\n output = keras.layers.Dense(\n 2, use_bias=False, kernel_initializer='ones', name='MyDense20')(dense1)\n model = keras.models.Model(inputs=[input_tensor], outputs=[output])\n h5_path = os.path.join(self._tmp_dir, 'MyModel.h5')\n model.save_weights(h5_path)\n\n # Load the saved weights as a JSON string.\n groups = conversion.h5_weights_to_tfjs_format(h5py.File(h5_path))\n\n # Check the loaded weights.\n # Due to the default `split_by_layer=True`, there should be only one weight\n # group.\n self.assertEqual(1, len(groups))\n self.assertEqual(3, len(groups[0]))\n kernel1 = groups[0][0]\n self.assertEqual('MyDense10/kernel', kernel1['name'])\n self.assertEqual('float32', kernel1['data'].dtype)\n self.assertEqual((3, 4), kernel1['data'].shape)\n self.assertTrue(np.allclose(np.ones([3, 4]), kernel1['data']))\n bias1 = groups[0][1]\n self.assertEqual('MyDense10/bias', bias1['name'])\n self.assertEqual('float32', bias1['data'].dtype)\n self.assertEqual((4,), bias1['data'].shape)\n self.assertTrue(np.allclose(np.zeros([4]), bias1['data']))\n kernel2 = groups[0][2]\n self.assertEqual('MyDense20/kernel', kernel2['name'])\n self.assertEqual('float32', kernel2['data'].dtype)\n self.assertEqual((4, 2), kernel2['data'].shape)\n self.assertTrue(np.allclose(np.ones([4, 2]), kernel2['data']))\n\n def testConvertWeightsFromSimpleModelSplitByLayer(self):\n input_tensor = keras.layers.Input((3,))\n dense1 = keras.layers.Dense(\n 4, use_bias=True, kernel_initializer='ones', bias_initializer='zeros',\n name='MyDense30')(input_tensor)\n output = keras.layers.Dense(\n 2, use_bias=False, kernel_initializer='ones', name='MyDense40')(dense1)\n model = keras.models.Model(inputs=[input_tensor], outputs=[output])\n h5_path = os.path.join(self._tmp_dir, 'MyModel.h5')\n model.save_weights(h5_path)\n\n # Load the saved weights as a JSON string.\n groups = conversion.h5_weights_to_tfjs_format(h5py.File(h5_path),\n split_by_layer=True)\n\n # Check the loaded weights.\n # Due to `split_by_layer=True` and the fact that the model has two layers,\n # there should be two weight groups.\n self.assertEqual(2, len(groups))\n self.assertEqual(2, len(groups[0]))\n kernel1 = groups[0][0]\n self.assertEqual('MyDense30/kernel', kernel1['name'])\n self.assertEqual('float32', kernel1['data'].dtype)\n self.assertEqual((3, 4), kernel1['data'].shape)\n self.assertTrue(np.allclose(np.ones([3, 4]), kernel1['data']))\n bias1 = groups[0][1]\n self.assertEqual('MyDense30/bias', bias1['name'])\n self.assertEqual('float32', bias1['data'].dtype)\n self.assertEqual((4,), bias1['data'].shape)\n self.assertTrue(np.allclose(np.zeros([4]), bias1['data']))\n\n self.assertEqual(1, len(groups[1]))\n kernel2 = groups[1][0]\n self.assertEqual('MyDense40/kernel', kernel2['name'])\n self.assertEqual('float32', kernel2['data'].dtype)\n self.assertEqual((4, 2), kernel2['data'].shape)\n self.assertTrue(np.allclose(np.ones([4, 2]), kernel2['data']))\n\n def testConvertModelWithNestedLayerNames(self):\n model = keras.Sequential()\n\n # Add a layer with a nested layer name, i.e., a layer name with slash(es)\n # in it.\n model.add(keras.layers.Dense(2, input_shape=[12], name='dense'))\n model.add(keras.layers.Dense(8, name='foo/dense'))\n model.add(keras.layers.Dense(4, name='foo/bar/dense'))\n tfjs_path = os.path.join(self._tmp_dir, 'nested_layer_names_model')\n conversion.save_keras_model(model, tfjs_path)\n\n # Check model.json and weights manifest.\n with open(os.path.join(tfjs_path, 'model.json'), 'rt') as f:\n model_json = json.load(f)\n self.assertTrue(model_json['modelTopology'])\n weights_manifest = model_json['weightsManifest']\n weight_shapes = dict()\n for group in weights_manifest:\n for weight in group['weights']:\n weight_shapes[weight['name']] = weight['shape']\n self.assertEqual(\n sorted(['dense/kernel', 'dense/bias', 'foo/dense/kernel',\n 'foo/dense/bias', 'foo/bar/dense/kernel',\n 'foo/bar/dense/bias']),\n sorted(list(weight_shapes.keys())))\n self.assertEqual([12, 2], weight_shapes['dense/kernel'])\n self.assertEqual([2], weight_shapes['dense/bias'])\n self.assertEqual([2, 8], weight_shapes['foo/dense/kernel'])\n self.assertEqual([8], weight_shapes['foo/dense/bias'])\n self.assertEqual([8, 4], weight_shapes['foo/bar/dense/kernel'])\n self.assertEqual([4], weight_shapes['foo/bar/dense/bias'])\n\n def testConvertMergedModelFromSimpleModelNoSplitByLayer(self):\n input_tensor = keras.layers.Input((3,))\n dense1 = keras.layers.Dense(\n 4, use_bias=True, kernel_initializer='ones', bias_initializer='zeros',\n name='MergedDense10')(input_tensor)\n output = keras.layers.Dense(\n 2, use_bias=False,\n kernel_initializer='ones', name='MergedDense20')(dense1)\n model = keras.models.Model(inputs=[input_tensor], outputs=[output])\n h5_path = os.path.join(self._tmp_dir, 'MyModelMerged.h5')\n model.save(h5_path)\n config_json = json.loads(model.to_json(), encoding='utf8')\n\n # Load the saved weights as a JSON string.\n out, groups = conversion.h5_merged_saved_model_to_tfjs_format(\n h5py.File(h5_path))\n saved_topology = out['model_config']\n\n # check the model topology was stored\n self.assertEqual(config_json['class_name'], saved_topology['class_name'])\n self.assertEqual(config_json['config'], saved_topology['config'])\n\n # Check the loaded weights.\n # By default, all weights of the model ought to be put in the same group.\n self.assertEqual(1, len(groups))\n\n self.assertEqual(keras.__version__, out['keras_version'])\n self.assertEqual('tensorflow', out['backend'])\n weight_group = groups[0]\n self.assertEqual(3, len(weight_group))\n kernel1 = weight_group[0]\n self.assertEqual('MergedDense10/kernel', kernel1['name'])\n self.assertEqual('float32', kernel1['data'].dtype)\n self.assertEqual((3, 4), kernel1['data'].shape)\n self.assertTrue(np.allclose(np.ones([3, 4]), kernel1['data']))\n bias1 = weight_group[1]\n self.assertEqual('MergedDense10/bias', bias1['name'])\n self.assertEqual('float32', bias1['data'].dtype)\n self.assertEqual((4,), bias1['data'].shape)\n self.assertTrue(np.allclose(np.zeros([4]), bias1['data']))\n kernel2 = weight_group[2]\n self.assertEqual('MergedDense20/kernel', kernel2['name'])\n self.assertEqual('float32', kernel2['data'].dtype)\n self.assertEqual((4, 2), kernel2['data'].shape)\n self.assertTrue(np.allclose(np.ones([4, 2]), kernel2['data']))\n\n def testConvertMergedModelFromSimpleModelSplitByLayer(self):\n input_tensor = keras.layers.Input((3,))\n dense1 = keras.layers.Dense(\n 4, use_bias=True, kernel_initializer='ones', bias_initializer='zeros',\n name='MergedDense30')(input_tensor)\n output = keras.layers.Dense(\n 2, use_bias=False,\n kernel_initializer='ones', name='MergedDense40')(dense1)\n model = keras.models.Model(inputs=[input_tensor], outputs=[output])\n h5_path = os.path.join(self._tmp_dir, 'MyModelMerged.h5')\n model.save(h5_path)\n config_json = json.loads(model.to_json(), encoding='utf8')\n\n # Load the saved weights as a JSON string.\n out, groups = conversion.h5_merged_saved_model_to_tfjs_format(\n h5py.File(h5_path), split_by_layer=True)\n saved_topology = out['model_config']\n\n # check the model topology was stored\n self.assertEqual(config_json['class_name'], saved_topology['class_name'])\n self.assertEqual(config_json['config'], saved_topology['config'])\n\n # Check the loaded weights.\n # Due to `split_by_layer=True`, there ought to be two weigth groups,\n # because the model has two layers.\n self.assertEqual(2, len(groups))\n\n self.assertEqual(keras.__version__, out['keras_version'])\n self.assertEqual('tensorflow', out['backend'])\n self.assertEqual(2, len(groups[0]))\n kernel1 = groups[0][0]\n self.assertEqual('MergedDense30/kernel', kernel1['name'])\n self.assertEqual('float32', kernel1['data'].dtype)\n self.assertEqual((3, 4), kernel1['data'].shape)\n self.assertTrue(np.allclose(np.ones([3, 4]), kernel1['data']))\n bias1 = groups[0][1]\n self.assertEqual('MergedDense30/bias', bias1['name'])\n self.assertEqual('float32', bias1['data'].dtype)\n self.assertEqual((4,), bias1['data'].shape)\n self.assertTrue(np.allclose(np.zeros([4]), bias1['data']))\n self.assertEqual(1, len(groups[1]))\n kernel2 = groups[1][0]\n self.assertEqual('MergedDense40/kernel', kernel2['name'])\n self.assertEqual('float32', kernel2['data'].dtype)\n self.assertEqual((4, 2), kernel2['data'].shape)\n self.assertTrue(np.allclose(np.ones([4, 2]), kernel2['data']))\n\n def testConvertWeightsFromSequentialModelNoSplitByLayer(self):\n sequential_model = keras.models.Sequential([\n keras.layers.Dense(\n 3, input_shape=(2,), use_bias=True, kernel_initializer='ones',\n name='Dense10'),\n keras.layers.Dense(\n 1, use_bias=False, kernel_initializer='ones', name='Dense20')])\n h5_path = os.path.join(self._tmp_dir, 'SequentialModel.h5')\n sequential_model.save_weights(h5_path)\n\n # Load the saved weights as a JSON string.\n groups = conversion.h5_weights_to_tfjs_format(h5py.File(h5_path))\n\n # Check the loaded weights.\n # Due to the default `split_by_layer=False`, there should be only one weight\n # group.\n self.assertEqual(1, len(groups))\n self.assertEqual(3, len(groups[0]))\n kernel1 = groups[0][0]\n self.assertEqual('Dense10/kernel', kernel1['name'])\n self.assertEqual('float32', kernel1['data'].dtype)\n self.assertEqual((2, 3), kernel1['data'].shape)\n self.assertTrue(np.allclose(np.ones([2, 3]).tolist(), kernel1['data']))\n bias1 = groups[0][1]\n self.assertEqual('Dense10/bias', bias1['name'])\n self.assertEqual('float32', bias1['data'].dtype)\n self.assertEqual((3,), bias1['data'].shape)\n self.assertTrue(np.allclose(np.zeros([3]).tolist(), bias1['data']))\n kernel2 = groups[0][2]\n self.assertEqual('Dense20/kernel', kernel2['name'])\n self.assertEqual('float32', kernel2['data'].dtype)\n self.assertEqual((3, 1), kernel2['data'].shape)\n self.assertTrue(np.allclose(np.ones([3, 1]).tolist(), kernel2['data']))\n\n def testConvertWeightsFromSequentialModelSplitByLayer(self):\n sequential_model = keras.models.Sequential([\n keras.layers.Dense(\n 3, input_shape=(2,), use_bias=True, kernel_initializer='ones',\n name='Dense30'),\n keras.layers.Dense(\n 1, use_bias=False, kernel_initializer='ones', name='Dense40')])\n h5_path = os.path.join(self._tmp_dir, 'SequentialModel.h5')\n sequential_model.save_weights(h5_path)\n\n # Load the saved weights as a JSON string.\n groups = conversion.h5_weights_to_tfjs_format(h5py.File(h5_path),\n split_by_layer=True)\n\n # Check the loaded weights.\n # Due to the default `split_by_layer=True`, there should be two weight\n # gropus, because the model has two layers.\n self.assertEqual(2, len(groups))\n self.assertEqual(2, len(groups[0]))\n kernel1 = groups[0][0]\n self.assertEqual('Dense30/kernel', kernel1['name'])\n self.assertEqual('float32', kernel1['data'].dtype)\n self.assertEqual((2, 3), kernel1['data'].shape)\n self.assertTrue(np.allclose(np.ones([2, 3]).tolist(), kernel1['data']))\n bias1 = groups[0][1]\n self.assertEqual('Dense30/bias', bias1['name'])\n self.assertEqual('float32', bias1['data'].dtype)\n self.assertEqual((3,), bias1['data'].shape)\n self.assertTrue(np.allclose(np.zeros([3]).tolist(), bias1['data']))\n\n self.assertEqual(1, len(groups[1]))\n kernel2 = groups[1][0]\n self.assertEqual('Dense40/kernel', kernel2['name'])\n self.assertEqual('float32', kernel2['data'].dtype)\n self.assertEqual((3, 1), kernel2['data'].shape)\n self.assertTrue(np.allclose(np.ones([3, 1]).tolist(), kernel2['data']))\n\n def testSaveModelSucceedsForNonSequentialModel(self):\n t_input = keras.Input([2])\n dense_layer = keras.layers.Dense(3)\n t_output = dense_layer(t_input)\n model = keras.Model(t_input, t_output)\n conversion.save_keras_model(model, self._tmp_dir)\n\n # Verify the content of the artifacts output directory.\n self.assertTrue(\n os.path.isfile(os.path.join(self._tmp_dir, 'group1-shard1of1.bin')))\n model_json = json.load(\n open(os.path.join(self._tmp_dir, 'model.json'), 'rt'))\n\n topology_json = model_json['modelTopology']\n self.assertIn('keras_version', topology_json)\n self.assertIn('backend', topology_json)\n self.assertIn('model_config', topology_json)\n\n weights_manifest = model_json['weightsManifest']\n self.assertTrue(isinstance(weights_manifest, list))\n self.assertEqual(1, len(weights_manifest))\n self.assertIn('paths', weights_manifest[0])\n\n def testSaveModelSucceedsForTfKerasNonSequentialModel(self):\n t_input = tf.keras.Input([2])\n dense_layer = tf.keras.layers.Dense(3)\n t_output = dense_layer(t_input)\n model = tf.keras.Model(t_input, t_output)\n\n # `tf.keras.Model`s must be compiled before they can be saved.\n model.compile(loss='mean_squared_error', optimizer='sgd')\n\n conversion.save_keras_model(model, self._tmp_dir)\n\n # Verify the content of the artifacts output directory.\n self.assertTrue(\n os.path.isfile(os.path.join(self._tmp_dir, 'group1-shard1of1.bin')))\n model_json = json.load(\n open(os.path.join(self._tmp_dir, 'model.json'), 'rt'))\n\n topology_json = model_json['modelTopology']\n self.assertIn('keras_version', topology_json)\n self.assertIn('backend', topology_json)\n self.assertIn('model_config', topology_json)\n\n weights_manifest = model_json['weightsManifest']\n self.assertTrue(isinstance(weights_manifest, list))\n self.assertEqual(1, len(weights_manifest))\n self.assertIn('paths', weights_manifest[0])\n\n def testSaveModelSucceedsForNestedKerasModel(self):\n inner_model = keras.Sequential([\n keras.layers.Dense(4, input_shape=[3], activation='relu'),\n keras.layers.Dense(3, activation='tanh')])\n outer_model = keras.Sequential()\n outer_model.add(inner_model)\n outer_model.add(keras.layers.Dense(1, activation='sigmoid'))\n\n conversion.save_keras_model(outer_model, self._tmp_dir)\n\n # Verify the content of the artifacts output directory.\n self.assertTrue(\n os.path.isfile(os.path.join(self._tmp_dir, 'group1-shard1of1.bin')))\n model_json = json.load(\n open(os.path.join(self._tmp_dir, 'model.json'), 'rt'))\n\n topology_json = model_json['modelTopology']\n self.assertIn('keras_version', topology_json)\n self.assertIn('backend', topology_json)\n self.assertIn('model_config', topology_json)\n\n # Verify that all the layers' weights are present.\n weights_manifest = model_json['weightsManifest']\n self.assertTrue(isinstance(weights_manifest, list))\n weight_entries = []\n for group in weights_manifest:\n weight_entries.extend(group['weights'])\n self.assertEqual(6, len(weight_entries))\n\n def testSaveModelSucceedsForTfKerasSequentialModel(self):\n model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=[2])])\n\n # `tf.keras.Model`s must be compiled before they can be saved.\n model.compile(loss='mean_squared_error', optimizer='sgd')\n\n conversion.save_keras_model(model, self._tmp_dir)\n\n # Verify the content of the artifacts output directory.\n self.assertTrue(\n os.path.isfile(os.path.join(self._tmp_dir, 'group1-shard1of1.bin')))\n model_json = json.load(\n open(os.path.join(self._tmp_dir, 'model.json'), 'rt'))\n\n topology_json = model_json['modelTopology']\n self.assertIn('keras_version', topology_json)\n self.assertIn('backend', topology_json)\n self.assertIn('model_config', topology_json)\n\n weights_manifest = model_json['weightsManifest']\n self.assertTrue(isinstance(weights_manifest, list))\n self.assertEqual(1, len(weights_manifest))\n self.assertIn('paths', weights_manifest[0])\n\n def testSavedModelSucceedsForExistingDirAndSequential(self):\n artifacts_dir = os.path.join(self._tmp_dir, 'artifacts')\n os.makedirs(artifacts_dir)\n model = keras.Sequential()\n model.add(keras.layers.Dense(3, input_shape=[2]))\n conversion.save_keras_model(model, artifacts_dir)\n\n # Verify the content of the artifacts output directory.\n self.assertTrue(\n os.path.isfile(os.path.join(artifacts_dir, 'group1-shard1of1.bin')))\n model_json = json.load(\n open(os.path.join(artifacts_dir, 'model.json'), 'rt'))\n\n topology_json = model_json['modelTopology']\n self.assertIn('keras_version', topology_json)\n self.assertIn('backend', topology_json)\n self.assertIn('model_config', topology_json)\n\n weights_manifest = model_json['weightsManifest']\n self.assertTrue(isinstance(weights_manifest, list))\n self.assertEqual(1, len(weights_manifest))\n self.assertIn('paths', weights_manifest[0])\n\n def testSavedModelRaisesErrorIfArtifactsDirExistsAsAFile(self):\n artifacts_dir = os.path.join(self._tmp_dir, 'artifacts')\n with open(artifacts_dir, 'wt') as f:\n f.write('foo\\n')\n t_input = keras.Input([2])\n dense_layer = keras.layers.Dense(3)\n t_output = dense_layer(t_input)\n model = keras.Model(t_input, t_output)\n with self.assertRaisesRegexp( # pylint: disable=deprecated-method\n ValueError, r'already exists as a file'):\n conversion.save_keras_model(model, artifacts_dir)\n\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.ones", "numpy.zeros", "tensorflow.keras.Model", "tensorflow.keras.layers.Dense", "tensorflow.keras.Input" ] ]
wangxr0526/RetroPrime
[ "a765b670b72fbfd512d0d437da8f27a95f9f0554", "a765b670b72fbfd512d0d437da8f27a95f9f0554" ]
[ "retroprime/data_process/clean_uspto.py", "retroprime/transformer_model/onmt/modules/position_ffn_h.py" ]
[ "from __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport argparse\n\nimport numpy as np\nimport random\nimport csv\nimport os\nimport sys\nimport re\nfrom tqdm import tqdm\nfrom rdkit import Chem\nimport pickle as cp\n\n\ndef get_rxn_smiles(prod, reactants):\n prod_smi = Chem.MolToSmiles(prod, True)\n\n # Get rid of reactants when they don't contribute to this prod\n prod_maps = set(re.findall('\\:([[0-9]+)\\]', prod_smi))\n reactants_smi_list = []\n for mol in reactants:\n if mol is None:\n continue\n used = False\n for a in mol.GetAtoms():\n if a.HasProp('molAtomMapNumber'):\n if a.GetProp('molAtomMapNumber') in prod_maps:\n used = True \n else:\n a.ClearProp('molAtomMapNumber')\n if used:\n reactants_smi_list.append(Chem.MolToSmiles(mol, True))\n\n reactants_smi = '.'.join(reactants_smi_list)\n return '{}>>{}'.format(reactants_smi, prod_smi)\n\n\nif __name__ == '__main__':\n seed = 19260817\n np.random.seed(seed)\n random.seed(seed)\n opt = argparse.ArgumentParser()\n opt.add_argument('-fname', default='../../databox/uspto_full/1976_Sep2016_USPTOgrants_smiles.rsmi')\n args, _ = opt.parse_known_args()\n fname = args.fname\n split_mode = 'single' # single or multi\n\n pt = re.compile(r':(\\d+)]')\n cnt = 0\n clean_list = []\n set_rxn = set()\n num_single = 0\n num_multi = 0\n bad_mapping = 0\n bad_prod = 0\n missing_map = 0\n raw_num = 0\n with open(fname, 'r') as f:\n reader = csv.reader(f, delimiter='\\t')\n header = next(reader)\n print(header)\n pbar = tqdm(reader)\n bad_rxn = 0\n for row in pbar:\n rxn_smiles = row[header.index('ReactionSmiles')]\n all_reactants, reagents, prods = rxn_smiles.split('>')\n all_reactants = all_reactants.split()[0] # remove ' |f:1...'\n prods = prods.split()[0] # remove ' |f:1...'\n if '.' in prods:\n num_multi += 1\n else:\n num_single += 1\n if split_mode == 'single' and '.' in prods: # multiple prods\n continue\n rids = ','.join(sorted(re.findall(pt, all_reactants)))\n pids = ','.join(sorted(re.findall(pt, prods)))\n if rids != pids: # mapping is not 1:1\n bad_mapping += 1\n continue\n reactants = [Chem.MolFromSmiles(smi) for smi in all_reactants.split('.')]\n \n for sub_prod in prods.split('.'):\n mol_prod = Chem.MolFromSmiles(sub_prod)\n if mol_prod is None: # rdkit is not able to parse the product\n bad_prod += 1\n continue\n # Make sure all have atom mapping\n if not all([a.HasProp('molAtomMapNumber') for a in mol_prod.GetAtoms()]):\n missing_map += 1\n continue\n \n raw_num += 1\n rxn_smiles = get_rxn_smiles(mol_prod, reactants)\n if not rxn_smiles in set_rxn:\n clean_list.append((row[header.index('PatentNumber')], rxn_smiles))\n set_rxn.add(rxn_smiles)\n pbar.set_description('select: %d, dup: %d' % (len(clean_list), raw_num))\n print('# clean', len(clean_list))\n print('single', num_single, 'multi', num_multi)\n print('bad mapping', bad_mapping)\n print('bad prod', bad_prod)\n print('missing map', missing_map)\n print('raw extracted', raw_num)\n \n random.shuffle(clean_list)\n\n num_val = num_test = int(len(clean_list) * 0.1)\n\n out_folder = '../../databox/uspto_full/'\n for phase in ['val', 'test', 'train']:\n fout = os.path.join(out_folder, 'raw_%s.csv' % phase)\n with open(fout, 'w') as f:\n writer = csv.writer(f)\n writer.writerow(['id', 'reactants>reagents>production'])\n\n if phase == 'val':\n r = range(num_val)\n elif phase == 'test':\n r = range(num_val, num_val + num_test)\n else:\n r = range(num_val + num_test, len(clean_list))\n for i in r:\n rxn_smiles = clean_list[i][1].split('>')\n result = []\n for r in rxn_smiles:\n if len(r.strip()):\n r = r.split()[0]\n result.append(r)\n rxn_smiles = '>'.join(result)\n writer.writerow([clean_list[i][0], rxn_smiles])\n", "\"\"\"\nPosition feed-forward network from \"Attention is All You Need\"\n\"\"\"\n\nimport torch.nn as nn\n\nimport onmt\n\nfrom onmt.modules.hyperbolic import cLinear\n\n\nclass PositionwiseFeedForward_h(nn.Module):\n \"\"\" A two-layer Feed-Forward-Network with residual layer norm.\n\n Args:\n d_model (int): the size of input for the first-layer of the FFN.\n d_ff (int): the hidden layer size of the second-layer\n of the FNN.\n dropout (float): dropout probability(0-1.0).\n \"\"\"\n\n def __init__(self, d_model, d_ff, c, dropout=0.1):\n super(PositionwiseFeedForward_h, self).__init__()\n # self.w_1 = nn.Linear(d_model, d_ff)\n # self.w_2 = nn.Linear(d_ff, d_model)\n self.w_1 = cLinear(d_model, d_ff, c)\n self.w_2 = cLinear(d_ff, d_model, c)\n self.layer_norm = onmt.modules.LayerNorm(d_model)\n self.dropout_1 = nn.Dropout(dropout)\n self.relu = nn.ReLU()\n self.dropout_2 = nn.Dropout(dropout)\n\n def forward(self, x):\n \"\"\"\n Layer definition.\n\n Args:\n input: [ batch_size, input_len, model_dim ]\n\n\n Returns:\n output: [ batch_size, input_len, model_dim ]\n \"\"\"\n inter = self.dropout_1(self.relu(self.w_1(self.layer_norm(x))))\n output = self.dropout_2(self.w_2(inter))\n return output + x\n" ]
[ [ "numpy.random.seed" ], [ "torch.nn.ReLU", "torch.nn.Dropout" ] ]
liuchangtai1996/MLIP
[ "ec217d592b8c51e98729d8c2b2abe1b2d918e14f" ]
[ "code/resnet_approach/prepare.py" ]
[ "import numpy as np\r\nimport cv2\r\n\r\ndef load_batch(ls,od,data_path,batch_size,which_batch):\r\n image_list=[]\r\n for i in range(which_batch*batch_size,(which_batch+1)*batch_size):\r\n image=[]\r\n image.append(cv2.imread(data_path+ls[od[i]]+'_red.png',0))\r\n image.append(cv2.imread(data_path+ls[od[i]]+'_green.png',0))\r\n image.append(cv2.imread(data_path+ls[od[i]]+'_blue.png',0))\r\n image.append(cv2.imread(data_path+ls[od[i]]+'_yellow.png',0))\r\n image=np.asarray(image).T\r\n image_list.append(image)\r\n image_list=np.asarray(image_list)\r\n return image_list\r\n\r\ndef normalize(image_list):\r\n ma=max(image_list.flatten())\r\n mi=min(image_list.flatten())\r\n mean = float((ma+mi)/2.0)\r\n output = (image_list-mean)/(ma-mean)\r\n return output\r\n" ]
[ [ "numpy.asarray" ] ]
19tony97/Autonomous_vheicle_drivingProject
[ "3938b132e11f7705bff2c2004ee80e1f87438565" ]
[ "behavioural_planner.py" ]
[ "#!/usr/bin/env python3\n\nimport numpy as np\nimport math\n\nfrom obstacle_detection import check_for_obs\n\n# State machine states\nFOLLOW_LANE = 0\nDECELERATE_TO_STOP = 1\nSTAY_STOPPED = 2\n# Stop speed threshold\nSTOP_THRESHOLD = 0.02\n# Number of cycles before moving from stop sign.\n\nSEMAPHORE = 3\n\nSTOP_COUNTS = 10\n\nclass BehaviouralPlanner:\n def __init__(self, lookahead, lead_vehicle_lookahead, traffic_light_state):\n self._lookahead = lookahead\n self._follow_lead_vehicle_lookahead = lead_vehicle_lookahead\n self._state = FOLLOW_LANE\n self._follow_lead_vehicle = False\n self._obstacle_on_lane = False\n self._goal_state = [0.0, 0.0, 0.0]\n self._goal_index = 0\n self._stop_count = 0\n self._lookahead_collision_index = 0\n self.traffic_light_state = traffic_light_state\n def set_lookahead(self, lookahead):\n self._lookahead = lookahead\n\n # Handles state transitions and computes the goal state.\n def transition_state(self, waypoints, ego_state, closed_loop_speed, camera_data, potential_obs):\n \"\"\"Handles state transitions and computes the goal state.\n\n args:\n waypoints: current waypoints to track (global frame).\n length and speed in m and m/s.\n (includes speed to track at each x,y location.)\n format: [[x0, y0, v0],\n [x1, y1, v1],\n ...\n [xn, yn, vn]]\n example:\n waypoints[2][1]:\n returns the 3rd waypoint's y position\n\n waypoints[5]:\n returns [x5, y5, v5] (6th waypoint)\n ego_state: ego state vector for the vehicle. (global frame)\n format: [ego_x, ego_y, ego_yaw, ego_open_loop_speed]\n ego_x and ego_y : position (m)\n ego_yaw : top-down orientation [-pi to pi]\n ego_open_loop_speed : open loop speed (m/s)\n closed_loop_speed: current (closed-loop) speed for vehicle (m/s)\n variables to set:\n self._goal_index: Goal index for the vehicle to reach\n i.e. waypoints[self._goal_index] gives the goal waypoint\n self._goal_state: Goal state for the vehicle to reach (global frame)\n format: [x_goal, y_goal, v_goal]\n self._state: The current state of the vehicle.\n available states:\n FOLLOW_LANE : Follow the global waypoints (lane).\n DECELERATE_TO_STOP : Decelerate to stop.\n STAY_STOPPED : Stay stopped.\n self._stop_count: Counter used to count the number of cycles which\n the vehicle was in the STAY_STOPPED state so far.\n useful_constants:\n STOP_THRESHOLD : Stop speed threshold (m). The vehicle should fully\n stop when its speed falls within this threshold.\n STOP_COUNTS : Number of cycles (simulation iterations)\n before moving from stop sign.\n \"\"\"\n # In this state, continue tracking the lane by finding the\n # goal index in the waypoint list that is within the lookahead\n # distance. Then, check to see if the waypoint path intersects\n # with any stop lines. If it does, then ensure that the goal\n # state enforces the car to be stopped before the stop line.\n # You should use the get_closest_index(), get_goal_index(), and\n # check_for_stop_signs() helper functions.\n # Make sure that get_closest_index() and get_goal_index() functions are\n # complete, and examine the check_for_stop_signs() function to\n # understand it.\n if self._state == FOLLOW_LANE:\n print(\"FOLLOW_LANE\")\n # First, find the closest index to the ego vehicle.\n update_waypoints(self,waypoints,ego_state)\n\n tl_state = self.traffic_light_state.detect_traffic_light(camera_data)\n #TODO add trafficlight detection and collision_prediction\n # to change from state \"FOLLOW_LANE\" to state \"DECELERATE_TO_STOP\"\n \n\n if check_for_obs(potential_obs, ego_state,is_collision = False) or tl_state == 1:\n self._goal_state[2] = 0\n self._state = DECELERATE_TO_STOP\n \n elif self._state == DECELERATE_TO_STOP:\n print(\"DECELERATE TO STOP...\")\n update_waypoints(self,waypoints,ego_state)\n tl_state = self.traffic_light_state.detect_traffic_light(camera_data)\n if abs(closed_loop_speed) <= STOP_THRESHOLD:\n self._goal_state[2]=0\n self._state = STAY_STOPPED\n self._stop_count = 0\n elif tl_state != 1 and not check_for_obs(potential_obs, ego_state,is_collision = False):\n self._state = FOLLOW_LANE\n\n\n\n\n # In this state, check to see if we have stayed stopped for at\n # least STOP_COUNTS number of cycles. If so, we can now leave\n # the stop sign and transition to the next state.\n elif self._state == STAY_STOPPED:\n print(\"STAY_STOPPED\")\n #TODO here make sure if no restriction change to state \"FOLLOW_LANE\"\n # We have stayed stopped for the required number of cycles.\n # Allow the ego vehicle to leave the stop sign. Once it has\n # passed the stop sign, return to lane following.\n # You should use the get_closest_index(), get_goal_index(), and\n # check_for_stop_signs() helper functions.\n print(\"Waiting: \" + str(self._stop_count))\n tl_state = self.traffic_light_state.detect_traffic_light(camera_data)\n if self._stop_count == STOP_COUNTS:\n \n update_waypoints(self, waypoints, ego_state)\n\n if tl_state != 1 and not check_for_obs(potential_obs, ego_state,is_collision = False):\n self._state = FOLLOW_LANE\n self._stop_count = 0\n\n elif tl_state != 1 and not check_for_obs(potential_obs, ego_state,is_collision = False):\n self._stop_count += 1\n\n else:\n raise ValueError('Invalid state value.')\n\n # Gets the goal index in the list of waypoints, based on the lookahead and\n # the current ego state. In particular, find the earliest waypoint that has accumulated\n # arc length (including closest_len) that is greater than or equal to self._lookahead.\n def get_goal_index(self, waypoints, ego_state, closest_len, closest_index):\n \"\"\"Gets the goal index for the vehicle.\n\n Set to be the earliest waypoint that has accumulated arc length\n accumulated arc length (including closest_len) that is greater than or\n equal to self._lookahead.\n\n args:\n waypoints: current waypoints to track. (global frame)\n length and speed in m and m/s.\n (includes speed to track at each x,y location.)\n format: [[x0, y0, v0],\n [x1, y1, v1],\n ...\n [xn, yn, vn]]\n example:\n waypoints[2][1]:\n returns the 3rd waypoint's y position\n\n waypoints[5]:\n returns [x5, y5, v5] (6th waypoint)\n ego_state: ego state vector for the vehicle. (global frame)\n format: [ego_x, ego_y, ego_yaw, ego_open_loop_speed]\n ego_x and ego_y : position (m)\n ego_yaw : top-down orientation [-pi to pi]\n ego_open_loop_speed : open loop speed (m/s)\n closest_len: length (m) to the closest waypoint from the vehicle.\n closest_index: index of the waypoint which is closest to the vehicle.\n i.e. waypoints[closest_index] gives the waypoint closest to the vehicle.\n returns:\n wp_index: Goal index for the vehicle to reach\n i.e. waypoints[wp_index] gives the goal waypoint\n \"\"\"\n # Find the farthest point along the path that is within the\n # lookahead distance of the ego vehicle.\n # Take the distance from the ego vehicle to the closest waypoint into\n # consideration.\n arc_length = closest_len\n wp_index = closest_index\n \n\n # In this case, reaching the closest waypoint is already far enough for\n # the planner. No need to check additional waypoints.\n if arc_length > self._lookahead:\n return wp_index\n\n # We are already at the end of the path.\n if wp_index == len(waypoints) - 1:\n return wp_index\n\n # Otherwise, find our next waypoint.\n while wp_index < len(waypoints) - 1:\n arc_length += np.sqrt((waypoints[wp_index][0] - waypoints[wp_index+1][0])**2 + (waypoints[wp_index][1] - waypoints[wp_index+1][1])**2)\n if arc_length > self._lookahead: break\n wp_index += 1\n\n return wp_index % len(waypoints)\n\n # Checks to see if we need to modify our velocity profile to accomodate the\n # lead vehicle.\n\n\n def check_for_lead_vehicle(self, ego_state, lead_car_position):\n \"\"\"Checks for lead vehicle within the proximity of the ego car, such\n that the ego car should begin to follow the lead vehicle.\n\n args:\n ego_state: ego state vector for the vehicle. (global frame)\n format: [ego_x, ego_y, ego_yaw, ego_open_loop_speed]\n ego_x and ego_y : position (m)\n ego_yaw : top-down orientation [-pi to pi]\n ego_open_loop_speed : open loop speed (m/s)\n lead_car_position: The [x, y] position of the lead vehicle.\n Lengths are in meters, and it is in the global frame.\n sets:\n self._follow_lead_vehicle: Boolean flag on whether the ego vehicle\n should follow (true) the lead car or not (false).\n \"\"\"\n # Check lead car position delta vector relative to heading, as well as\n # distance, to determine if car should be followed.\n # Check to see if lead vehicle is within range, and is ahead of us.\n if not self._follow_lead_vehicle:\n # Compute the angle between the normalized vector between the lead vehicle\n # and ego vehicle position with the ego vehicle's heading vector.\n lead_car_delta_vector = [lead_car_position[0] - ego_state[0],\n lead_car_position[1] - ego_state[1]]\n lead_car_distance = np.linalg.norm(lead_car_delta_vector)\n # In this case, the car is too far away.\n if lead_car_distance > self._follow_lead_vehicle_lookahead:\n return\n\n lead_car_delta_vector = np.divide(lead_car_delta_vector,\n lead_car_distance)\n ego_heading_vector = [math.cos(ego_state[2]),\n math.sin(ego_state[2])]\n # Check to see if the relative angle between the lead vehicle and the ego\n # vehicle lies within +/- 45 degrees of the ego vehicle's heading.\n if np.dot(lead_car_delta_vector,\n ego_heading_vector) < (1 / math.sqrt(2)):\n return\n\n self._follow_lead_vehicle = True\n\n else:\n lead_car_delta_vector = [lead_car_position[0] - ego_state[0],\n lead_car_position[1] - ego_state[1]]\n lead_car_distance = np.linalg.norm(lead_car_delta_vector)\n\n # Add a 15m buffer to prevent oscillations for the distance check.\n if lead_car_distance < self._follow_lead_vehicle_lookahead + 15:\n return\n # Check to see if the lead vehicle is still within the ego vehicle's\n # frame of view.\n lead_car_delta_vector = np.divide(lead_car_delta_vector, lead_car_distance)\n ego_heading_vector = [math.cos(ego_state[2]), math.sin(ego_state[2])]\n if np.dot(lead_car_delta_vector, ego_heading_vector) > (1 / math.sqrt(2)):\n return\n\n self._follow_lead_vehicle = False\n\n# Compute the waypoint index that is closest to the ego vehicle, and return\n# it as well as the distance from the ego vehicle to that waypoint.\ndef get_closest_index(waypoints, ego_state):\n \"\"\"Gets closest index a given list of waypoints to the vehicle position.\n\n args:\n waypoints: current waypoints to track. (global frame)\n length and speed in m and m/s.\n (includes speed to track at each x,y location.)\n format: [[x0, y0, v0],\n [x1, y1, v1],\n ...\n [xn, yn, vn]]\n example:\n waypoints[2][1]:\n returns the 3rd waypoint's y position\n\n waypoints[5]:\n returns [x5, y5, v5] (6th waypoint)\n ego_state: ego state vector for the vehicle. (global frame)\n format: [ego_x, ego_y, ego_yaw, ego_open_loop_speed]\n ego_x and ego_y : position (m)\n ego_yaw : top-down orientation [-pi to pi]\n ego_open_loop_speed : open loop speed (m/s)\n\n returns:\n [closest_len, closest_index]:\n closest_len: length (m) to the closest waypoint from the vehicle.\n closest_index: index of the waypoint which is closest to the vehicle.\n i.e. waypoints[closest_index] gives the waypoint closest to the vehicle.\n \"\"\"\n closest_len = float('Inf')\n closest_index = 0\n\n for i in range(len(waypoints)):\n temp = (waypoints[i][0] - ego_state[0])**2 + (waypoints[i][1] - ego_state[1])**2\n if temp < closest_len:\n closest_len = temp\n closest_index = i\n closest_len = np.sqrt(closest_len)\n\n return closest_len, closest_index\n\n# Checks if p2 lies on segment p1-p3, if p1, p2, p3 are collinear.\ndef pointOnSegment(p1, p2, p3):\n if (p2[0] <= max(p1[0], p3[0]) and (p2[0] >= min(p1[0], p3[0])) and \\\n (p2[1] <= max(p1[1], p3[1])) and (p2[1] >= min(p1[1], p3[1]))):\n return True\n else:\n return False\n\n\ndef update_waypoints(self, waypoints, ego_state):\n\n #First, find the closest index to the ego vehicle\n closest_len, closest_index = get_closest_index(waypoints, ego_state)\n\n # Next, find the goal index that lies within the lookahed distance\n # along the waypoints\n goal_index = self.get_goal_index(waypoints, ego_state, closest_len, closest_index)\n while waypoints[goal_index][2] <= 0.1: goal_index += 1\n\n self._goal_index = goal_index\n self._goal_state = waypoints[goal_index]" ]
[ [ "numpy.sqrt", "numpy.divide", "numpy.linalg.norm", "numpy.dot" ] ]
QuintonWeenink/pso
[ "f6fbb4c5889745d5747b367ecb3c9833805d9963" ]
[ "mlpy/particleSwarmOptimization/structure/particle.py" ]
[ "import numpy as np\n\nclass Particle(object):\n def __init__(self, bounds, weight, cognitiveConstant, socialConstant):\n self.position = None # particle position\n self.velocity = None # particle velocity\n\n self.best_position = None # best position individual\n self.best_error = float('inf') # best error individual\n\n self.error = None # error individual\n\n self.num_dimensions = None\n self.weight = weight\n self.cognitiveConstant = cognitiveConstant\n self.socialConstant = socialConstant\n self.bounds = bounds\n\n self.neighbourhood = []\n\n def initPos(self, position, velocity):\n self.num_dimensions = len(position)\n\n self.position = np.array(position)\n self.velocity = np.array(velocity)\n\n def getPersonalBest(self):\n if self.error < self.best_error:\n self.best_position = np.array(self.position)\n self.best_error = self.error\n\n return self.best_error\n\n def update_velocity(self, group_best_position):\n r1 = np.random.random(self.num_dimensions)\n r2 = np.random.random(self.num_dimensions)\n\n vel_cognitive = self.cognitiveConstant * r1 * (self.best_position - self.position)\n vel_social = self.socialConstant * r2 * (group_best_position - self.position)\n vel_inertia = self.weight * self.velocity\n self.velocity = vel_inertia + vel_cognitive + vel_social\n\n return self.velocity\n\n def update_position(self):\n self.position = self.position + self.velocity\n\n return self.velocity\n\n\n def toString(self):\n return ('\\tPosition: {position}\\n'+\n '\\tBest Position: {pos_best}\\n' +\n '\\tError: {err}\\n').format(position=self.position,\n pos_best=self.best_position,\n err=self.error)\n" ]
[ [ "numpy.array", "numpy.random.random" ] ]
JeremieMelo/pytorch-onn
[ "670996112277a6c19c7da400afbe0a4ce45ad5de" ]
[ "examples/core/models/mzi_cnn.py" ]
[ "\"\"\"\nDescription:\nAuthor: Jiaqi Gu ([email protected])\nDate: 2021-06-07 03:43:40\nLastEditors: Jiaqi Gu ([email protected])\nLastEditTime: 2021-06-07 03:43:40\n\"\"\"\n\nfrom torchonn.op.mzi_op import project_matrix_to_unitary\nfrom typing import List, Union\n\nimport torch\nfrom torch import Tensor, nn\nfrom torch.types import Device, _size\nfrom torchonn.layers import MZIBlockConv2d, MZIBlockLinear\nfrom torchonn.models import ONNBaseModel\nfrom collections import OrderedDict\n\n__all__ = [\"MZI_CLASS_CNN\"]\n\n\nclass ConvBlock(nn.Module):\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n kernel_size: int = 3,\n stride: Union[int, _size] = 1,\n padding: Union[int, _size] = 0,\n dilation: _size = 1,\n groups: int = 1,\n bias: bool = False,\n miniblock: int = 8,\n mode: str = \"weight\",\n decompose_alg: str = \"clements\",\n photodetect: bool = False,\n device: Device = torch.device(\"cuda\"),\n ) -> None:\n super().__init__()\n self.conv = MZIBlockConv2d(\n in_channels,\n out_channels,\n kernel_size,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n bias=bias,\n miniblock=miniblock,\n mode=mode,\n decompose_alg=decompose_alg,\n photodetect=photodetect,\n device=device,\n )\n\n self.bn = nn.BatchNorm2d(out_channels)\n\n self.activation = nn.ReLU(inplace=True)\n\n def forward(self, x: Tensor) -> Tensor:\n return self.activation(self.bn(self.conv(x)))\n\n\nclass LinearBlock(nn.Module):\n def __init__(\n self,\n in_features: int,\n out_features: int,\n bias: bool = False,\n miniblock: int = 8,\n mode: str = \"weight\",\n decompose_alg: str = \"clements\",\n photodetect: bool = False,\n activation: bool = True,\n device: Device = torch.device(\"cuda\"),\n ) -> None:\n super().__init__()\n self.linear = MZIBlockLinear(\n in_features,\n out_features,\n bias=bias,\n miniblock=miniblock,\n mode=mode,\n decompose_alg=decompose_alg,\n photodetect=photodetect,\n device=device,\n )\n\n self.activation = nn.ReLU(inplace=True) if activation else None\n\n def forward(self, x: Tensor) -> Tensor:\n x = self.linear(x)\n if self.activation is not None:\n x = self.activation(x)\n return x\n\n\nclass MZI_CLASS_CNN(ONNBaseModel):\n \"\"\"\n MZI CNN for classification.\n Blocking matrix multiplication, which is much faster and more scalable than implementing the entire weight matrix on an MZI array.\n Each block is implemented by a square MZI array\n\n \"\"\"\n\n _conv_linear = (MZIBlockConv2d, MZIBlockLinear)\n _conv = (MZIBlockConv2d,)\n _linear = (MZIBlockLinear,)\n\n def __init__(\n self,\n img_height: int,\n img_width: int,\n in_channels: int,\n num_classes: int,\n kernel_list: List[int] = [32],\n kernel_size_list: List[int] = [3],\n stride_list: List[int] = [1],\n padding_list: List[int] = [1],\n dilation_list: List[int] = [1],\n pool_out_size: int = 5,\n hidden_list: List[int] = [32],\n block_list: List[int] = [8],\n mode: str = \"usv\",\n decompose_alg: str = \"clements\",\n photodetect: bool = True,\n bias: bool = False,\n device: Device = torch.device(\"cuda\"),\n ) -> None:\n super().__init__()\n self.img_height = img_height\n self.img_width = img_width\n self.in_channels = in_channels\n self.num_classes = num_classes\n self.kernel_list = kernel_list\n self.kernel_size_list = kernel_size_list\n self.stride_list = stride_list\n self.padding_list = padding_list\n self.dilation_list = dilation_list\n\n self.pool_out_size = pool_out_size\n\n self.hidden_list = hidden_list\n self.block_list = block_list\n self.mode = mode\n self.decompose_alg = decompose_alg\n\n self.photodetect = photodetect\n self.bias = bias\n\n self.device = device\n\n self.build_layers()\n\n self.reset_parameters()\n\n def build_layers(self):\n self.features = OrderedDict()\n for idx, out_channels in enumerate(self.kernel_list, 0):\n layer_name = \"conv\" + str(idx + 1)\n in_channels = self.in_channels if (idx == 0) else self.kernel_list[idx - 1]\n\n self.features[layer_name] = ConvBlock(\n in_channels,\n out_channels,\n kernel_size=self.kernel_size_list[idx],\n stride=self.stride_list[idx],\n padding=self.padding_list[idx],\n dilation=self.dilation_list[idx],\n groups=1,\n bias=self.bias,\n miniblock=self.block_list[idx],\n mode=self.mode,\n decompose_alg=self.decompose_alg,\n photodetect=self.photodetect,\n device=self.device,\n )\n self.features = nn.Sequential(self.features)\n\n if self.pool_out_size > 0:\n self.pool2d = nn.AdaptiveAvgPool2d(self.pool_out_size)\n feature_size = self.kernel_list[-1] * self.pool_out_size * self.pool_out_size\n else:\n self.pool2d = None\n img_height, img_width = self.img_height, self.img_width\n for layer in self.modules():\n if isinstance(layer, self._conv):\n img_height, img_width = layer.get_output_dim(img_height, img_width)\n feature_size = img_height * img_width * self.kernel_list[-1]\n\n self.classifier = OrderedDict()\n for idx, hidden_dim in enumerate(self.hidden_list, 0):\n layer_name = \"fc\" + str(idx + 1)\n in_channel = feature_size if idx == 0 else self.hidden_list[idx - 1]\n out_channel = hidden_dim\n self.classifier[layer_name] = LinearBlock(\n in_channel,\n out_channel,\n bias=self.bias,\n miniblock=self.block_list[idx + len(self.kernel_list)],\n mode=self.mode,\n decompose_alg=self.decompose_alg,\n photodetect=self.photodetect,\n activation=True,\n device=self.device,\n )\n\n layer_name = \"fc\" + str(len(self.hidden_list) + 1)\n self.classifier[layer_name] = LinearBlock(\n self.hidden_list[-1] if len(self.hidden_list) > 0 else feature_size,\n self.num_classes,\n bias=self.bias,\n miniblock=self.block_list[-1],\n mode=self.mode,\n decompose_alg=self.decompose_alg,\n photodetect=self.photodetect,\n activation=False,\n device=self.device,\n )\n self.classifier = nn.Sequential(self.classifier)\n\n def unitary_projection(self) -> None:\n assert self.mode == \"usv\", \"Unitary projection can only be applied in usv mode\"\n for m in self.modules():\n if isinstance(m, self._conv_linear):\n m.U.data.copy_(project_matrix_to_unitary(m.U.data))\n m.V.data.copy_(project_matrix_to_unitary(m.V.data))\n\n def forward(self, x: Tensor) -> Tensor:\n x = self.features(x)\n if self.pool2d is not None:\n x = self.pool2d(x)\n x = torch.flatten(x, 1)\n x = self.classifier(x)\n\n return x\n" ]
[ [ "torch.nn.BatchNorm2d", "torch.flatten", "torch.nn.AdaptiveAvgPool2d", "torch.device", "torch.nn.Sequential", "torch.nn.ReLU" ] ]
888yzbt888/Pensieve-multiagent
[ "b5409c949a4855afedc910de5dd6eabe076567cc" ]
[ "demo/demo.py" ]
[ "import time\nimport bisect\nimport cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom matplotlib import gridspec\n\n\nVIDEO_FILE = 'la_luna.mp4'\nRL_BITRATE_FILE = './rl_bitrate'\nRL_BUFFER_FILE = './rl_buffer'\nMPC_BITRATE_FILE = './mpc_bitrate'\nMPC_BUFFER_FILE = './mpc_buffer'\nTRACE_FILE = './network_trace'\nSKIP_FRAMES = 8820\nTOTAL_FRAMES = 2000\nCHUNK_LEN = 4.0\nALL_BITRATES = {0.3, 0.75, 1.2}\n\ncap = cv.VideoCapture(VIDEO_FILE)\nkern_map = {0.3: np.ones((12, 12), np.float32) / 144, \n\t\t\t0.75: np.ones((6, 6), np.float32) / 36, \n\t\t\t1.2: np.ones((1, 1), np.float32) / 1}\ntext_map = {0.3: '240P',\n\t\t\t0.75: '360P',\n\t\t\t1.2: '720P'}\n\ndef read_file(FILE_NAME):\n\tts = []\n\tvs = []\n\twith open(FILE_NAME, 'rb') as f:\n\t\tfor line in f:\n\t\t\tparse = line.split()\n\t\t\tif len(parse) != 2:\n\t\t\t\tbreak\n\t\t\tts.append(float(parse[0]))\n\t\t\tvs.append(float(parse[1]))\n\treturn ts, vs\n\nrl_bitrates_ts, rl_bitrates = read_file(RL_BITRATE_FILE)\nrl_buffer_ts, rl_buffers = read_file(RL_BUFFER_FILE)\nmpc_bitrates_ts, mpc_bitrates = read_file(MPC_BITRATE_FILE)\nmpc_buffer_ts, mpc_buffers = read_file(MPC_BUFFER_FILE)\ntrace_ts, trace_bw = read_file(TRACE_FILE)\n\nprint (\" -- Processing videos -- \")\nall_processed_frames = {}\nfor br in ALL_BITRATES:\n\tall_processed_frames[br] = []\n\nfor _ in xrange(SKIP_FRAMES):\n\t_, frame = cap.read()\t\n\n# while(cap.isOpened()):\nfor f in xrange(TOTAL_FRAMES):\n\tprint ('frame', f)\n\t_, frame = cap.read()\n\tframe = cv.cvtColor(frame, cv.COLOR_BGR2RGB)\n\tfor br in ALL_BITRATES:\n\t\tprocessed_frame = cv.filter2D(frame, -1, kern_map[br])\n\t\tall_processed_frames[br].append(processed_frame)\n\nframe = all_processed_frames[1.2][0]\n\nfig = plt.figure(figsize=(14, 6))\n\ngs = gridspec.GridSpec(6, 6)\nax1 = plt.subplot(gs[:3, :3])\nax2 = plt.subplot(gs[3:, :3])\nax3 = plt.subplot(gs[:2, 3:])\nax4 = plt.subplot(gs[2:4, 3:])\nax5 = plt.subplot(gs[4:, 3:])\n\nbbox_props = dict(boxstyle=\"round\", fc=\"gray\", ec=\"0.5\", alpha=0.5)\n\nimg1 = ax1.imshow(frame)\nax1.set_ylabel('RL', size=21, color='#f23030')\nax1.xaxis.set_tick_params(bottom='off', labelbottom='off') \nax1.yaxis.set_tick_params(left='off', labelleft='off')\ntext1 = ax1.text(1150, 650, \"240P\", color=\"white\", ha=\"center\", va=\"center\", size=16, bbox=bbox_props)\n\nimg2 = ax2.imshow(frame)\nax2.set_ylabel('MPC', size=21, color='#2127dd')\nax2.xaxis.set_tick_params(bottom='off', labelbottom='off') \nax2.yaxis.set_tick_params(left='off', labelleft='off')\ntext2 = ax2.text(1150, 650, \"240P\", color=\"white\", ha=\"center\", va=\"center\", size=16, bbox=bbox_props)\n\nax3.plot(rl_buffer_ts, rl_buffers, color='#f23030')\nbar1, = ax3.plot([0, 0], [0, 25], color=\"orange\", alpha=0.5)\nax3.set_ylabel('RL buffer (sec)')\nax3.set_xlim([-5, 105])\nax3.set_ylim([-2, 26])\nax3.xaxis.set_tick_params(labelbottom='off') \n# ax3.yaxis.set_tick_params(labelleft='off') \n\nax4.plot(trace_ts, trace_bw, color='#1c1c1c', alpha=0.9)\nbar2, = ax4.plot([0, 0], [0.4, 2.3], color=\"orange\", alpha=0.5)\nax4.set_ylabel('Throughput (mbps)')\nax4.set_xlim([-5, 105])\nax4.xaxis.set_tick_params(labelbottom='off') \n# ax4.yaxis.set_tick_params(labelleft='off') \n\nax5.plot(mpc_buffer_ts, mpc_buffers, color='#2127dd')\nbar3, = ax5.plot([0, 0], [0, 25], color=\"orange\", alpha=0.5)\nax5.set_ylabel('MPC buffer (sec)')\nax5.set_xlim([-5, 105])\nax3.set_ylim([-2, 26])\nax5.xaxis.set_tick_params(labelbottom='off') \n# ax5.yaxis.set_tick_params(labelleft='off') \nax5.set_xlabel('Time')\n\nrolling_ts = np.linspace(0, 4 * len(rl_bitrates) - 4, len(rl_bitrates) * 20)\ndef get_frame_quality(rolling_ts, bitrates_ts, bitrates, buffer_ts, buffers):\n\tframe_quality = {}\n\ttext_quality = {}\n\n\tlast_frame = 0\n\tfor t in rolling_ts:\n\t\tbr_pt = bisect.bisect(bitrates_ts, t) - 1\n\t\tbuf_pt = bisect.bisect(buffer_ts, t) - 1\n\n\t\tif buffers[buf_pt] > 0.05:\n\t\t\tlast_frame = (last_frame + 2) % TOTAL_FRAMES\n\n\t\tframe_quality[t] = all_processed_frames[bitrates[br_pt]][last_frame]\n\t\ttext_quality[t] = text_map[bitrates[br_pt]]\n\n\treturn frame_quality, text_quality\n\nrl_frame_quality, rl_text_quality = get_frame_quality(\n\trolling_ts, rl_bitrates_ts, rl_bitrates, rl_buffer_ts, rl_buffers)\nmpc_frame_quality, mpc_text_quality = get_frame_quality(\n\trolling_ts, mpc_bitrates_ts, mpc_bitrates, mpc_buffer_ts, mpc_buffers)\n\ndef animate(i):\n\tbar1.set_data([i, i], [0, 25])\n\tbar2.set_data([i, i], [0.4, 2.3])\n\tbar3.set_data([i, i], [0, 25])\n\n\timg1.set_data(rl_frame_quality[i])\n\timg2.set_data(mpc_frame_quality[i])\n\n\ttext1.set_text(rl_text_quality[i])\n\ttext2.set_text(mpc_text_quality[i])\n\t\n\treturn bar1, bar2, bar3, img1, img2, text1, text2\n\nani = animation.FuncAnimation(fig, animate, rolling_ts, \n\t\t\t\t\t\t\t interval=50, blit=True)\n\n# plt.show()\n\n# Set up formatting for the movie files\nWriter = animation.writers['ffmpeg']\nwriter = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)\n\nani.save('demo.mp4', writer=writer)\n" ]
[ [ "numpy.ones", "matplotlib.pyplot.figure", "matplotlib.pyplot.subplot", "matplotlib.animation.FuncAnimation", "matplotlib.gridspec.GridSpec" ] ]
caoyi0905/Surprise
[ "1a707b32a3a68b0eb3f23b829b57604a131e00f7" ]
[ "tests/test_dataset.py" ]
[ "\"\"\"\nModule for testing the Dataset class.\n\"\"\"\n\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\nimport os\nimport random\n\nimport pytest\nimport pandas as pd\n\nfrom surprise import BaselineOnly\nfrom surprise import Dataset\nfrom surprise import Reader\nfrom surprise.builtin_datasets import get_dataset_dir\n\n\nrandom.seed(1)\n\n\ndef test_wrong_file_name():\n \"\"\"Ensure file names are checked when creating a (custom) Dataset.\"\"\"\n wrong_files = [('does_not_exist', 'does_not_either')]\n\n with pytest.raises(ValueError):\n Dataset.load_from_folds(folds_files=wrong_files, reader=Reader(),\n rating_scale=(1, 5))\n\n\ndef test_build_full_trainset(toy_data):\n \"\"\"Test the build_full_trainset method.\"\"\"\n\n trainset = toy_data.build_full_trainset()\n\n assert len(trainset.ur) == 5\n assert len(trainset.ir) == 2\n assert trainset.n_users == 5\n assert trainset.n_items == 2\n\n\ndef test_no_call_to_split(toy_data):\n \"\"\"Ensure, as mentioned in the split() docstring, that even if split is not\n called then the data is split with 5 folds after being shuffled.\"\"\"\n\n with pytest.warns(UserWarning):\n assert len(list(toy_data.folds())) == 5\n\n # make sure data has been shuffled. If not shuffled, the users in the\n # testsets would be 0, 1, 2... 4 (in that order).\n with pytest.warns(UserWarning):\n users = [int(testset[0][0][-1])\n for (_, testset) in toy_data.folds()]\n assert users != list(range(5))\n\n\ndef test_split(toy_data):\n \"\"\"Test the split method.\"\"\"\n\n # Test the shuffle parameter\n # Make sure data has not been shuffled. If not shuffled, the users in the\n # testsets are 0, 1, 2... 4 (in that order).\n with pytest.warns(UserWarning):\n toy_data.split(n_folds=5, shuffle=False)\n users = [int(testset[0][0][-1])\n for (_, testset) in toy_data.folds()]\n assert users == list(range(5))\n\n # Test the shuffle parameter\n # Make sure that when called two times without shuffling, folds are the\n # same.\n with pytest.warns(UserWarning):\n toy_data.split(n_folds=3, shuffle=False)\n testsets_a = [testset for (_, testset) in toy_data.folds()]\n toy_data.split(n_folds=3, shuffle=False)\n testsets_b = [testset for (_, testset) in toy_data.folds()]\n assert testsets_a == testsets_b\n\n # We'll now shuffle b and check that folds are different.\n with pytest.warns(UserWarning):\n toy_data.split(n_folds=3, shuffle=True)\n testsets_b = [testset for (_, testset) in toy_data.folds()]\n assert testsets_a != testsets_b\n\n # Ensure that folds are the same if split is not called again\n with pytest.warns(UserWarning):\n testsets_a = [testset for (_, testset) in toy_data.folds()]\n testsets_b = [testset for (_, testset) in toy_data.folds()]\n assert testsets_a == testsets_b\n\n # Test n_folds parameter\n with pytest.warns(UserWarning):\n toy_data.split(5)\n assert len(list(toy_data.folds())) == 5\n\n with pytest.raises(ValueError):\n toy_data.split(10) # Too big (greater than number of ratings)\n\n with pytest.raises(ValueError):\n toy_data.split(1) # Too low (must be >= 2)\n\n\ndef test_trainset_testset(toy_data_reader):\n \"\"\"Test the construct_trainset and construct_testset methods.\"\"\"\n\n current_dir = os.path.dirname(os.path.realpath(__file__))\n folds_files = [(current_dir + '/custom_train',\n current_dir + '/custom_test')]\n\n data = Dataset.load_from_folds(folds_files=folds_files,\n reader=toy_data_reader, rating_scale=(1, 5))\n\n with pytest.warns(UserWarning):\n trainset, testset = next(data.folds())\n\n # test ur\n ur = trainset.ur\n assert ur[0] == [(0, 4)]\n assert ur[1] == [(0, 4), (1, 2)]\n assert ur[40] == [] # not in the trainset\n\n # test ir\n ir = trainset.ir\n assert ir[0] == [(0, 4), (1, 4), (2, 1)]\n assert ir[1] == [(1, 2), (2, 1), (3, 5)]\n assert ir[20000] == [] # not in the trainset\n\n # test n_users, n_items, n_ratings, rating_scale\n assert trainset.n_users == 4\n assert trainset.n_items == 2\n assert trainset.n_ratings == 6\n assert trainset.rating_scale == (1, 5)\n\n # test raw2inner\n for i in range(4):\n assert trainset.to_inner_uid('user' + str(i)) == i\n with pytest.raises(ValueError):\n trainset.to_inner_uid('unkown_user')\n\n for i in range(2):\n assert trainset.to_inner_iid('item' + str(i)) == i\n with pytest.raises(ValueError):\n trainset.to_inner_iid('unkown_item')\n\n # test inner2raw\n assert trainset._inner2raw_id_users is None\n assert trainset._inner2raw_id_items is None\n for i in range(4):\n assert trainset.to_raw_uid(i) == 'user' + str(i)\n for i in range(2):\n assert trainset.to_raw_iid(i) == 'item' + str(i)\n assert trainset._inner2raw_id_users is not None\n assert trainset._inner2raw_id_items is not None\n\n # Test the build_testset() method\n algo = BaselineOnly()\n algo.fit(trainset)\n testset = trainset.build_testset()\n algo.test(testset) # ensure an algorithm can manage the data\n assert ('user0', 'item0', 4) in testset\n assert ('user3', 'item1', 5) in testset\n assert ('user3', 'item1', 0) not in testset\n\n # Test the build_anti_testset() method\n algo = BaselineOnly()\n algo.fit(trainset)\n testset = trainset.build_anti_testset()\n algo.test(testset) # ensure an algorithm can manage the data\n assert ('user0', 'item0', trainset.global_mean) not in testset\n assert ('user3', 'item1', trainset.global_mean) not in testset\n assert ('user0', 'item1', trainset.global_mean) in testset\n assert ('user3', 'item0', trainset.global_mean) in testset\n\n\ndef test_load_form_df():\n \"\"\"Ensure reading dataset from pandas dataframe is OK.\"\"\"\n\n # DF creation.\n ratings_dict = {'itemID': [1, 1, 1, 2, 2],\n 'userID': [9, 32, 2, 45, '10000'],\n 'rating': [3, 2, 4, 3, 1]}\n df = pd.DataFrame(ratings_dict)\n\n data = Dataset.load_from_df(df[['userID', 'itemID', 'rating']],\n rating_scale=(1, 5))\n\n # Assert split and folds can be used without problems\n with pytest.warns(UserWarning):\n data.split(2)\n assert sum(1 for _ in data.folds()) == 2\n\n # assert users and items are correctly mapped\n trainset = data.build_full_trainset()\n assert trainset.knows_user(trainset.to_inner_uid(9))\n assert trainset.knows_user(trainset.to_inner_uid('10000'))\n assert trainset.knows_item(trainset.to_inner_iid(2))\n\n # assert r(9, 1) = 3 and r(2, 1) = 4\n uid9 = trainset.to_inner_uid(9)\n uid2 = trainset.to_inner_uid(2)\n iid1 = trainset.to_inner_iid(1)\n assert trainset.ur[uid9] == [(iid1, 3)]\n assert trainset.ur[uid2] == [(iid1, 4)]\n\n # mess up the column ordering and assert that users are not correctly\n # mapped\n data = Dataset.load_from_df(df[['rating', 'itemID', 'userID']],\n rating_scale=(1, 5))\n trainset = data.build_full_trainset()\n with pytest.raises(ValueError):\n trainset.to_inner_uid('10000')\n\n\ndef test_build_anti_testset():\n ratings_dict = {'itemID': [1, 2, 3, 4, 5, 6, 7, 8, 9],\n 'userID': [1, 2, 3, 4, 5, 6, 7, 8, 9],\n 'rating': [1, 2, 3, 4, 5, 6, 7, 8, 9]}\n df = pd.DataFrame(ratings_dict)\n\n data = Dataset.load_from_df(df[['userID', 'itemID', 'rating']],\n rating_scale=(1, 5))\n with pytest.warns(UserWarning):\n data.split(2)\n trainset, __testset = next(data.folds())\n # fill with some specific value\n for fillvalue in (0, 42., -1):\n anti = trainset.build_anti_testset(fill=fillvalue)\n for (u, i, r) in anti:\n assert r == fillvalue\n # fill with global_mean\n anti = trainset.build_anti_testset(fill=None)\n for (u, i, r) in anti:\n assert r == trainset.global_mean\n expect = trainset.n_users * trainset.n_items\n assert trainset.n_ratings + len(anti) == expect\n\n\ndef test_get_dataset_dir():\n '''Test the get_dataset_dir() function.'''\n\n os.environ['SURPRISE_DATA_FOLDER'] = '/tmp/surprise_data'\n assert get_dataset_dir() == '/tmp/surprise_data'\n\n # Fall back to default\n del os.environ['SURPRISE_DATA_FOLDER']\n assert get_dataset_dir() == os.path.expanduser('~' + '/.surprise_data/')\n" ]
[ [ "pandas.DataFrame" ] ]
jfw225/ptlib
[ "a78ef707ed09aa9c1f1b1157a20e3d9d3fb04c4d" ]
[ "tests/queue_test.py" ]
[ "import cv2\nimport pickle\nimport numpy as np\n\nimport ptlib as pt\nfrom ptlib.core.metadata import MetadataManager\nfrom ptlib.core.queue import Queue\n\n\nclass VideoIngest(pt.Task):\n # variables here are static\n NUM_WORKERS = 1\n\n VIDEO_PATH = \"C:\\\\Users\\\\Owner\\\\Videos\\\\Battlefield 2042 Open Beta\\\\testvid.mp4\"\n BATCH_SIZE = 30 * 5 # fps * duartion in seconds\n\n def __init__(self):\n # maybe no init\n super().__init__(num_workers=VideoIngest.NUM_WORKERS)\n\n def create_map(self, worker):\n # create capture object\n capture = cv2.VideoCapture(self.VIDEO_PATH)\n\n # compute task specific start position, stop position, and batch_id\n num_frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))\n start_pos = worker.id * num_frames // self.num_workers\n stop_pos = (worker.id + 1) * num_frames // self.num_workers\n worker.batch_id = start_pos // self.BATCH_SIZE\n print(\n f\"ingest: {worker.id} | start: {start_pos} | stop: {stop_pos} | batch_id: {worker.batch_id}\")\n\n # get shape and dtype\n _, frame = capture.read()\n shape, dtype = frame.shape, frame.dtype\n\n # set the capture object to the start position\n capture.set(cv2.CAP_PROP_POS_FRAMES, start_pos)\n\n # create range to iterate over\n batch_iter = [i for i in range(self.BATCH_SIZE)]\n\n # set the current frame position\n worker.current_pos = start_pos\n\n # set zero array and output array\n worker.output_arr = np.zeros((self.BATCH_SIZE, *shape), dtype=dtype)\n\n def job_map(input_job):\n worker.output_arr.fill(0)\n for i in batch_iter:\n ret, frame = capture.read()\n\n if not ret or worker.current_pos == stop_pos:\n capture.release()\n worker.EXIT_FLAG = True\n break\n\n worker.output_arr[i] = frame\n worker.current_pos += 1\n\n worker.batch_id += 1\n\n # return output_batch\n return [worker.output_arr]\n\n return job_map\n\n\n##### pseudo-controller implementation for testing #####\ndef run(pipeline, meta_manager, output_q):\n # link output queue\n output_q._link_mem(create_local=True)\n\n # set start time\n meta_manager.set_time()\n\n # start all worker processes\n for task in pipeline.iter_tasks():\n task._start_workers()\n\n task = pipeline\n while task is not pt.EmptyTask:\n # force pull from output queue\n output_q.get()\n\n # update metadata\n meta_manager.update()\n\n # if current task finishes, send kill signal to workers\n if not task._workers_running():\n print(f\"Task Finished: {task.name}\")\n task = task.next\n task._kill_workers()\n\n # finish retreiving metadata (in case loop exits before getting all metadata)\n meta_manager.update()\n\n # set finish time\n meta_manager.set_time()\n\n\nif __name__ == '__main__':\n # create pipeline\n pipeline = VideoIngest()\n\n # infer output\n output_job, job_specs = pipeline.infer_structure(None)\n\n # create I/O queues\n input_q, output_q = Queue(), Queue(job_specs, capacity=5)\n\n # create metadata manager\n meta_manager = MetadataManager(pipeline)\n\n # create workers and assign them to task\n pipeline.create_workers(input_q, output_q, meta_manager.meta_q)\n\n # start pseudo-controller\n run(pipeline, meta_manager, output_q)\n\n # create and run controller\n # controller = pt.Controller(pipeline, 5)\n # controller.run()\n # controller.graph()\n" ]
[ [ "numpy.zeros" ] ]
vipksmosar/habr_rss_parse
[ "91fa3df3db3a1416348237919824696239d4cb29" ]
[ "airflow/airflow_own/plugins/WRITER.py" ]
[ "import os\ntry:\n import pandas as pd\nexcept:\n os.system('pip3 install pandas')\n import pandas as pd\ntry:\n import psycopg2\nexcept:\n os.system('pip3 install psycopg2-binary')\n import psycopg2\nimport numpy as np\nfrom psycopg2.extensions import register_adapter, AsIs\npsycopg2.extensions.register_adapter(np.int64, psycopg2._psycopg.AsIs)\n\nclass POSTGREE_WRITER:\n \n def __init__(self, string_to_connect='postgresql://postgres:postgres@pdbserv:5432/postgres'):\n \n self.string_to_connect = string_to_connect\n self.conn = psycopg2.connect(self.string_to_connect)\n self.cursor = self.conn.cursor()\n \n def __create_DF(self, path='./habr_news/'):\n DF_ALL = pd.DataFrame()\n for file in os.listdir(path):\n full_filename = '{}{}'.format(path, file)\n DF = pd.read_parquet(full_filename)\n DF_ALL = pd.concat([DF_ALL, DF])\n DF_ALL = DF_ALL.drop_duplicates()\n return DF_ALL\n \n def __clear_directory(self, path='./habr_news/'):\n for file in os.listdir(path):\n full_filename = '{}{}'.format(path, file)\n os.remove(full_filename)\n \n \n def sql_test(self, table_name):\n select_req = '''SELECT * FROM {};'''.format(table_name)\n #select_req = '''SELECT * FROM INFORMATION_SCHEMA.TABLES'''\n self.cursor.execute(select_req)\n data_final = self.cursor.fetchall()\n columns_data = list(map(lambda x: x[0], self.cursor.description))\n self.conn.commit()\n return data_final, columns_data\n \n def sql_insert(self, table_name, data):\n self.__init__('postgresql://postgres:postgres@pdbserv:5432/postgres')\n select_insert = '''INSERT INTO {}\n (\n title,\n link,\n author_name,\n real_author_name,\n body,\n index_hash,\n create_at,\n text_len,\n word_count,\n word_mean,\n eng_symbol ,\n rus_symbol,\n num_symbol \n )\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);\n '''.format(table_name)\n self.cursor.execute(select_insert, data)\n self.conn.commit()\n \n def sql_start(self, path):\n self.result = {'error_count':0, 'success_count':0}\n self.create_table_if_not_exist('habr_news')\n data = self.__create_DF(path)\n for i in range(len(data)):\n try:\n string = data.iloc[i]\n self.sql_insert('habr_news',(string['title'], string['link'], string['author_name'],\n string['real_author_name'],string['body'], string['index_hash'],\n string['create_at'], string['text_len'], string['word_count'],\n string['word_mean'], string['eng_symbol'], string['rus_symbol'],\n string['num_symbol']))\n self.result['success_count']+=1\n except Exception as E:\n #print(E)\n if 'duplicate key value violates unique constraint' in '{}'.format(E):\n self.result['error_count']+=1\n #data, columns = self.sql_test('habr_news')\n self.cursor.close()\n self.conn.close()\n if self.result['error_count']==len(data):\n self.__clear_directory('/opt/airflow/tmp_dir/habr_news/')\n return self.result\n \n def create_table_if_not_exist(self, table_name):\n select_insert = '''create table if not exists {} (\n title TEXT,\n link TEXT,\n author_name TEXT,\n real_author_name TEXT,\n body TEXT,\n index_hash VARCHAR NOT NULL,\n create_at TIMESTAMP,\n text_len INT,\n word_count REAL,\n word_mean REAL,\n eng_symbol INT,\n rus_symbol INT,\n num_symbol INT,\n CONSTRAINT habr_news_pk PRIMARY KEY (index_hash)\n )'''.format(table_name)\n self.cursor.execute(select_insert)\n self.conn.commit()" ]
[ [ "pandas.DataFrame", "pandas.concat", "pandas.read_parquet" ] ]
where-is-brett/tensorflow
[ "5da8599b2cf9edfb9fac4431c705501bf7ceccd8", "5da8599b2cf9edfb9fac4431c705501bf7ceccd8" ]
[ "tensorflow/lite/testing/op_tests/unroll_batch_matmul.py", "tensorflow/python/keras/layers/preprocessing/image_preprocessing.py" ]
[ "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Test configs for unroll_batch_matmul.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.compat.v1 as tf\nfrom tensorflow.lite.testing.zip_test_utils import create_tensor_data\nfrom tensorflow.lite.testing.zip_test_utils import make_zip_of_tests\nfrom tensorflow.lite.testing.zip_test_utils import register_make_test_function\n\n\n@register_make_test_function()\ndef make_unroll_batch_matmul_tests(options):\n \"\"\"Make a set of tests to test unroll_batch_matmul.\"\"\"\n\n # The test cases below requires broadcasting support (BatchMatMulV2 semantic),\n # whis isn't supported as of this change.\n broadcast_shape_params = [\n # Simple broadcast.\n [(1, 2, 3), (3, 5), False, False],\n # Empty batch broadcast.\n [(2, 5, 3), (3, 7), False, False],\n # Single batch with non-empty batch broadcast.\n [(1, 5, 3), (4, 3, 7), False, False],\n # Broadcast both operands\n [(3, 1, 5, 3), (1, 4, 3, 7), False, False],\n ]\n\n test_parameters = [{\n \"dtype\": [tf.float32],\n \"shape\": [[(2, 2, 3),\n (2, 3, 2), False, False], [(2, 2, 3), (2, 3, 2), True, True],\n [(2, 2, 3),\n (2, 2, 3), False, True], [(2, 2, 3), (2, 2, 3), True, False],\n [(4, 2, 2, 3), (4, 2, 3, 2), False, False],\n [(4, 2, 2, 3), (4, 2, 3, 2), True, True],\n [(4, 2, 2, 3), (4, 2, 2, 3), False, True],\n [(4, 2, 2, 3),\n (4, 2, 2, 3), True, False]] + broadcast_shape_params,\n # TODO(b/130887442): Improve the forward compatibility tests for every\n # ops.\n \"forward_compatibility_test\": [False, True],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the batch_matmul op testing graph.\"\"\"\n\n def _build_graph():\n \"\"\"Build the graph.\"\"\"\n input_tensor1 = tf.compat.v1.placeholder(\n dtype=parameters[\"dtype\"], shape=parameters[\"shape\"][0])\n input_tensor2 = tf.compat.v1.placeholder(\n dtype=parameters[\"dtype\"], shape=parameters[\"shape\"][1])\n # Should be unrolled and replaced with fully_connected ops in the end.\n out = tf.matmul(\n input_tensor1,\n input_tensor2,\n transpose_a=parameters[\"shape\"][2],\n transpose_b=parameters[\"shape\"][3])\n return [input_tensor1, input_tensor2], [out]\n\n if parameters[\"forward_compatibility_test\"]:\n # This is hardcoded to the date after MatMulV2 is activated.\n # TODO(b/130887442): Improve the forward compatibility tests for every\n # ops, and remove the hardcoded date.\n with tf.compat.forward_compatibility_horizon(2019, 4, 26):\n return _build_graph()\n else:\n return _build_graph()\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value1 = create_tensor_data(\n parameters[\"dtype\"], shape=parameters[\"shape\"][0])\n input_value2 = create_tensor_data(\n parameters[\"dtype\"], shape=parameters[\"shape\"][1])\n return [input_value1, input_value2], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Keras image preprocessing layers.\"\"\"\n# pylint: disable=g-classes-have-attributes\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras.engine.base_layer import Layer\nfrom tensorflow.python.keras.engine.input_spec import InputSpec\nfrom tensorflow.python.keras.utils import tf_utils\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import check_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import image_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import stateful_random_ops\nfrom tensorflow.python.ops import stateless_random_ops\n\nResizeMethod = image_ops.ResizeMethod\n\n_RESIZE_METHODS = {\n 'bilinear': ResizeMethod.BILINEAR,\n 'nearest': ResizeMethod.NEAREST_NEIGHBOR,\n 'bicubic': ResizeMethod.BICUBIC,\n 'area': ResizeMethod.AREA,\n 'lanczos3': ResizeMethod.LANCZOS3,\n 'lanczos5': ResizeMethod.LANCZOS5,\n 'gaussian': ResizeMethod.GAUSSIAN,\n 'mitchellcubic': ResizeMethod.MITCHELLCUBIC\n}\n\n\nclass Resizing(Layer):\n \"\"\"Image resizing layer.\n\n Resize the batched image input to target height and width. The input should\n be a 4-D tensor in the format of NHWC.\n\n Arguments:\n height: Integer, the height of the output shape.\n width: Integer, the width of the output shape.\n interpolation: String, the interpolation method. Defaults to `bilinear`.\n Supports `bilinear`, `nearest`, `bicubic`, `area`, `lanczos3`, `lanczos5`,\n `gaussian`, `mitchellcubic`\n \"\"\"\n\n def __init__(self, height, width, interpolation='bilinear', **kwargs):\n self.target_height = height\n self.target_width = width\n self.interpolation = interpolation\n self._interpolation_method = get_interpolation(interpolation)\n self.input_spec = InputSpec(ndim=4)\n super(Resizing, self).__init__(**kwargs)\n\n def build(self, input_shape):\n channel_axis = 3\n channel_dim = int(input_shape[channel_axis])\n self.input_spec = InputSpec(ndim=4, axes={channel_axis: channel_dim})\n self.built = True\n\n def call(self, inputs):\n outputs = image_ops.resize_images_v2(\n images=inputs,\n size=[self.target_height, self.target_width],\n method=self._interpolation_method)\n return outputs\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n return tensor_shape.TensorShape(\n [input_shape[0], self.target_height, self.target_width, input_shape[3]])\n\n def get_config(self):\n config = {\n 'height': self.target_height,\n 'width': self.target_width,\n 'interpolation': self.interpolation,\n }\n base_config = super(Resizing, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass CenterCrop(Layer):\n \"\"\"Crop the central portion of the images to target height and width.\n\n Input shape:\n 4D tensor with shape:\n `(samples, height, width, channels)`, data_format='channels_last'.\n\n Output shape:\n 4D tensor with shape:\n `(samples, target_height, target_width, channels)`.\n\n If the input height/width is even and the target height/width is odd (or\n inversely), the input image is left-padded by 1 pixel.\n\n Arguments:\n height: Integer, the height of the output shape.\n width: Integer, the width of the output shape.\n \"\"\"\n\n def __init__(self, height, width, **kwargs):\n self.target_height = height\n self.target_width = width\n self.input_spec = InputSpec(ndim=4)\n super(CenterCrop, self).__init__(**kwargs)\n\n def build(self, input_shape):\n channel_axis = 3\n channel_dim = int(input_shape[channel_axis])\n self.input_spec = InputSpec(ndim=4, axes={channel_axis: channel_dim})\n self.built = True\n\n def call(self, inputs):\n inputs_shape = array_ops.shape(inputs)\n h_axis, w_axis = 1, 2\n img_hd = inputs_shape[h_axis]\n img_wd = inputs_shape[w_axis]\n img_hd_diff = img_hd - self.target_height\n img_wd_diff = img_wd - self.target_width\n checks = []\n checks.append(\n check_ops.assert_non_negative(\n img_hd_diff,\n message='The crop height {} should not be greater than input '\n 'height.'.format(self.target_height)))\n checks.append(\n check_ops.assert_non_negative(\n img_wd_diff,\n message='The crop width {} should not be greater than input '\n 'width.'.format(self.target_width)))\n with ops.control_dependencies(checks):\n bbox_h_start = math_ops.cast(img_hd_diff / 2, dtypes.int32)\n bbox_w_start = math_ops.cast(img_wd_diff / 2, dtypes.int32)\n bbox_begin = array_ops.stack([0, bbox_h_start, bbox_w_start, 0])\n bbox_size = array_ops.stack(\n [-1, self.target_height, self.target_width, -1])\n outputs = array_ops.slice(inputs, bbox_begin, bbox_size)\n return outputs\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n return tensor_shape.TensorShape(\n [input_shape[0], self.target_height, self.target_width, input_shape[3]])\n\n def get_config(self):\n config = {\n 'height': self.target_height,\n 'width': self.target_width,\n }\n base_config = super(CenterCrop, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass RandomCrop(Layer):\n \"\"\"Randomly crop the images to target height and width.\n\n This layer will crop all the images in the same batch to the same cropping\n location.\n By default, random cropping is only applied during training. At inference\n time, the images will be first rescaled to preserve the shorter side, and\n center cropped. If you need to apply random cropping at inference time,\n set `training` to True when calling the layer.\n\n Input shape:\n 4D tensor with shape:\n `(samples, height, width, channels)`, data_format='channels_last'.\n\n Output shape:\n 4D tensor with shape:\n `(samples, target_height, target_width, channels)`.\n\n Arguments:\n height: Integer, the height of the output shape.\n width: Integer, the width of the output shape.\n seed: Integer. Used to create a random seed.\n \"\"\"\n\n def __init__(self, height, width, seed=None, **kwargs):\n self.height = height\n self.width = width\n self.seed = seed\n self._rng = make_generator(self.seed)\n self.input_spec = InputSpec(ndim=4)\n super(RandomCrop, self).__init__(**kwargs)\n\n def call(self, inputs, training=None):\n if training is None:\n training = K.learning_phase()\n\n def random_cropped_inputs():\n \"\"\"Cropped inputs with stateless random ops.\"\"\"\n input_shape = array_ops.shape(inputs)\n crop_size = array_ops.stack(\n [input_shape[0], self.height, self.width, input_shape[3]])\n check = control_flow_ops.Assert(\n math_ops.reduce_all(input_shape >= crop_size),\n [self.height, self.width])\n input_shape = control_flow_ops.with_dependencies([check], input_shape)\n limit = input_shape - crop_size + 1\n offset = stateless_random_ops.stateless_random_uniform(\n array_ops.shape(input_shape),\n dtype=crop_size.dtype,\n maxval=crop_size.dtype.max,\n seed=self._rng.make_seeds()[:, 0]) % limit\n return array_ops.slice(inputs, offset, crop_size)\n\n # TODO(b/143885775): Share logic with Resize and CenterCrop.\n def resize_and_center_cropped_inputs():\n \"\"\"Deterministically resize to shorter side and center crop.\"\"\"\n input_shape = array_ops.shape(inputs)\n input_height_t = input_shape[1]\n input_width_t = input_shape[2]\n ratio_cond = (input_height_t / input_width_t > 1.)\n # pylint: disable=g-long-lambda\n resized_height = tf_utils.smart_cond(\n ratio_cond,\n lambda: math_ops.cast(self.width * input_height_t / input_width_t,\n input_height_t.dtype), lambda: self.height)\n resized_width = tf_utils.smart_cond(\n ratio_cond, lambda: self.width,\n lambda: math_ops.cast(self.height * input_width_t / input_height_t,\n input_width_t.dtype))\n # pylint: enable=g-long-lambda\n resized_inputs = image_ops.resize_images_v2(\n images=inputs, size=array_ops.stack([resized_height, resized_width]))\n\n img_hd_diff = resized_height - self.height\n img_wd_diff = resized_width - self.width\n bbox_h_start = math_ops.cast(img_hd_diff / 2, dtypes.int32)\n bbox_w_start = math_ops.cast(img_wd_diff / 2, dtypes.int32)\n bbox_begin = array_ops.stack([0, bbox_h_start, bbox_w_start, 0])\n bbox_size = array_ops.stack([-1, self.height, self.width, -1])\n outputs = array_ops.slice(resized_inputs, bbox_begin, bbox_size)\n return outputs\n\n output = tf_utils.smart_cond(training, random_cropped_inputs,\n resize_and_center_cropped_inputs)\n original_shape = inputs.shape.as_list()\n batch_size, num_channels = original_shape[0], original_shape[3]\n output_shape = [batch_size] + [self.height, self.width] + [num_channels]\n output.set_shape(output_shape)\n return output\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n return tensor_shape.TensorShape(\n [input_shape[0], self.height, self.width, input_shape[3]])\n\n def get_config(self):\n config = {\n 'height': self.height,\n 'width': self.width,\n 'seed': self.seed,\n }\n base_config = super(RandomCrop, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass Rescaling(Layer):\n \"\"\"Multiply inputs by `scale`.\n\n For instance, to rescale an input in the `[0, 255]` range\n to be in the `[0, 1]` range, you would pass `scale=1./255`.\n\n The rescaling is applied both during training and inference.\n\n Input shape:\n Arbitrary.\n\n Output shape:\n Same as input.\n\n Arguments:\n scale: Float, the scale to apply to the inputs.\n \"\"\"\n\n def __init__(self, scale, **kwargs):\n self.scale = scale\n super(Rescaling, self).__init__(**kwargs)\n\n def call(self, inputs):\n dtype = self._compute_dtype\n return math_ops.cast(inputs, dtype) * math_ops.cast(self.scale, dtype)\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def get_config(self):\n config = {\n 'scale': self.scale,\n }\n base_config = super(Rescaling, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass RandomFlip(Layer):\n \"\"\"Randomly flip each image horizontally and vertically.\n\n This layer will by default flip the images horizontally and then vertically\n during training time.\n `RandomFlip(horizontal=True)` will only flip the input horizontally.\n `RandomFlip(vertical=True)` will only flip the input vertically.\n During inference time, the output will be identical to input. Call the layer\n with `training=True` to flip the input.\n\n Input shape:\n 4D tensor with shape:\n `(samples, height, width, channels)`, data_format='channels_last'.\n\n Output shape:\n 4D tensor with shape:\n `(samples, height, width, channels)`, data_format='channels_last'.\n\n Attributes:\n horizontal: Bool, whether to randomly flip horizontally.\n width: Bool, whether to randomly flip vertically.\n seed: Integer. Used to create a random seed.\n \"\"\"\n\n def __init__(self, horizontal=None, vertical=None, seed=None, **kwargs):\n # If both arguments are None, set both to True.\n if horizontal is None and vertical is None:\n self.horizontal = True\n self.vertical = True\n else:\n self.horizontal = horizontal or False\n self.vertical = vertical or False\n self.seed = seed\n self._rng = make_generator(self.seed)\n self.input_spec = InputSpec(ndim=4)\n super(RandomFlip, self).__init__(**kwargs)\n\n def call(self, inputs, training=None):\n if training is None:\n training = K.learning_phase()\n\n def random_flipped_inputs():\n flipped_outputs = inputs\n if self.horizontal:\n flipped_outputs = image_ops.random_flip_up_down(flipped_outputs,\n self.seed)\n if self.vertical:\n flipped_outputs = image_ops.random_flip_left_right(\n flipped_outputs, self.seed)\n return flipped_outputs\n\n output = tf_utils.smart_cond(training, random_flipped_inputs,\n lambda: inputs)\n output.set_shape(inputs.shape)\n return output\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def get_config(self):\n config = {\n 'horizontal': self.horizontal,\n 'vertical': self.vertical,\n 'seed': self.seed,\n }\n base_config = super(RandomFlip, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass RandomTranslation(Layer):\n \"\"\"Randomly translate each image during training.\n\n Arguments:\n height_factor: a positive float represented as fraction of value, or a tuple\n of size 2 representing lower and upper bound for shifting vertically. When\n represented as a single float, this value is used for both the upper and\n lower bound. For instance, `height_factor=(0.2, 0.3)` results in an output\n height varying in the range `[original - 20%, original + 30%]`.\n `height_factor=0.2` results in an output height varying in the range\n `[original - 20%, original + 20%]`.\n width_factor: a positive float represented as fraction of value, or a tuple\n of size 2 representing lower and upper bound for shifting horizontally.\n When represented as a single float, this value is used for both the upper\n and lower bound.\n fill_mode: Points outside the boundaries of the input are filled according\n to the given mode (one of `{'nearest', 'bilinear'}`).\n fill_value: Value used for points outside the boundaries of the input if\n `mode='constant'`.\n seed: Integer. Used to create a random seed.\n Input shape:\n 4D tensor with shape: `(samples, height, width, channels)`,\n data_format='channels_last'.\n Output shape:\n 4D tensor with shape: `(samples, height, width, channels)`,\n data_format='channels_last'.\n Raise:\n ValueError: if lower bound is not between [0, 1], or upper bound is\n negative.\n \"\"\"\n\n def __init__(self,\n height_factor,\n width_factor,\n fill_mode='nearest',\n fill_value=0.,\n seed=None,\n **kwargs):\n self.height_factor = height_factor\n if isinstance(height_factor, (tuple, list)):\n self.height_lower = abs(height_factor[0])\n self.height_upper = height_factor[1]\n else:\n self.height_lower = self.height_upper = height_factor\n if self.height_upper < 0.:\n raise ValueError('`height_factor` cannot have negative values as upper '\n 'bound, got {}'.format(height_factor))\n if abs(self.height_lower) > 1. or abs(self.height_upper) > 1.:\n raise ValueError('`height_factor` must have values between [-1, 1], '\n 'got {}'.format(height_factor))\n\n self.width_factor = width_factor\n if isinstance(width_factor, (tuple, list)):\n self.width_lower = abs(width_factor[0])\n self.width_upper = width_factor[1]\n else:\n self.width_lower = self.width_upper = width_factor\n if self.width_upper < 0.:\n raise ValueError('`width_factor` cannot have negative values as upper '\n 'bound, got {}'.format(width_factor))\n if abs(self.width_lower) > 1. or abs(self.width_upper) > 1.:\n raise ValueError('`width_factor` must have values between [-1, 1], '\n 'got {}'.format(width_factor))\n\n if fill_mode not in {'nearest', 'bilinear'}:\n raise NotImplementedError(\n '`fill_mode` {} is not supported yet.'.format(fill_mode))\n self.fill_mode = fill_mode\n self.fill_value = fill_value\n self.seed = seed\n self._rng = make_generator(self.seed)\n self.input_spec = InputSpec(ndim=4)\n super(RandomTranslation, self).__init__(**kwargs)\n\n def call(self, inputs, training=None):\n if training is None:\n training = K.learning_phase()\n\n def random_translated_inputs():\n \"\"\"Translated inputs with random ops.\"\"\"\n inputs_shape = array_ops.shape(inputs)\n batch_size = inputs_shape[0]\n h_axis, w_axis = 1, 2\n img_hd = math_ops.cast(inputs_shape[h_axis], dtypes.float32)\n img_wd = math_ops.cast(inputs_shape[w_axis], dtypes.float32)\n height_translate = self._rng.uniform(\n shape=[batch_size, 1],\n minval=-self.height_lower,\n maxval=self.height_upper)\n height_translate = height_translate * img_hd\n width_translate = self._rng.uniform(\n shape=[batch_size, 1],\n minval=-self.width_lower,\n maxval=self.width_upper)\n width_translate = width_translate * img_wd\n translations = math_ops.cast(\n array_ops.concat([height_translate, width_translate], axis=1),\n dtype=inputs.dtype)\n return transform(\n inputs,\n get_translation_matrix(translations),\n interpolation=self.fill_mode)\n\n output = tf_utils.smart_cond(training, random_translated_inputs,\n lambda: inputs)\n output.set_shape(inputs.shape)\n return output\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def get_config(self):\n config = {\n 'height_factor': self.height_factor,\n 'width_factor': self.width_factor,\n 'fill_mode': self.fill_mode,\n 'fill_value': self.fill_value,\n 'seed': self.seed,\n }\n base_config = super(RandomTranslation, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\ndef get_translation_matrix(translations, name=None):\n \"\"\"Returns projective transform(s) for the given translation(s).\n\n Args:\n translations: A matrix of 2-element lists representing [dx, dy] to translate\n for each image (for a batch of images).\n name: The name of the op.\n\n Returns:\n A tensor of shape (num_images, 8) projective transforms which can be given\n to `transform`.\n \"\"\"\n with ops.name_scope(name, 'translation_matrix'):\n num_translations = array_ops.shape(translations)[0]\n # The translation matrix looks like:\n # [[1 0 -dx]\n # [0 1 -dy]\n # [0 0 1]]\n # where the last entry is implicit.\n # Translation matrices are always float32.\n return array_ops.concat(\n values=[\n array_ops.ones((num_translations, 1), dtypes.float32),\n array_ops.zeros((num_translations, 1), dtypes.float32),\n -translations[:, 0, None],\n array_ops.zeros((num_translations, 1), dtypes.float32),\n array_ops.ones((num_translations, 1), dtypes.float32),\n -translations[:, 1, None],\n array_ops.zeros((num_translations, 2), dtypes.float32),\n ],\n axis=1)\n\n\ndef transform(images,\n transforms,\n interpolation='nearest',\n output_shape=None,\n name=None):\n \"\"\"Applies the given transform(s) to the image(s).\n\n Args:\n images: A tensor of shape (num_images, num_rows, num_columns, num_channels)\n (NHWC), (num_rows, num_columns, num_channels) (HWC), or (num_rows,\n num_columns) (HW). The rank must be statically known (the shape is not\n `TensorShape(None)`.\n transforms: Projective transform matrix/matrices. A vector of length 8 or\n tensor of size N x 8. If one row of transforms is [a0, a1, a2, b0, b1, b2,\n c0, c1], then it maps the *output* point `(x, y)` to a transformed *input*\n point `(x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k)`, where\n `k = c0 x + c1 y + 1`. The transforms are *inverted* compared to the\n transform mapping input points to output points. Note that gradients are\n not backpropagated into transformation parameters.\n interpolation: Interpolation mode. Supported values: \"NEAREST\", \"BILINEAR\".\n output_shape: Output dimesion after the transform, [height, width]. If None,\n output is the same size as input image.\n name: The name of the op.\n\n Returns:\n Image(s) with the same type and shape as `images`, with the given\n transform(s) applied. Transformed coordinates outside of the input image\n will be filled with zeros.\n\n Raises:\n TypeError: If `image` is an invalid type.\n ValueError: If output shape is not 1-D int32 Tensor.\n \"\"\"\n with ops.name_scope(name, 'transform'):\n if output_shape is None:\n output_shape = array_ops.shape(images)[1:3]\n if not context.executing_eagerly():\n output_shape_value = tensor_util.constant_value(output_shape)\n if output_shape_value is not None:\n output_shape = output_shape_value\n\n output_shape = ops.convert_to_tensor_v2(\n output_shape, dtypes.int32, name='output_shape')\n\n if not output_shape.get_shape().is_compatible_with([2]):\n raise ValueError('output_shape must be a 1-D Tensor of 2 elements: '\n 'new_height, new_width, instead got '\n '{}'.format(output_shape))\n\n return image_ops.image_projective_transform_v2(\n images,\n output_shape=output_shape,\n transforms=transforms,\n interpolation=interpolation.upper())\n\n\ndef get_rotation_matrix(angles, image_height, image_width, name=None):\n \"\"\"Returns projective transform(s) for the given angle(s).\n\n Args:\n angles: A scalar angle to rotate all images by, or (for batches of images) a\n vector with an angle to rotate each image in the batch. The rank must be\n statically known (the shape is not `TensorShape(None)`).\n image_height: Height of the image(s) to be transformed.\n image_width: Width of the image(s) to be transformed.\n name: The name of the op.\n\n Returns:\n A tensor of shape (num_images, 8). Projective transforms which can be given\n to operation `image_projective_transform_v2`. If one row of transforms is\n [a0, a1, a2, b0, b1, b2, c0, c1], then it maps the *output* point\n `(x, y)` to a transformed *input* point\n `(x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k)`,\n where `k = c0 x + c1 y + 1`.\n \"\"\"\n with ops.name_scope(name, 'rotation_matrix'):\n x_offset = ((image_width - 1) - (math_ops.cos(angles) *\n (image_width - 1) - math_ops.sin(angles) *\n (image_height - 1))) / 2.0\n y_offset = ((image_height - 1) - (math_ops.sin(angles) *\n (image_width - 1) + math_ops.cos(angles) *\n (image_height - 1))) / 2.0\n num_angles = array_ops.shape(angles)[0]\n return array_ops.concat(\n values=[\n math_ops.cos(angles)[:, None],\n -math_ops.sin(angles)[:, None],\n x_offset[:, None],\n math_ops.sin(angles)[:, None],\n math_ops.cos(angles)[:, None],\n y_offset[:, None],\n array_ops.zeros((num_angles, 2), dtypes.float32),\n ],\n axis=1)\n\n\nclass RandomRotation(Layer):\n \"\"\"Randomly rotate each image.\n\n By default, random rotations are only applied during training.\n At inference time, the layer does nothing. If you need to apply random\n rotations at inference time, set `training` to True when calling the layer.\n\n Input shape:\n 4D tensor with shape:\n `(samples, height, width, channels)`, data_format='channels_last'.\n\n Output shape:\n 4D tensor with shape:\n `(samples, height, width, channels)`, data_format='channels_last'.\n\n Attributes:\n factor: a positive float represented as fraction of 2pi, or a tuple of size\n 2 representing lower and upper bound for rotating clockwise and\n counter-clockwise. When represented as a single float, lower = upper.\n fill_mode: Points outside the boundaries of the input are filled according\n to the given mode (one of `{'constant', 'nearest', 'bilinear', 'reflect',\n 'wrap'}`).\n seed: Integer. Used to create a random seed.\n Raise:\n ValueError: if lower bound is not between [0, 1], or upper bound is\n negative.\n \"\"\"\n\n def __init__(self,\n factor,\n fill_mode='nearest',\n seed=None,\n **kwargs):\n self.factor = factor\n if isinstance(factor, (tuple, list)):\n self.lower = factor[0]\n self.upper = factor[1]\n else:\n self.lower = self.upper = factor\n if self.lower < 0. or self.upper < 0.:\n raise ValueError('Factor cannot have negative values, '\n 'got {}'.format(factor))\n if fill_mode not in {'nearest', 'bilinear'}:\n raise NotImplementedError(\n '`fill_mode` {} is not supported yet.'.format(fill_mode))\n self.fill_mode = fill_mode\n self.seed = seed\n self._rng = make_generator(self.seed)\n self.input_spec = InputSpec(ndim=4)\n super(RandomRotation, self).__init__(**kwargs)\n\n def call(self, inputs, training=None):\n if training is None:\n training = K.learning_phase()\n\n def random_rotated_inputs():\n \"\"\"Rotated inputs with random ops.\"\"\"\n inputs_shape = array_ops.shape(inputs)\n batch_size = inputs_shape[0]\n h_axis, w_axis = 1, 2\n img_hd = math_ops.cast(inputs_shape[h_axis], dtypes.float32)\n img_wd = math_ops.cast(inputs_shape[w_axis], dtypes.float32)\n min_angle = self.lower * 2. * np.pi\n max_angle = self.upper * 2. * np.pi\n angles = self._rng.uniform(\n shape=[batch_size], minval=-min_angle, maxval=max_angle)\n return transform(\n inputs,\n get_rotation_matrix(angles, img_hd, img_wd),\n interpolation=self.fill_mode)\n\n output = tf_utils.smart_cond(training, random_rotated_inputs,\n lambda: inputs)\n output.set_shape(inputs.shape)\n return output\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def get_config(self):\n config = {\n 'factor': self.factor,\n 'fill_mode': self.fill_mode,\n 'seed': self.seed,\n }\n base_config = super(RandomRotation, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass RandomZoom(Layer):\n \"\"\"Randomly zoom each image during training.\n\n Arguments:\n height_factor: a positive float represented as fraction of value, or a tuple\n of size 2 representing lower and upper bound for zooming horizontally.\n When represented as a single float, this value is used for both the\n upper and lower bound. For instance, `height_factor=(0.2, 0.3)` result in\n an output zoom varying in the range `[original * 20%, original * 30%]`.\n width_factor: a positive float represented as fraction of value, or a tuple\n of size 2 representing lower and upper bound for zooming vertically.\n When represented as a single float, this value is used for both the\n upper and lower bound. For instance, `width_factor=(0.2, 0.3)` result in\n an output zoom varying in the range `[original * 20%, original * 30%]`.\n fill_mode: Points outside the boundaries of the input are filled according\n to the given mode (one of `{'nearest', 'bilinear'}`).\n fill_value: Value used for points outside the boundaries of the input if\n `mode='constant'`.\n seed: Integer. Used to create a random seed.\n\n Input shape:\n 4D tensor with shape:\n `(samples, height, width, channels)`, data_format='channels_last'.\n\n Output shape:\n 4D tensor with shape:\n `(samples, height, width, channels)`, data_format='channels_last'.\n\n Raise:\n ValueError: if lower bound is not between [0, 1], or upper bound is\n negative.\n \"\"\"\n\n def __init__(self,\n height_factor,\n width_factor,\n fill_mode='nearest',\n fill_value=0.,\n seed=None,\n **kwargs):\n self.height_factor = height_factor\n if isinstance(height_factor, (tuple, list)):\n self.height_lower = height_factor[0]\n self.height_upper = height_factor[1]\n else:\n self.height_lower = self.height_upper = height_factor\n if self.height_lower < 0. or self.height_upper < 0.:\n raise ValueError('`height_factor` cannot have negative values, '\n 'got {}'.format(height_factor))\n if self.height_lower > self.height_upper:\n raise ValueError('`height_factor` cannot have lower bound larger than '\n 'upper bound, got {}.'.format(height_factor))\n\n self.width_factor = width_factor\n if isinstance(width_factor, (tuple, list)):\n self.width_lower = width_factor[0]\n self.width_upper = width_factor[1]\n else:\n self.width_lower = self.width_upper = width_factor\n if self.width_lower < 0. or self.width_upper < 0.:\n raise ValueError('`width_factor` cannot have negative values, '\n 'got {}'.format(width_factor))\n if self.width_lower > self.width_upper:\n raise ValueError('`width_factor` cannot have lower bound larger than '\n 'upper bound, got {}.'.format(width_factor))\n\n if fill_mode not in {'nearest', 'bilinear'}:\n raise NotImplementedError(\n '`fill_mode` {} is not supported yet.'.format(fill_mode))\n self.fill_mode = fill_mode\n self.fill_value = fill_value\n self.seed = seed\n self._rng = make_generator(self.seed)\n self.input_spec = InputSpec(ndim=4)\n super(RandomZoom, self).__init__(**kwargs)\n\n def call(self, inputs, training=None):\n if training is None:\n training = K.learning_phase()\n\n def random_zoomed_inputs():\n \"\"\"Zoomed inputs with random ops.\"\"\"\n inputs_shape = array_ops.shape(inputs)\n batch_size = inputs_shape[0]\n h_axis, w_axis = 1, 2\n img_hd = math_ops.cast(inputs_shape[h_axis], dtypes.float32)\n img_wd = math_ops.cast(inputs_shape[w_axis], dtypes.float32)\n height_zoom = self._rng.uniform(\n shape=[batch_size, 1],\n minval=-self.height_lower,\n maxval=self.height_upper)\n height_zoom = height_zoom * img_hd\n width_zoom = self._rng.uniform(\n shape=[batch_size, 1],\n minval=-self.width_lower,\n maxval=self.width_upper)\n width_zoom = width_zoom * img_wd\n zooms = math_ops.cast(\n array_ops.concat([height_zoom, width_zoom], axis=1),\n dtype=inputs.dtype)\n return transform(\n inputs, get_zoom_matrix(zooms, img_hd, img_wd),\n interpolation=self.fill_mode)\n\n output = tf_utils.smart_cond(training, random_zoomed_inputs,\n lambda: inputs)\n output.set_shape(inputs.shape)\n return output\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def get_config(self):\n config = {\n 'height_factor': self.height_factor,\n 'width_factor': self.width_factor,\n 'fill_mode': self.fill_mode,\n 'fill_value': self.fill_value,\n 'seed': self.seed,\n }\n base_config = super(RandomZoom, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\ndef get_zoom_matrix(zooms, image_height, image_width, name=None):\n \"\"\"Returns projective transform(s) for the given zoom(s).\n\n Args:\n zooms: A matrix of 2-element lists representing [zx, zy] to zoom\n for each image (for a batch of images).\n image_height: Height of the image(s) to be transformed.\n image_width: Width of the image(s) to be transformed.\n name: The name of the op.\n\n Returns:\n A tensor of shape (num_images, 8). Projective transforms which can be given\n to operation `image_projective_transform_v2`. If one row of transforms is\n [a0, a1, a2, b0, b1, b2, c0, c1], then it maps the *output* point\n `(x, y)` to a transformed *input* point\n `(x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k)`,\n where `k = c0 x + c1 y + 1`.\n \"\"\"\n with ops.name_scope(name, 'zoom_matrix'):\n num_zooms = array_ops.shape(zooms)[0]\n # The zoom matrix looks like:\n # [[zx 0 0]\n # [0 zy 0]\n # [0 0 1]]\n # where the last entry is implicit.\n # Zoom matrices are always float32.\n x_offset = ((image_height + 1.) / 2.0) * (zooms[:, 0, None] - 1.)\n y_offset = ((image_width + 1.) / 2.0) * (zooms[:, 1, None] - 1.)\n return array_ops.concat(\n values=[\n zooms[:, 0, None],\n array_ops.zeros((num_zooms, 1), dtypes.float32),\n x_offset,\n array_ops.zeros((num_zooms, 1), dtypes.float32),\n zooms[:, 1, None],\n y_offset,\n array_ops.zeros((num_zooms, 2), dtypes.float32),\n ],\n axis=1)\n\n\nclass RandomContrast(Layer):\n \"\"\"Adjust the contrast of an image or images by a random factor.\n\n Contrast is adjusted independently for each channel of each image during\n training.\n\n For each channel, this layer computes the mean of the image pixels in the\n channel and then adjusts each component `x` of each pixel to\n `(x - mean) * contrast_factor + mean`.\n\n Input shape:\n 4D tensor with shape:\n `(samples, height, width, channels)`, data_format='channels_last'.\n\n Output shape:\n 4D tensor with shape:\n `(samples, height, width, channels)`, data_format='channels_last'.\n\n Attributes:\n factor: a positive float represented as fraction of value, or a tuple\n of size 2 representing lower and upper bound. When represented as a\n single float, lower = upper. The contrast factor will be randomly picked\n between [1.0 - lower, 1.0 + upper].\n seed: Integer. Used to create a random seed.\n Raise:\n ValueError: if lower bound is not between [0, 1], or upper bound is\n negative.\n \"\"\"\n\n def __init__(self, factor, seed=None, **kwargs):\n self.factor = factor\n if isinstance(factor, (tuple, list)):\n self.lower = factor[0]\n self.upper = factor[1]\n else:\n self.lower = self.upper = factor\n if self.lower < 0. or self.upper < 0. or self.lower > 1.:\n raise ValueError('Factor cannot have negative values, '\n 'got {}'.format(factor))\n self.seed = seed\n self.input_spec = InputSpec(ndim=4)\n super(RandomContrast, self).__init__(**kwargs)\n\n def call(self, inputs, training=None):\n if training is None:\n training = K.learning_phase()\n\n def random_contrasted_inputs():\n return image_ops.random_contrast(inputs, 1. - self.lower, 1. + self.upper,\n self.seed)\n\n output = tf_utils.smart_cond(training, random_contrasted_inputs,\n lambda: inputs)\n output.set_shape(inputs.shape)\n return output\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def get_config(self):\n config = {\n 'factor': self.factor,\n 'seed': self.seed,\n }\n base_config = super(RandomContrast, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass RandomHeight(Layer):\n \"\"\"Randomly vary the height of a batch of images during training.\n\n Adjusts the height of a batch of images by a random factor. The input\n should be a 4-D tensor in the \"channels_last\" image data format.\n\n By default, this layer is inactive during inference.\n\n Arguments:\n factor: A positive float (fraction of original height), or a tuple of\n size 2 representing lower and upper bound for resizing vertically. When\n represented as a single float, this value is used for both the upper and\n lower bound. For instance, `factor=(0.2, 0.3)` results in an output height\n varying in the range `[original + 20%, original + 30%]`. `factor=(-0.2,\n 0.3)` results in an output height varying in the range `[original - 20%,\n original + 30%]`. `factor=0.2` results in an output height varying in the\n range `[original - 20%, original + 20%]`.\n interpolation: String, the interpolation method. Defaults to `bilinear`.\n Supports `bilinear`, `nearest`, `bicubic`, `area`, `lanczos3`, `lanczos5`,\n `gaussian`, `mitchellcubic`\n seed: Integer. Used to create a random seed.\n\n Input shape:\n 4D tensor with shape:\n `(samples, height, width, channels)` (data_format='channels_last').\n\n Output shape:\n 4D tensor with shape:\n `(samples, random_height, width, channels)`.\n \"\"\"\n\n def __init__(self, factor, interpolation='bilinear', seed=None, **kwargs):\n self.factor = factor\n if isinstance(factor, (tuple, list)):\n self.height_lower = -factor[0]\n self.height_upper = factor[1]\n else:\n self.height_lower = self.height_upper = factor\n if self.height_lower > 1.:\n raise ValueError('`factor` cannot have abs lower bound larger than 1.0, '\n 'got {}'.format(factor))\n self.interpolation = interpolation\n self._interpolation_method = get_interpolation(interpolation)\n self.input_spec = InputSpec(ndim=4)\n self.seed = seed\n self._rng = make_generator(self.seed)\n super(RandomHeight, self).__init__(**kwargs)\n\n def call(self, inputs, training=None):\n if training is None:\n training = K.learning_phase()\n\n def random_height_inputs():\n \"\"\"Inputs height-adjusted with random ops.\"\"\"\n inputs_shape = array_ops.shape(inputs)\n h_axis, w_axis = 1, 2\n img_hd = math_ops.cast(inputs_shape[h_axis], dtypes.float32)\n img_wd = inputs_shape[w_axis]\n height_factor = self._rng.uniform(\n shape=[],\n minval=(1.0 - self.height_lower),\n maxval=(1.0 + self.height_upper))\n adjusted_height = math_ops.cast(height_factor * img_hd, dtypes.int32)\n adjusted_size = array_ops.stack([adjusted_height, img_wd])\n output = image_ops.resize_images_v2(\n images=inputs, size=adjusted_size, method=self._interpolation_method)\n original_shape = inputs.shape.as_list()\n output_shape = [original_shape[0]] + [None] + original_shape[2:4]\n output.set_shape(output_shape)\n return output\n\n return tf_utils.smart_cond(training, random_height_inputs, lambda: inputs)\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n return tensor_shape.TensorShape(\n [input_shape[0], None, input_shape[2], input_shape[3]])\n\n def get_config(self):\n config = {\n 'factor': self.factor,\n 'interpolation': self.interpolation,\n 'seed': self.seed,\n }\n base_config = super(RandomHeight, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass RandomWidth(Layer):\n \"\"\"Randomly vary the width of a batch of images during training.\n\n Adjusts the width of a batch of images by a random factor. The input\n should be a 4-D tensor in the \"channels_last\" image data format.\n\n By default, this layer is inactive during inference.\n\n Arguments:\n factor: A positive float (fraction of original width), or a tuple of\n size 2 representing lower and upper bound for resizing horizontally. When\n represented as a single float, this value is used for both the upper and\n lower bound. For instance, `factor=(0.2, 0.3)` results in an output width\n varying in the range `[original + 20%, original + 30%]`. `factor=(-0.2,\n 0.3)` results in an output width varying in the range `[original - 20%,\n original + 30%]`. `factor=0.2` results in an output width varying in the\n range `[original - 20%, original + 20%]`.\n interpolation: String, the interpolation method. Defaults to `bilinear`.\n Supports `bilinear`, `nearest`, `bicubic`, `area`, `lanczos3`, `lanczos5`,\n `gaussian`, `mitchellcubic`\n seed: Integer. Used to create a random seed.\n\n Input shape:\n 4D tensor with shape:\n `(samples, height, width, channels)` (data_format='channels_last').\n\n Output shape:\n 4D tensor with shape:\n `(samples, random_height, width, channels)`.\n \"\"\"\n\n def __init__(self, factor, interpolation='bilinear', seed=None, **kwargs):\n self.factor = factor\n if isinstance(factor, (tuple, list)):\n self.width_lower = -factor[0]\n self.width_upper = factor[1]\n else:\n self.width_lower = self.width_upper = factor\n if self.width_lower > 1.:\n raise ValueError('`factor` cannot have abs lower bound larger than 1.0, '\n 'got {}'.format(factor))\n self.interpolation = interpolation\n self._interpolation_method = get_interpolation(interpolation)\n self.input_spec = InputSpec(ndim=4)\n self.seed = seed\n self._rng = make_generator(self.seed)\n super(RandomWidth, self).__init__(**kwargs)\n\n def call(self, inputs, training=None):\n if training is None:\n training = K.learning_phase()\n\n def random_width_inputs():\n \"\"\"Inputs width-adjusted with random ops.\"\"\"\n inputs_shape = array_ops.shape(inputs)\n h_axis, w_axis = 1, 2\n img_hd = inputs_shape[h_axis]\n img_wd = math_ops.cast(inputs_shape[w_axis], dtypes.float32)\n width_factor = self._rng.uniform(\n shape=[],\n minval=(1.0 - self.width_lower),\n maxval=(1.0 + self.width_upper))\n adjusted_width = math_ops.cast(width_factor * img_wd, dtypes.int32)\n adjusted_size = array_ops.stack([img_hd, adjusted_width])\n output = image_ops.resize_images_v2(\n images=inputs, size=adjusted_size, method=self._interpolation_method)\n original_shape = inputs.shape.as_list()\n output_shape = original_shape[0:2] + [None] + [original_shape[3]]\n output.set_shape(output_shape)\n return output\n\n return tf_utils.smart_cond(training, random_width_inputs, lambda: inputs)\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n return tensor_shape.TensorShape(\n [input_shape[0], input_shape[1], None, input_shape[3]])\n\n def get_config(self):\n config = {\n 'factor': self.factor,\n 'interpolation': self.interpolation,\n 'seed': self.seed,\n }\n base_config = super(RandomWidth, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\ndef make_generator(seed=None):\n if seed:\n return stateful_random_ops.Generator.from_seed(seed)\n else:\n return stateful_random_ops.Generator.from_non_deterministic_state()\n\n\ndef get_interpolation(interpolation):\n interpolation = interpolation.lower()\n if interpolation not in _RESIZE_METHODS:\n raise NotImplementedError(\n 'Value not recognized for `interpolation`: {}. Supported values '\n 'are: {}'.format(interpolation, _RESIZE_METHODS.keys()))\n return _RESIZE_METHODS[interpolation]\n" ]
[ [ "tensorflow.lite.testing.zip_test_utils.create_tensor_data", "tensorflow.lite.testing.zip_test_utils.register_make_test_function", "tensorflow.compat.v1.matmul", "tensorflow.compat.v1.compat.v1.placeholder", "tensorflow.lite.testing.zip_test_utils.make_zip_of_tests", "tensorflow.compat.v1.compat.forward_compatibility_horizon" ], [ "tensorflow.python.ops.image_ops.random_flip_up_down", "tensorflow.python.ops.stateful_random_ops.Generator.from_seed", "tensorflow.python.ops.stateful_random_ops.Generator.from_non_deterministic_state", "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.ops.image_ops.resize_images_v2", "tensorflow.python.ops.image_ops.random_flip_left_right", "tensorflow.python.keras.backend.learning_phase", "tensorflow.python.keras.utils.tf_utils.smart_cond", "tensorflow.python.ops.math_ops.cos", "tensorflow.python.ops.array_ops.slice", "tensorflow.python.ops.math_ops.reduce_all", "tensorflow.python.framework.tensor_util.constant_value", "tensorflow.python.framework.ops.convert_to_tensor_v2", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.ops.math_ops.sin", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.ops.control_flow_ops.with_dependencies", "tensorflow.python.ops.array_ops.ones", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.array_ops.stack", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.keras.engine.input_spec.InputSpec", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.ops.image_ops.random_contrast" ] ]