repo_name
stringlengths
6
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
sparkingdark/scikit-learn
[ "73e8b7d0a984fac8420cb4f948d53470ef9b5abf" ]
[ "sklearn/utils/tests/test_fixes.py" ]
[ "# Authors: Gael Varoquaux <[email protected]>\n# Justin Vincent\n# Lars Buitinck\n# License: BSD 3 clause\n\nimport math\n\nimport numpy as np\nimport pytest\nimport scipy.stats\n\nfrom sklearn.utils._testing import assert_array_equal\n\nfrom sklearn.utils.fixes import _joblib_parallel_args\nfrom sklearn.utils.fixes import _object_dtype_isnan\nfrom sklearn.utils.fixes import loguniform\nfrom sklearn.utils.fixes import MaskedArray\nfrom sklearn.utils.fixes import linspace, parse_version, np_version\n\n\[email protected]('joblib_version', ('0.11', '0.12.0'))\ndef test_joblib_parallel_args(monkeypatch, joblib_version):\n import joblib\n monkeypatch.setattr(joblib, '__version__', joblib_version)\n\n if joblib_version == '0.12.0':\n # arguments are simply passed through\n assert _joblib_parallel_args(prefer='threads') == {'prefer': 'threads'}\n assert _joblib_parallel_args(prefer='processes', require=None) == {\n 'prefer': 'processes', 'require': None}\n assert _joblib_parallel_args(non_existing=1) == {'non_existing': 1}\n elif joblib_version == '0.11':\n # arguments are mapped to the corresponding backend\n assert _joblib_parallel_args(prefer='threads') == {\n 'backend': 'threading'}\n assert _joblib_parallel_args(prefer='processes') == {\n 'backend': 'multiprocessing'}\n with pytest.raises(ValueError):\n _joblib_parallel_args(prefer='invalid')\n assert _joblib_parallel_args(\n prefer='processes', require='sharedmem') == {\n 'backend': 'threading'}\n with pytest.raises(ValueError):\n _joblib_parallel_args(require='invalid')\n with pytest.raises(NotImplementedError):\n _joblib_parallel_args(verbose=True)\n else:\n raise ValueError\n\n\[email protected](\"dtype, val\", ([object, 1],\n [object, \"a\"],\n [float, 1]))\ndef test_object_dtype_isnan(dtype, val):\n X = np.array([[val, np.nan],\n [np.nan, val]], dtype=dtype)\n\n expected_mask = np.array([[False, True],\n [True, False]])\n\n mask = _object_dtype_isnan(X)\n\n assert_array_equal(mask, expected_mask)\n\n\[email protected](\"low,high,base\",\n [(-1, 0, 10), (0, 2, np.exp(1)), (-1, 1, 2)])\ndef test_loguniform(low, high, base):\n rv = loguniform(base ** low, base ** high)\n assert isinstance(rv, scipy.stats._distn_infrastructure.rv_frozen)\n rvs = rv.rvs(size=2000, random_state=0)\n\n # Test the basics; right bounds, right size\n assert (base ** low <= rvs).all() and (rvs <= base ** high).all()\n assert len(rvs) == 2000\n\n # Test that it's actually (fairly) uniform\n log_rvs = np.array([math.log(x, base) for x in rvs])\n counts, _ = np.histogram(log_rvs)\n assert counts.mean() == 200\n assert np.abs(counts - counts.mean()).max() <= 40\n\n # Test that random_state works\n assert (\n loguniform(base ** low, base ** high).rvs(random_state=0)\n == loguniform(base ** low, base ** high).rvs(random_state=0)\n )\n\n\ndef test_masked_array_deprecated(): # TODO: remove in 1.0\n with pytest.warns(FutureWarning, match='is deprecated'):\n MaskedArray()\n\n\ndef test_linspace():\n \"\"\"Test that linespace works like np.linespace as of numpy version 1.16.\"\"\"\n start, stop = 0, 10\n num = 6\n out = linspace(start=start, stop=stop, num=num, endpoint=True)\n assert_array_equal(out, np.array([0., 2, 4, 6, 8, 10]))\n\n start, stop = [0, 100], [10, 1100]\n num = 6\n out = linspace(start=start, stop=stop, num=num, endpoint=True)\n res = np.c_[[0., 2, 4, 6, 8, 10],\n [100, 300, 500, 700, 900, 1100]]\n assert_array_equal(out, res)\n\n out2 = linspace(start=start, stop=stop, num=num, endpoint=True, axis=1)\n assert_array_equal(out2, out.T)\n\n out, step = linspace(\n start=start,\n stop=stop,\n num=num,\n endpoint=True,\n retstep=True,\n )\n assert_array_equal(out, res)\n assert_array_equal(step, [2, 200])\n\n if np_version < parse_version('1.16'):\n with pytest.raises(ValueError):\n linspace(start=[0, 1], stop=10)\n else:\n linspace(start=[0, 1], stop=10)\n" ]
[ [ "sklearn.utils.fixes.MaskedArray", "numpy.histogram", "numpy.array", "sklearn.utils.fixes.parse_version", "sklearn.utils._testing.assert_array_equal", "sklearn.utils.fixes._joblib_parallel_args", "sklearn.utils.fixes.linspace", "numpy.exp", "sklearn.utils.fixes._object_dtype_isnan", "sklearn.utils.fixes.loguniform" ] ]
matt-graham/differentiable-generator-networks
[ "5dcef70fe73461d56f0b79628aaba2722b09e10c" ]
[ "dgn/invertible_layers.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"Invertible density network layer definitions.\"\"\"\n\n__authors__ = 'Matt Graham'\n__license__ = 'MIT'\n\nimport numpy as np\nimport theano as th\nimport theano.tensor as tt\nimport theano.tensor.slinalg as slinalg\nfrom theano_cpu_ops import (\n log_det, lower_triangular_solve, upper_triangular_solve)\n\n\nclass DensityNetworkLayer(object):\n \"\"\" Base class for invertible density network layers. \"\"\"\n\n def __init__(self, params):\n self.params = params\n\n def param_log_prior(self):\n return tt.constant(0.)\n\n def forward_map(self, x):\n raise NotImplementedError()\n\n def inverse_map(self, y):\n raise NotImplementedError()\n\n def forward_jacobian_log_det(self, x):\n raise NotImplementedError()\n\n def compile_theano_functions(self):\n \"\"\" Compile functions from symbolic theano methods defined in class.\n\n Intended only to be used for unit testing of methods therefore not\n called by default during construction of object as generally a\n whole symbolic computational graph should be compiled from the\n composition of multiple layers rather than compiling functions for\n each layer separately.\n \"\"\"\n x_batch = tt.matrix('x_batch')\n x_point = tt.vector('x_point')\n y_batch = tt.matrix('y_batch')\n y_point = tt.vector('y_point')\n self.forward_map_batch = th.function(\n inputs=[x_batch],\n outputs=self.forward_map(x_batch)\n )\n self.forward_map_point = th.function(\n inputs=[x_point],\n outputs=self.forward_map(x_point)\n )\n self.inverse_map_batch = th.function(\n inputs=[y_batch],\n outputs=self.inverse_map(y_batch)\n )\n self.inverse_map_point = th.function(\n inputs=[y_point],\n outputs=self.inverse_map(y_point)\n )\n self.forward_jacobian_log_det_batch = th.function(\n inputs=[x_batch],\n outputs=self.forward_jacobian_log_det(x_batch),\n on_unused_input='ignore'\n )\n self.forward_jacobian_log_det_point = th.function(\n inputs=[x_point],\n outputs=self.forward_jacobian_log_det(x_point),\n on_unused_input='ignore'\n )\n\n\nclass LeapfrogLayer(DensityNetworkLayer):\n \"\"\"\n Layer applying invertible iterated leapfrog type transformation.\n \"\"\"\n\n def __init__(self, map_1, map_2, split, n_iter=1):\n self.map_1 = map_1\n self.map_2 = map_2\n self.split = split\n self.n_iter = n_iter\n super(LeapfrogLayer, self).__init__(\n self.map_1.params + self.map_2.params)\n\n def param_log_prior(self):\n return self.map_1.param_log_prior() + self.map_2.param_log_prior()\n\n def forward_map(self, x):\n if x.ndim == 1:\n x = x.reshape((1, -1))\n n_dim_orig = 1\n elif x.ndim == 2:\n n_dim_orig = 2\n else:\n raise ValueError('x must be one or two dimensional.')\n x1, x2 = x[:, :self.split], x[:, self.split:]\n for s in range(self.n_iter):\n y1 = x1 + self.map_1(x2)\n y2 = x2 + self.map_2(y1)\n x1, x2 = y1, y2\n y = tt.join(1, y1, y2)\n if n_dim_orig == 1:\n y = y.flatten()\n return y\n\n def inverse_map(self, y):\n if y.ndim == 1:\n y = y.reshape((1, -1))\n n_dim_orig = 1\n elif y.ndim == 2:\n n_dim_orig = 2\n else:\n raise ValueError('y must be one or two dimensional.')\n y1, y2 = y[:, :self.split], y[:, self.split:]\n for s in range(self.n_iter):\n x2 = y2 - self.map_2(y1)\n x1 = y1 - self.map_1(x2)\n y1, y2 = x1, x2\n x = tt.join(1, x1, x2)\n if n_dim_orig == 1:\n x = x.flatten()\n return x\n\n def forward_jacobian_log_det(self, x):\n return tt.constant(0.)\n\n\nclass AffineLayer(DensityNetworkLayer):\n \"\"\"\n Layer applying general affine transformation.\n\n Forward map: x -> W.dot(x) + b\n \"\"\"\n\n def __init__(self, weights_init, biases_init, weights_prec=0.,\n biases_prec=0., weights_mean=None, biases_mean=None):\n assert weights_init.ndim == 2, 'weights_init must be 2D array.'\n assert biases_init.ndim == 1, 'biases_init must be 1D array.'\n assert weights_init.shape[0] == biases_init.shape[0], \\\n 'Dimensions of weights_init and biases_init must be consistent.'\n self.weights = th.shared(weights_init, name='W')\n self.biases = th.shared(biases_init, name='b')\n self.weights_prec = weights_prec\n self.biases_prec = biases_prec\n if weights_mean is None:\n weights_mean = np.identity(weights_init.shape[0])\n if biases_mean is None:\n biases_mean = np.zeros_like(biases_init)\n self.weights_mean = weights_mean\n self.biases_mean = biases_mean\n super(AffineLayer, self).__init__([self.weights, self.biases])\n\n def param_log_prior(self):\n return -(0.5 * self.weights_prec *\n ((self.weights - self.weights_mean)**2).sum() +\n 0.5 * self.biases_prec *\n ((self.biases - self.biases_mean)**2).sum())\n\n def forward_map(self, x):\n return x.dot(self.weights.T) + self.biases\n\n def inverse_map(self, y):\n return slinalg.solve(self.weights, (y - self.biases).T).T\n\n def forward_jacobian_log_det(self, x):\n if x.ndim == 1:\n return log_det(self.weights)\n elif x.ndim == 2:\n return x.shape[0] * log_det(self.weights)\n else:\n raise ValueError('x must be one or two dimensional.')\n\n\nclass DiagonalAffineLayer(DensityNetworkLayer):\n \"\"\"\n Layer applying restricted affine transformation.\n\n Matrix restricted to diagonal transformation.\n\n Forward map: x -> diag(d).dot(x) + b\n \"\"\"\n\n def __init__(self, diag_weights_init, biases_init,\n diag_weights_prec=0., biases_prec=0.,\n diag_weights_mean=None, biases_mean=None):\n assert diag_weights_init.ndim == 1, (\n 'diag_weights_init must be 1D array.')\n assert biases_init.ndim == 1, 'biases_init must be 1D array.'\n assert diag_weights_init.size == biases_init.size, (\n 'Dimensions of diag_weights_init and biases_init inconsistent.')\n self.diag_weights = th.shared(diag_weights_init, name='d')\n self.biases = th.shared(biases_init, name='b')\n self.diag_weights_prec = diag_weights_prec\n self.biases_prec = biases_prec\n if diag_weights_mean is None:\n diag_weights_mean = np.ones_like(diag_weights_init)\n if biases_mean is None:\n biases_mean = np.zeros_like(biases_init)\n self.diag_weights_mean = diag_weights_mean\n self.biases_mean = biases_mean\n super(DiagonalAffineLayer, self).__init__(\n [self.diag_weights, self.biases])\n\n def param_log_prior(self):\n return -(0.5 * self.diag_weights_prec *\n ((self.diag_weights - self.diag_weights_mean)**2).sum() +\n 0.5 * self.biases_prec *\n ((self.biases - self.biases_mean)**2).sum())\n\n def forward_map(self, x):\n if x.ndim == 1:\n return x * self.diag_weights + self.biases\n elif x.ndim == 2:\n return x * self.diag_weights + self.biases\n else:\n raise ValueError('x must be one or two dimensional.')\n\n def inverse_map(self, y):\n return (y - self.biases) / self.diag_weights\n\n def forward_jacobian_log_det(self, x):\n if x.ndim == 1:\n return tt.log(tt.abs_(self.diag_weights)).sum()\n elif x.ndim == 2:\n return x.shape[0] * tt.log(tt.abs_(self.diag_weights)).sum()\n else:\n raise ValueError('x must be one or two dimensional.')\n\n\nclass DiagPlusRank1AffineLayer(DensityNetworkLayer):\n \"\"\"\n Layer applying restricted affine transformation.\n\n Matrix restricted to diagonal plus rank-1 transformation.\n\n Forward map: x -> (diag(d) + outer(u, v)).dot(x) + b\n \"\"\"\n\n def __init__(self, diag_weights_init, u_vect_init, v_vect_init,\n biases_init, diag_weights_prec=0., u_vect_prec=0.,\n v_vect_prec=0., biases_prec=0., diag_weights_mean=None,\n u_vect_mean=None, v_vect_mean=None, biases_mean=None):\n assert diag_weights_init.ndim == 1, (\n 'diag_weights_init must be 1D array.')\n assert u_vect_init.ndim == 1, 'u_vect_init must be 1D array.'\n assert v_vect_init.ndim == 1, 'v_vect_init must be 1D array.'\n assert biases_init.ndim == 1, 'biases_init must be 1D array.'\n assert (diag_weights_init.size == u_vect_init.size and\n diag_weights_init.size == v_vect_init.size and\n diag_weights_init.size == biases_init.size), (\n 'Dimensions of diag_weights_init, u_vect_unit,'\n ' v_vect_init and biases_init inconsistent.')\n self.diag_weights = th.shared(diag_weights_init, name='d')\n self.u_vect = th.shared(u_vect_init, name='u')\n self.v_vect = th.shared(v_vect_init, name='v')\n self.biases = th.shared(biases_init, name='b')\n self.diag_weights_prec = diag_weights_prec\n self.u_vect_prec = u_vect_prec\n self.v_vect_prec = v_vect_prec\n self.biases_prec = biases_prec\n if diag_weights_mean is None:\n diag_weights_mean = np.ones_like(diag_weights_init)\n if u_vect_mean is None:\n u_vect_mean = np.zeros_like(u_vect_init)\n if v_vect_mean is None:\n v_vect_mean = np.zeros_like(v_vect_init)\n if biases_mean is None:\n biases_mean = np.zeros_like(biases_init)\n self.diag_weights_mean = diag_weights_mean\n self.u_vect_mean = u_vect_mean\n self.v_vect_mean = v_vect_mean\n self.biases_mean = biases_mean\n super(DiagPlusRank1AffineLayer, self).__init__(\n [self.diag_weights, self.u_vect, self.v_vect, self.biases])\n\n def param_log_prior(self):\n return -(0.5 * self.diag_weights_prec *\n ((self.diag_weights - self.diag_weights_mean)**2).sum() +\n 0.5 * self.u_vect_prec *\n ((self.u_vect - self.u_vect_mean)**2).sum() +\n 0.5 * self.v_vect_prec *\n ((self.v_vect - self.v_vect_mean)**2).sum() +\n 0.5 * self.biases_prec *\n ((self.biases - self.biases_mean)**2).sum())\n\n def forward_map(self, x):\n if x.ndim == 1:\n return (x * self.diag_weights + self.u_vect * x.dot(self.v_vect)\n + self.biases)\n elif x.ndim == 2:\n return (x * self.diag_weights +\n self.u_vect[None, :] * (x.dot(self.v_vect)[:, None]) +\n self.biases)\n else:\n raise ValueError('x must be one or two dimensional.')\n\n def inverse_map(self, y):\n z = (y - self.biases) / self.diag_weights\n u_vect_over_diag_weights = (self.u_vect / self.diag_weights)\n if y.ndim == 1:\n return (z - u_vect_over_diag_weights *\n (z.dot(self.v_vect)) /\n (1 + self.v_vect.dot(u_vect_over_diag_weights)))\n elif y.ndim == 2:\n return (z - u_vect_over_diag_weights[None, :] *\n (z.dot(self.v_vect))[:, None] /\n (1 + self.v_vect.dot(u_vect_over_diag_weights)))\n else:\n raise ValueError('y must be one or two dimensional.')\n\n def forward_jacobian_log_det(self, x):\n if x.ndim == 1:\n return (tt.log(tt.abs_(1 + self.v_vect.dot(self.u_vect /\n self.diag_weights))) +\n tt.log(tt.abs_(self.diag_weights)).sum())\n elif x.ndim == 2:\n return x.shape[0] * (\n tt.log(tt.abs_(1 + self.v_vect.dot(self.u_vect /\n self.diag_weights))) +\n tt.log(tt.abs_(self.diag_weights)).sum()\n )\n else:\n raise ValueError('x must be one or two dimensional.')\n\n\nclass TriangularAffineLayer(DensityNetworkLayer):\n \"\"\"\n Layer applying restricted affine transformation.\n\n Matrix restricted to be triangular.\n\n Forward map:\n if lower:\n x -> tril(W).dot(x) + b\n else:\n x -> triu(W).dot(x) + b\n \"\"\"\n\n def __init__(self, weights_init, biases_init, lower=False,\n weights_prec=0., biases_prec=0., weights_mean=None,\n biases_mean=None):\n assert weights_init.ndim == 2, 'weights_init must be 2D array.'\n assert biases_init.ndim == 1, 'biases_init must be 1D array.'\n assert weights_init.shape[0] == biases_init.shape[0], \\\n 'Dimensions of weights_init and biases_init must be consistent.'\n self.lower = lower\n self.weights = th.shared(weights_init, name='W')\n self.weights_tri = (tt.tril(self.weights)\n if lower else tt.triu(self.weights))\n self.biases = th.shared(biases_init, name='b')\n self.weights_prec = weights_prec\n self.biases_prec = biases_prec\n if weights_mean is None:\n weights_mean = np.eye(weights_init.shape[0])\n if biases_mean is None:\n biases_mean = np.zeros_like(biases_init)\n self.weights_mean = (np.tril(weights_mean)\n if lower else np.triu(weights_mean))\n self.biases_mean = biases_mean\n super(TriangularAffineLayer, self).__init__(\n [self.weights, self.biases])\n\n def param_log_prior(self):\n return -(0.5 * self.weights_prec *\n ((self.weights_tri - self.weights_mean)**2).sum()\n + 0.5 * self.biases_prec *\n ((self.biases - self.biases_mean)**2).sum())\n\n def forward_map(self, x):\n return x.dot(self.weights_tri.T) + self.biases\n\n def inverse_map(self, y):\n if self.lower:\n return lower_triangular_solve(self.weights_tri,\n (y - self.biases).T).T\n else:\n return upper_triangular_solve(self.weights_tri,\n (y - self.biases).T).T\n\n def forward_jacobian_log_det(self, x):\n if x.ndim == 1:\n return tt.log(tt.abs_(tt.nlinalg.diag(self.weights))).sum()\n elif x.ndim == 2:\n return (x.shape[0] *\n tt.log(tt.abs_(tt.nlinalg.diag(self.weights))).sum())\n else:\n raise ValueError('x must be one or two dimensional.')\n\n\nclass ElementwiseLayer(DensityNetworkLayer):\n \"\"\"\n Layer applying bijective elementwise transformation.\n\n Forward map: x -> f(x)\n \"\"\"\n\n def __init__(self, forward_func, inverse_func, fudge=0.):\n self.forward_func = forward_func\n self.inverse_func = inverse_func\n self.fudge = fudge\n super(ElementwiseLayer, self).__init__([])\n\n def forward_map(self, x):\n return self.forward_func(x)\n\n def inverse_map(self, y):\n return self.inverse_func(y)\n\n def forward_jacobian_log_det(self, x):\n dy_dx, _ = th.scan(lambda x_i: th.grad(self.forward_func(x_i), x_i),\n sequences=[x.flatten()])\n if self.fudge != 0.:\n return tt.log(dy_dx + self.fudge).sum()\n else:\n return tt.log(dy_dx).sum()\n\n\nclass FwdDiagInvElementwiseLayer(DiagonalAffineLayer):\n \"\"\"\n Layer applying forward elementwise map, diagonal scaling then inverse map.\n\n Forward map: x -> f(d * g(x)) where g(f(x)) = f(g(x)) = x\n \"\"\"\n\n def __init__(self, forward_func, inverse_func,\n diag_weights_init, biases_init,\n diag_weights_prec=0., biases_prec=0.,\n diag_weights_mean=None, biases_mean=None,\n fudge=0.):\n self.forward_func = forward_func\n self.inverse_func = inverse_func\n self.fudge = fudge\n super(FwdDiagInvElementwiseLayer, self).__init__(\n diag_weights_init, biases_init, diag_weights_prec,\n biases_prec, diag_weights_mean, biases_mean)\n\n def forward_map(self, x):\n return self.forward_func(self.diag_weights * self.inverse_func(x) +\n self.biases)\n\n def inverse_map(self, y):\n return self.forward_func((self.inverse_func(y) - self.biases) /\n self.diag_weights)\n\n def forward_jacobian_log_det(self, x):\n y_sum = self.forward_map(x).sum()\n dy_dx = th.grad(y_sum, x)\n if self.fudge != 0.:\n return tt.log(dy_dx + self.fudge).sum()\n else:\n return tt.log(dy_dx).sum()\n\n\nclass PermuteDimensionsLayer(DensityNetworkLayer):\n \"\"\"\n Layer applying permutation of dimensions.\n\n Forward map: x -> x[perm]\n \"\"\"\n\n def __init__(self, perm):\n self.perm = th.shared(perm, name='perm')\n super(PermuteDimensionsLayer, self).__init__([])\n\n def forward_map(self, x):\n return tt.permute_row_elements(x, self.perm)\n\n def inverse_map(self, y):\n return tt.permute_row_elements(y, self.perm, inverse=True)\n\n def forward_jacobian_log_det(self, x):\n return tt.constant(0.)\n" ]
[ [ "numpy.zeros_like", "numpy.ones_like", "numpy.triu", "numpy.eye", "numpy.identity", "numpy.tril" ] ]
aiudirog/pandas
[ "58059c152ccf8a714eb3233f13ed22987eb42b44" ]
[ "pandas/tests/series/methods/test_fillna.py" ]
[ "from datetime import (\n datetime,\n timedelta,\n timezone,\n)\n\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas import (\n Categorical,\n DataFrame,\n DatetimeIndex,\n NaT,\n Period,\n Series,\n Timedelta,\n Timestamp,\n date_range,\n isna,\n)\nimport pandas._testing as tm\n\n\nclass TestSeriesFillNA:\n def test_fillna_nat(self):\n series = Series([0, 1, 2, NaT.value], dtype=\"M8[ns]\")\n\n filled = series.fillna(method=\"pad\")\n filled2 = series.fillna(value=series.values[2])\n\n expected = series.copy()\n expected.values[3] = expected.values[2]\n\n tm.assert_series_equal(filled, expected)\n tm.assert_series_equal(filled2, expected)\n\n df = DataFrame({\"A\": series})\n filled = df.fillna(method=\"pad\")\n filled2 = df.fillna(value=series.values[2])\n expected = DataFrame({\"A\": expected})\n tm.assert_frame_equal(filled, expected)\n tm.assert_frame_equal(filled2, expected)\n\n series = Series([NaT.value, 0, 1, 2], dtype=\"M8[ns]\")\n\n filled = series.fillna(method=\"bfill\")\n filled2 = series.fillna(value=series[1])\n\n expected = series.copy()\n expected[0] = expected[1]\n\n tm.assert_series_equal(filled, expected)\n tm.assert_series_equal(filled2, expected)\n\n df = DataFrame({\"A\": series})\n filled = df.fillna(method=\"bfill\")\n filled2 = df.fillna(value=series[1])\n expected = DataFrame({\"A\": expected})\n tm.assert_frame_equal(filled, expected)\n tm.assert_frame_equal(filled2, expected)\n\n def test_fillna(self, datetime_series):\n ts = Series([0.0, 1.0, 2.0, 3.0, 4.0], index=tm.makeDateIndex(5))\n\n tm.assert_series_equal(ts, ts.fillna(method=\"ffill\"))\n\n ts[2] = np.NaN\n\n exp = Series([0.0, 1.0, 1.0, 3.0, 4.0], index=ts.index)\n tm.assert_series_equal(ts.fillna(method=\"ffill\"), exp)\n\n exp = Series([0.0, 1.0, 3.0, 3.0, 4.0], index=ts.index)\n tm.assert_series_equal(ts.fillna(method=\"backfill\"), exp)\n\n exp = Series([0.0, 1.0, 5.0, 3.0, 4.0], index=ts.index)\n tm.assert_series_equal(ts.fillna(value=5), exp)\n\n msg = \"Must specify a fill 'value' or 'method'\"\n with pytest.raises(ValueError, match=msg):\n ts.fillna()\n\n msg = \"Cannot specify both 'value' and 'method'\"\n with pytest.raises(ValueError, match=msg):\n datetime_series.fillna(value=0, method=\"ffill\")\n\n # GH#5703\n s1 = Series([np.nan])\n s2 = Series([1])\n result = s1.fillna(s2)\n expected = Series([1.0])\n tm.assert_series_equal(result, expected)\n result = s1.fillna({})\n tm.assert_series_equal(result, s1)\n result = s1.fillna(Series((), dtype=object))\n tm.assert_series_equal(result, s1)\n result = s2.fillna(s1)\n tm.assert_series_equal(result, s2)\n result = s1.fillna({0: 1})\n tm.assert_series_equal(result, expected)\n result = s1.fillna({1: 1})\n tm.assert_series_equal(result, Series([np.nan]))\n result = s1.fillna({0: 1, 1: 1})\n tm.assert_series_equal(result, expected)\n result = s1.fillna(Series({0: 1, 1: 1}))\n tm.assert_series_equal(result, expected)\n result = s1.fillna(Series({0: 1, 1: 1}, index=[4, 5]))\n tm.assert_series_equal(result, s1)\n\n s1 = Series([0, 1, 2], list(\"abc\"))\n s2 = Series([0, np.nan, 2], list(\"bac\"))\n result = s2.fillna(s1)\n expected = Series([0, 0, 2.0], list(\"bac\"))\n tm.assert_series_equal(result, expected)\n\n # limit\n ser = Series(np.nan, index=[0, 1, 2])\n result = ser.fillna(999, limit=1)\n expected = Series([999, np.nan, np.nan], index=[0, 1, 2])\n tm.assert_series_equal(result, expected)\n\n result = ser.fillna(999, limit=2)\n expected = Series([999, 999, np.nan], index=[0, 1, 2])\n tm.assert_series_equal(result, expected)\n\n # GH#9043\n # make sure a string representation of int/float values can be filled\n # correctly without raising errors or being converted\n vals = [\"0\", \"1.5\", \"-0.3\"]\n for val in vals:\n ser = Series([0, 1, np.nan, np.nan, 4], dtype=\"float64\")\n result = ser.fillna(val)\n expected = Series([0, 1, val, val, 4], dtype=\"object\")\n tm.assert_series_equal(result, expected)\n\n def test_fillna_consistency(self):\n # GH#16402\n # fillna with a tz aware to a tz-naive, should result in object\n\n ser = Series([Timestamp(\"20130101\"), NaT])\n\n result = ser.fillna(Timestamp(\"20130101\", tz=\"US/Eastern\"))\n expected = Series(\n [Timestamp(\"20130101\"), Timestamp(\"2013-01-01\", tz=\"US/Eastern\")],\n dtype=\"object\",\n )\n tm.assert_series_equal(result, expected)\n\n # where (we ignore the errors=)\n result = ser.where(\n [True, False], Timestamp(\"20130101\", tz=\"US/Eastern\"), errors=\"ignore\"\n )\n tm.assert_series_equal(result, expected)\n\n result = ser.where(\n [True, False], Timestamp(\"20130101\", tz=\"US/Eastern\"), errors=\"ignore\"\n )\n tm.assert_series_equal(result, expected)\n\n # with a non-datetime\n result = ser.fillna(\"foo\")\n expected = Series([Timestamp(\"20130101\"), \"foo\"])\n tm.assert_series_equal(result, expected)\n\n # assignment\n ser2 = ser.copy()\n ser2[1] = \"foo\"\n tm.assert_series_equal(ser2, expected)\n\n def test_fillna_downcast(self):\n # GH#15277\n # infer int64 from float64\n ser = Series([1.0, np.nan])\n result = ser.fillna(0, downcast=\"infer\")\n expected = Series([1, 0])\n tm.assert_series_equal(result, expected)\n\n # infer int64 from float64 when fillna value is a dict\n ser = Series([1.0, np.nan])\n result = ser.fillna({1: 0}, downcast=\"infer\")\n expected = Series([1, 0])\n tm.assert_series_equal(result, expected)\n\n def test_timedelta_fillna(self, frame_or_series):\n # GH#3371\n ser = Series(\n [\n Timestamp(\"20130101\"),\n Timestamp(\"20130101\"),\n Timestamp(\"20130102\"),\n Timestamp(\"20130103 9:01:01\"),\n ]\n )\n td = ser.diff()\n obj = frame_or_series(td)\n\n # reg fillna\n result = obj.fillna(Timedelta(seconds=0))\n expected = Series(\n [\n timedelta(0),\n timedelta(0),\n timedelta(1),\n timedelta(days=1, seconds=9 * 3600 + 60 + 1),\n ]\n )\n expected = frame_or_series(expected)\n tm.assert_equal(result, expected)\n\n # interpreted as seconds, no longer supported\n msg = \"value should be a 'Timedelta', 'NaT', or array of those. Got 'int'\"\n with pytest.raises(TypeError, match=msg):\n obj.fillna(1)\n\n result = obj.fillna(Timedelta(seconds=1))\n expected = Series(\n [\n timedelta(seconds=1),\n timedelta(0),\n timedelta(1),\n timedelta(days=1, seconds=9 * 3600 + 60 + 1),\n ]\n )\n expected = frame_or_series(expected)\n tm.assert_equal(result, expected)\n\n result = obj.fillna(timedelta(days=1, seconds=1))\n expected = Series(\n [\n timedelta(days=1, seconds=1),\n timedelta(0),\n timedelta(1),\n timedelta(days=1, seconds=9 * 3600 + 60 + 1),\n ]\n )\n expected = frame_or_series(expected)\n tm.assert_equal(result, expected)\n\n result = obj.fillna(np.timedelta64(10 ** 9))\n expected = Series(\n [\n timedelta(seconds=1),\n timedelta(0),\n timedelta(1),\n timedelta(days=1, seconds=9 * 3600 + 60 + 1),\n ]\n )\n expected = frame_or_series(expected)\n tm.assert_equal(result, expected)\n\n result = obj.fillna(NaT)\n expected = Series(\n [\n NaT,\n timedelta(0),\n timedelta(1),\n timedelta(days=1, seconds=9 * 3600 + 60 + 1),\n ],\n dtype=\"m8[ns]\",\n )\n expected = frame_or_series(expected)\n tm.assert_equal(result, expected)\n\n # ffill\n td[2] = np.nan\n obj = frame_or_series(td)\n result = obj.ffill()\n expected = td.fillna(Timedelta(seconds=0))\n expected[0] = np.nan\n expected = frame_or_series(expected)\n\n tm.assert_equal(result, expected)\n\n # bfill\n td[2] = np.nan\n obj = frame_or_series(td)\n result = obj.bfill()\n expected = td.fillna(Timedelta(seconds=0))\n expected[2] = timedelta(days=1, seconds=9 * 3600 + 60 + 1)\n expected = frame_or_series(expected)\n tm.assert_equal(result, expected)\n\n def test_datetime64_fillna(self):\n\n ser = Series(\n [\n Timestamp(\"20130101\"),\n Timestamp(\"20130101\"),\n Timestamp(\"20130102\"),\n Timestamp(\"20130103 9:01:01\"),\n ]\n )\n ser[2] = np.nan\n\n # ffill\n result = ser.ffill()\n expected = Series(\n [\n Timestamp(\"20130101\"),\n Timestamp(\"20130101\"),\n Timestamp(\"20130101\"),\n Timestamp(\"20130103 9:01:01\"),\n ]\n )\n tm.assert_series_equal(result, expected)\n\n # bfill\n result = ser.bfill()\n expected = Series(\n [\n Timestamp(\"20130101\"),\n Timestamp(\"20130101\"),\n Timestamp(\"20130103 9:01:01\"),\n Timestamp(\"20130103 9:01:01\"),\n ]\n )\n tm.assert_series_equal(result, expected)\n\n # GH#6587\n # make sure that we are treating as integer when filling\n msg = \"containing strings is deprecated\"\n with tm.assert_produces_warning(FutureWarning, match=msg):\n # this also tests inference of a datetime-like with NaT's\n ser = Series([NaT, NaT, \"2013-08-05 15:30:00.000001\"])\n\n expected = Series(\n [\n \"2013-08-05 15:30:00.000001\",\n \"2013-08-05 15:30:00.000001\",\n \"2013-08-05 15:30:00.000001\",\n ],\n dtype=\"M8[ns]\",\n )\n result = ser.fillna(method=\"backfill\")\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize(\"tz\", [\"US/Eastern\", \"Asia/Tokyo\"])\n def test_datetime64_tz_fillna(self, tz):\n # DatetimeLikeBlock\n ser = Series(\n [\n Timestamp(\"2011-01-01 10:00\"),\n NaT,\n Timestamp(\"2011-01-03 10:00\"),\n NaT,\n ]\n )\n null_loc = Series([False, True, False, True])\n\n result = ser.fillna(Timestamp(\"2011-01-02 10:00\"))\n expected = Series(\n [\n Timestamp(\"2011-01-01 10:00\"),\n Timestamp(\"2011-01-02 10:00\"),\n Timestamp(\"2011-01-03 10:00\"),\n Timestamp(\"2011-01-02 10:00\"),\n ]\n )\n tm.assert_series_equal(expected, result)\n # check s is not changed\n tm.assert_series_equal(isna(ser), null_loc)\n\n result = ser.fillna(Timestamp(\"2011-01-02 10:00\", tz=tz))\n expected = Series(\n [\n Timestamp(\"2011-01-01 10:00\"),\n Timestamp(\"2011-01-02 10:00\", tz=tz),\n Timestamp(\"2011-01-03 10:00\"),\n Timestamp(\"2011-01-02 10:00\", tz=tz),\n ]\n )\n tm.assert_series_equal(expected, result)\n tm.assert_series_equal(isna(ser), null_loc)\n\n result = ser.fillna(\"AAA\")\n expected = Series(\n [\n Timestamp(\"2011-01-01 10:00\"),\n \"AAA\",\n Timestamp(\"2011-01-03 10:00\"),\n \"AAA\",\n ],\n dtype=object,\n )\n tm.assert_series_equal(expected, result)\n tm.assert_series_equal(isna(ser), null_loc)\n\n result = ser.fillna(\n {\n 1: Timestamp(\"2011-01-02 10:00\", tz=tz),\n 3: Timestamp(\"2011-01-04 10:00\"),\n }\n )\n expected = Series(\n [\n Timestamp(\"2011-01-01 10:00\"),\n Timestamp(\"2011-01-02 10:00\", tz=tz),\n Timestamp(\"2011-01-03 10:00\"),\n Timestamp(\"2011-01-04 10:00\"),\n ]\n )\n tm.assert_series_equal(expected, result)\n tm.assert_series_equal(isna(ser), null_loc)\n\n result = ser.fillna(\n {1: Timestamp(\"2011-01-02 10:00\"), 3: Timestamp(\"2011-01-04 10:00\")}\n )\n expected = Series(\n [\n Timestamp(\"2011-01-01 10:00\"),\n Timestamp(\"2011-01-02 10:00\"),\n Timestamp(\"2011-01-03 10:00\"),\n Timestamp(\"2011-01-04 10:00\"),\n ]\n )\n tm.assert_series_equal(expected, result)\n tm.assert_series_equal(isna(ser), null_loc)\n\n # DatetimeTZBlock\n idx = DatetimeIndex([\"2011-01-01 10:00\", NaT, \"2011-01-03 10:00\", NaT], tz=tz)\n ser = Series(idx)\n assert ser.dtype == f\"datetime64[ns, {tz}]\"\n tm.assert_series_equal(isna(ser), null_loc)\n\n result = ser.fillna(Timestamp(\"2011-01-02 10:00\"))\n expected = Series(\n [\n Timestamp(\"2011-01-01 10:00\", tz=tz),\n Timestamp(\"2011-01-02 10:00\"),\n Timestamp(\"2011-01-03 10:00\", tz=tz),\n Timestamp(\"2011-01-02 10:00\"),\n ]\n )\n tm.assert_series_equal(expected, result)\n tm.assert_series_equal(isna(ser), null_loc)\n\n result = ser.fillna(Timestamp(\"2011-01-02 10:00\", tz=tz))\n idx = DatetimeIndex(\n [\n \"2011-01-01 10:00\",\n \"2011-01-02 10:00\",\n \"2011-01-03 10:00\",\n \"2011-01-02 10:00\",\n ],\n tz=tz,\n )\n expected = Series(idx)\n tm.assert_series_equal(expected, result)\n tm.assert_series_equal(isna(ser), null_loc)\n\n result = ser.fillna(Timestamp(\"2011-01-02 10:00\", tz=tz).to_pydatetime())\n idx = DatetimeIndex(\n [\n \"2011-01-01 10:00\",\n \"2011-01-02 10:00\",\n \"2011-01-03 10:00\",\n \"2011-01-02 10:00\",\n ],\n tz=tz,\n )\n expected = Series(idx)\n tm.assert_series_equal(expected, result)\n tm.assert_series_equal(isna(ser), null_loc)\n\n result = ser.fillna(\"AAA\")\n expected = Series(\n [\n Timestamp(\"2011-01-01 10:00\", tz=tz),\n \"AAA\",\n Timestamp(\"2011-01-03 10:00\", tz=tz),\n \"AAA\",\n ],\n dtype=object,\n )\n tm.assert_series_equal(expected, result)\n tm.assert_series_equal(isna(ser), null_loc)\n\n result = ser.fillna(\n {\n 1: Timestamp(\"2011-01-02 10:00\", tz=tz),\n 3: Timestamp(\"2011-01-04 10:00\"),\n }\n )\n expected = Series(\n [\n Timestamp(\"2011-01-01 10:00\", tz=tz),\n Timestamp(\"2011-01-02 10:00\", tz=tz),\n Timestamp(\"2011-01-03 10:00\", tz=tz),\n Timestamp(\"2011-01-04 10:00\"),\n ]\n )\n tm.assert_series_equal(expected, result)\n tm.assert_series_equal(isna(ser), null_loc)\n\n result = ser.fillna(\n {\n 1: Timestamp(\"2011-01-02 10:00\", tz=tz),\n 3: Timestamp(\"2011-01-04 10:00\", tz=tz),\n }\n )\n expected = Series(\n [\n Timestamp(\"2011-01-01 10:00\", tz=tz),\n Timestamp(\"2011-01-02 10:00\", tz=tz),\n Timestamp(\"2011-01-03 10:00\", tz=tz),\n Timestamp(\"2011-01-04 10:00\", tz=tz),\n ]\n )\n tm.assert_series_equal(expected, result)\n tm.assert_series_equal(isna(ser), null_loc)\n\n # filling with a naive/other zone, coerce to object\n result = ser.fillna(Timestamp(\"20130101\"))\n expected = Series(\n [\n Timestamp(\"2011-01-01 10:00\", tz=tz),\n Timestamp(\"2013-01-01\"),\n Timestamp(\"2011-01-03 10:00\", tz=tz),\n Timestamp(\"2013-01-01\"),\n ]\n )\n tm.assert_series_equal(expected, result)\n tm.assert_series_equal(isna(ser), null_loc)\n\n result = ser.fillna(Timestamp(\"20130101\", tz=\"US/Pacific\"))\n expected = Series(\n [\n Timestamp(\"2011-01-01 10:00\", tz=tz),\n Timestamp(\"2013-01-01\", tz=\"US/Pacific\"),\n Timestamp(\"2011-01-03 10:00\", tz=tz),\n Timestamp(\"2013-01-01\", tz=\"US/Pacific\"),\n ]\n )\n tm.assert_series_equal(expected, result)\n tm.assert_series_equal(isna(ser), null_loc)\n\n def test_fillna_dt64tz_with_method(self):\n # with timezone\n # GH#15855\n ser = Series([Timestamp(\"2012-11-11 00:00:00+01:00\"), NaT])\n exp = Series(\n [\n Timestamp(\"2012-11-11 00:00:00+01:00\"),\n Timestamp(\"2012-11-11 00:00:00+01:00\"),\n ]\n )\n tm.assert_series_equal(ser.fillna(method=\"pad\"), exp)\n\n ser = Series([NaT, Timestamp(\"2012-11-11 00:00:00+01:00\")])\n exp = Series(\n [\n Timestamp(\"2012-11-11 00:00:00+01:00\"),\n Timestamp(\"2012-11-11 00:00:00+01:00\"),\n ]\n )\n tm.assert_series_equal(ser.fillna(method=\"bfill\"), exp)\n\n def test_fillna_pytimedelta(self):\n # GH#8209\n ser = Series([np.nan, Timedelta(\"1 days\")], index=[\"A\", \"B\"])\n\n result = ser.fillna(timedelta(1))\n expected = Series(Timedelta(\"1 days\"), index=[\"A\", \"B\"])\n tm.assert_series_equal(result, expected)\n\n def test_fillna_period(self):\n # GH#13737\n ser = Series([Period(\"2011-01\", freq=\"M\"), Period(\"NaT\", freq=\"M\")])\n\n res = ser.fillna(Period(\"2012-01\", freq=\"M\"))\n exp = Series([Period(\"2011-01\", freq=\"M\"), Period(\"2012-01\", freq=\"M\")])\n tm.assert_series_equal(res, exp)\n assert res.dtype == \"Period[M]\"\n\n def test_fillna_dt64_timestamp(self, frame_or_series):\n ser = Series(\n [\n Timestamp(\"20130101\"),\n Timestamp(\"20130101\"),\n Timestamp(\"20130102\"),\n Timestamp(\"20130103 9:01:01\"),\n ]\n )\n ser[2] = np.nan\n obj = frame_or_series(ser)\n\n # reg fillna\n result = obj.fillna(Timestamp(\"20130104\"))\n expected = Series(\n [\n Timestamp(\"20130101\"),\n Timestamp(\"20130101\"),\n Timestamp(\"20130104\"),\n Timestamp(\"20130103 9:01:01\"),\n ]\n )\n expected = frame_or_series(expected)\n tm.assert_equal(result, expected)\n\n result = obj.fillna(NaT)\n expected = obj\n tm.assert_equal(result, expected)\n\n def test_fillna_dt64_non_nao(self):\n # GH#27419\n ser = Series([Timestamp(\"2010-01-01\"), NaT, Timestamp(\"2000-01-01\")])\n val = np.datetime64(\"1975-04-05\", \"ms\")\n\n result = ser.fillna(val)\n expected = Series(\n [Timestamp(\"2010-01-01\"), Timestamp(\"1975-04-05\"), Timestamp(\"2000-01-01\")]\n )\n tm.assert_series_equal(result, expected)\n\n def test_fillna_numeric_inplace(self):\n x = Series([np.nan, 1.0, np.nan, 3.0, np.nan], [\"z\", \"a\", \"b\", \"c\", \"d\"])\n y = x.copy()\n\n return_value = y.fillna(value=0, inplace=True)\n assert return_value is None\n\n expected = x.fillna(value=0)\n tm.assert_series_equal(y, expected)\n\n # ---------------------------------------------------------------\n # CategoricalDtype\n\n @pytest.mark.parametrize(\n \"fill_value, expected_output\",\n [\n (\"a\", [\"a\", \"a\", \"b\", \"a\", \"a\"]),\n ({1: \"a\", 3: \"b\", 4: \"b\"}, [\"a\", \"a\", \"b\", \"b\", \"b\"]),\n ({1: \"a\"}, [\"a\", \"a\", \"b\", np.nan, np.nan]),\n ({1: \"a\", 3: \"b\"}, [\"a\", \"a\", \"b\", \"b\", np.nan]),\n (Series(\"a\"), [\"a\", np.nan, \"b\", np.nan, np.nan]),\n (Series(\"a\", index=[1]), [\"a\", \"a\", \"b\", np.nan, np.nan]),\n (Series({1: \"a\", 3: \"b\"}), [\"a\", \"a\", \"b\", \"b\", np.nan]),\n (Series([\"a\", \"b\"], index=[3, 4]), [\"a\", np.nan, \"b\", \"a\", \"b\"]),\n ],\n )\n def test_fillna_categorical(self, fill_value, expected_output):\n # GH#17033\n # Test fillna for a Categorical series\n data = [\"a\", np.nan, \"b\", np.nan, np.nan]\n ser = Series(Categorical(data, categories=[\"a\", \"b\"]))\n exp = Series(Categorical(expected_output, categories=[\"a\", \"b\"]))\n result = ser.fillna(fill_value)\n tm.assert_series_equal(result, exp)\n\n @pytest.mark.parametrize(\n \"fill_value, expected_output\",\n [\n (Series([\"a\", \"b\", \"c\", \"d\", \"e\"]), [\"a\", \"b\", \"b\", \"d\", \"e\"]),\n (Series([\"b\", \"d\", \"a\", \"d\", \"a\"]), [\"a\", \"d\", \"b\", \"d\", \"a\"]),\n (\n Series(\n Categorical(\n [\"b\", \"d\", \"a\", \"d\", \"a\"], categories=[\"b\", \"c\", \"d\", \"e\", \"a\"]\n )\n ),\n [\"a\", \"d\", \"b\", \"d\", \"a\"],\n ),\n ],\n )\n def test_fillna_categorical_with_new_categories(self, fill_value, expected_output):\n # GH#26215\n data = [\"a\", np.nan, \"b\", np.nan, np.nan]\n ser = Series(Categorical(data, categories=[\"a\", \"b\", \"c\", \"d\", \"e\"]))\n exp = Series(Categorical(expected_output, categories=[\"a\", \"b\", \"c\", \"d\", \"e\"]))\n result = ser.fillna(fill_value)\n tm.assert_series_equal(result, exp)\n\n def test_fillna_categorical_raises(self):\n data = [\"a\", np.nan, \"b\", np.nan, np.nan]\n ser = Series(Categorical(data, categories=[\"a\", \"b\"]))\n cat = ser._values\n\n msg = \"Cannot setitem on a Categorical with a new category\"\n with pytest.raises(TypeError, match=msg):\n ser.fillna(\"d\")\n\n msg2 = \"Length of 'value' does not match.\"\n with pytest.raises(ValueError, match=msg2):\n cat.fillna(Series(\"d\"))\n\n with pytest.raises(TypeError, match=msg):\n ser.fillna({1: \"d\", 3: \"a\"})\n\n msg = '\"value\" parameter must be a scalar or dict, but you passed a \"list\"'\n with pytest.raises(TypeError, match=msg):\n ser.fillna([\"a\", \"b\"])\n\n msg = '\"value\" parameter must be a scalar or dict, but you passed a \"tuple\"'\n with pytest.raises(TypeError, match=msg):\n ser.fillna((\"a\", \"b\"))\n\n msg = (\n '\"value\" parameter must be a scalar, dict '\n 'or Series, but you passed a \"DataFrame\"'\n )\n with pytest.raises(TypeError, match=msg):\n ser.fillna(DataFrame({1: [\"a\"], 3: [\"b\"]}))\n\n # ---------------------------------------------------------------\n # Invalid Usages\n\n def test_fillna_invalid_method(self, datetime_series):\n try:\n datetime_series.fillna(method=\"ffil\")\n except ValueError as inst:\n assert \"ffil\" in str(inst)\n\n def test_fillna_listlike_invalid(self):\n ser = Series(np.random.randint(-100, 100, 50))\n msg = '\"value\" parameter must be a scalar or dict, but you passed a \"list\"'\n with pytest.raises(TypeError, match=msg):\n ser.fillna([1, 2])\n\n msg = '\"value\" parameter must be a scalar or dict, but you passed a \"tuple\"'\n with pytest.raises(TypeError, match=msg):\n ser.fillna((1, 2))\n\n def test_fillna_method_and_limit_invalid(self):\n\n # related GH#9217, make sure limit is an int and greater than 0\n ser = Series([1, 2, 3, None])\n msg = (\n r\"Cannot specify both 'value' and 'method'\\.|\"\n r\"Limit must be greater than 0|\"\n \"Limit must be an integer\"\n )\n for limit in [-1, 0, 1.0, 2.0]:\n for method in [\"backfill\", \"bfill\", \"pad\", \"ffill\", None]:\n with pytest.raises(ValueError, match=msg):\n ser.fillna(1, limit=limit, method=method)\n\n def test_fillna_datetime64_with_timezone_tzinfo(self):\n # https://github.com/pandas-dev/pandas/issues/38851\n # different tzinfos representing UTC treated as equal\n ser = Series(date_range(\"2020\", periods=3, tz=\"UTC\"))\n expected = ser.copy()\n ser[1] = NaT\n result = ser.fillna(datetime(2020, 1, 2, tzinfo=timezone.utc))\n tm.assert_series_equal(result, expected)\n\n # but we dont (yet) consider distinct tzinfos for non-UTC tz equivalent\n ts = Timestamp(\"2000-01-01\", tz=\"US/Pacific\")\n ser2 = Series(ser._values.tz_convert(\"dateutil/US/Pacific\"))\n result = ser2.fillna(ts)\n expected = Series([ser[0], ts, ser[2]], dtype=object)\n tm.assert_series_equal(result, expected)\n\n def test_fillna_pos_args_deprecation(self):\n # https://github.com/pandas-dev/pandas/issues/41485\n srs = Series([1, 2, 3, np.nan], dtype=float)\n msg = (\n r\"In a future version of pandas all arguments of Series.fillna \"\n r\"except for the argument 'value' will be keyword-only\"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = srs.fillna(0, None, None)\n expected = Series([1, 2, 3, 0], dtype=float)\n tm.assert_series_equal(result, expected)\n\n\nclass TestFillnaPad:\n def test_fillna_bug(self):\n ser = Series([np.nan, 1.0, np.nan, 3.0, np.nan], [\"z\", \"a\", \"b\", \"c\", \"d\"])\n filled = ser.fillna(method=\"ffill\")\n expected = Series([np.nan, 1.0, 1.0, 3.0, 3.0], ser.index)\n tm.assert_series_equal(filled, expected)\n\n filled = ser.fillna(method=\"bfill\")\n expected = Series([1.0, 1.0, 3.0, 3.0, np.nan], ser.index)\n tm.assert_series_equal(filled, expected)\n\n def test_ffill(self):\n ts = Series([0.0, 1.0, 2.0, 3.0, 4.0], index=tm.makeDateIndex(5))\n ts[2] = np.NaN\n tm.assert_series_equal(ts.ffill(), ts.fillna(method=\"ffill\"))\n\n def test_ffill_pos_args_deprecation(self):\n # https://github.com/pandas-dev/pandas/issues/41485\n ser = Series([1, 2, 3])\n msg = (\n r\"In a future version of pandas all arguments of Series.ffill \"\n r\"will be keyword-only\"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = ser.ffill(0)\n expected = Series([1, 2, 3])\n tm.assert_series_equal(result, expected)\n\n def test_ffill_mixed_dtypes_without_missing_data(self):\n # GH#14956\n series = Series([datetime(2015, 1, 1, tzinfo=pytz.utc), 1])\n result = series.ffill()\n tm.assert_series_equal(series, result)\n\n def test_bfill(self):\n ts = Series([0.0, 1.0, 2.0, 3.0, 4.0], index=tm.makeDateIndex(5))\n ts[2] = np.NaN\n tm.assert_series_equal(ts.bfill(), ts.fillna(method=\"bfill\"))\n\n def test_bfill_pos_args_deprecation(self):\n # https://github.com/pandas-dev/pandas/issues/41485\n ser = Series([1, 2, 3])\n msg = (\n r\"In a future version of pandas all arguments of Series.bfill \"\n r\"will be keyword-only\"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = ser.bfill(0)\n expected = Series([1, 2, 3])\n tm.assert_series_equal(result, expected)\n\n def test_pad_nan(self):\n x = Series(\n [np.nan, 1.0, np.nan, 3.0, np.nan], [\"z\", \"a\", \"b\", \"c\", \"d\"], dtype=float\n )\n\n return_value = x.fillna(method=\"pad\", inplace=True)\n assert return_value is None\n\n expected = Series(\n [np.nan, 1.0, 1.0, 3.0, 3.0], [\"z\", \"a\", \"b\", \"c\", \"d\"], dtype=float\n )\n tm.assert_series_equal(x[1:], expected[1:])\n assert np.isnan(x[0]), np.isnan(expected[0])\n\n def test_series_fillna_limit(self):\n index = np.arange(10)\n s = Series(np.random.randn(10), index=index)\n\n result = s[:2].reindex(index)\n result = result.fillna(method=\"pad\", limit=5)\n\n expected = s[:2].reindex(index).fillna(method=\"pad\")\n expected[-3:] = np.nan\n tm.assert_series_equal(result, expected)\n\n result = s[-2:].reindex(index)\n result = result.fillna(method=\"bfill\", limit=5)\n\n expected = s[-2:].reindex(index).fillna(method=\"backfill\")\n expected[:3] = np.nan\n tm.assert_series_equal(result, expected)\n\n def test_series_pad_backfill_limit(self):\n index = np.arange(10)\n s = Series(np.random.randn(10), index=index)\n\n result = s[:2].reindex(index, method=\"pad\", limit=5)\n\n expected = s[:2].reindex(index).fillna(method=\"pad\")\n expected[-3:] = np.nan\n tm.assert_series_equal(result, expected)\n\n result = s[-2:].reindex(index, method=\"backfill\", limit=5)\n\n expected = s[-2:].reindex(index).fillna(method=\"backfill\")\n expected[:3] = np.nan\n tm.assert_series_equal(result, expected)\n\n def test_fillna_int(self):\n ser = Series(np.random.randint(-100, 100, 50))\n return_value = ser.fillna(method=\"ffill\", inplace=True)\n assert return_value is None\n tm.assert_series_equal(ser.fillna(method=\"ffill\", inplace=False), ser)\n\n def test_datetime64tz_fillna_round_issue(self):\n # GH#14872\n\n data = Series(\n [NaT, NaT, datetime(2016, 12, 12, 22, 24, 6, 100001, tzinfo=pytz.utc)]\n )\n\n filled = data.fillna(method=\"bfill\")\n\n expected = Series(\n [\n datetime(2016, 12, 12, 22, 24, 6, 100001, tzinfo=pytz.utc),\n datetime(2016, 12, 12, 22, 24, 6, 100001, tzinfo=pytz.utc),\n datetime(2016, 12, 12, 22, 24, 6, 100001, tzinfo=pytz.utc),\n ]\n )\n\n tm.assert_series_equal(filled, expected)\n" ]
[ [ "pandas.DatetimeIndex", "pandas.Timestamp", "pandas._testing.assert_series_equal", "pandas._testing.makeDateIndex", "pandas.Timedelta", "pandas.DataFrame", "numpy.arange", "numpy.random.randint", "pandas.Period", "numpy.random.randn", "pandas._testing.assert_frame_equal", "numpy.timedelta64", "pandas._testing.assert_equal", "numpy.datetime64", "numpy.isnan", "pandas.isna", "pandas._testing.assert_produces_warning", "pandas.date_range", "pandas.Categorical", "pandas.Series" ] ]
joycenerd/rsna-pneumonia-detection
[ "671c345533461ec497ee6b9cfd52ddcd5c59c942" ]
[ "yolov5/utils/datasets.py" ]
[ "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nDataloaders and dataset utils\n\"\"\"\n\nimport glob\nimport hashlib\nimport json\nimport os\nimport random\nimport shutil\nimport time\nfrom itertools import repeat\nfrom multiprocessing.pool import Pool, ThreadPool\nfrom pathlib import Path\nfrom threading import Thread\nfrom zipfile import ZipFile\n\nimport cv2\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport yaml\nfrom PIL import ExifTags, Image, ImageOps\nfrom torch.utils.data import DataLoader, Dataset, dataloader, distributed\nfrom tqdm import tqdm\n\nfrom utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective\nfrom utils.general import (LOGGER, check_dataset, check_requirements, check_yaml, clean_str, segments2boxes, xyn2xy,\n xywh2xyxy, xywhn2xyxy, xyxy2xywhn)\nfrom utils.torch_utils import torch_distributed_zero_first\n\n# Parameters\nHELP_URL = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'\nIMG_FORMATS = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes\nVID_FORMATS = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes\nWORLD_SIZE = int(os.getenv('WORLD_SIZE', 1)) # DPP\nNUM_THREADS = min(8, os.cpu_count()) # number of multiprocessing threads\n\n# Get orientation exif tag\nfor orientation in ExifTags.TAGS.keys():\n if ExifTags.TAGS[orientation] == 'Orientation':\n break\n\n\ndef get_hash(paths):\n # Returns a single hash value of a list of paths (files or dirs)\n size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes\n h = hashlib.md5(str(size).encode()) # hash sizes\n h.update(''.join(paths).encode()) # hash paths\n return h.hexdigest() # return hash\n\n\ndef exif_size(img):\n # Returns exif-corrected PIL size\n s = img.size # (width, height)\n try:\n rotation = dict(img._getexif().items())[orientation]\n if rotation == 6: # rotation 270\n s = (s[1], s[0])\n elif rotation == 8: # rotation 90\n s = (s[1], s[0])\n except:\n pass\n\n return s\n\n\ndef exif_transpose(image):\n \"\"\"\n Transpose a PIL image accordingly if it has an EXIF Orientation tag.\n Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose()\n\n :param image: The image to transpose.\n :return: An image.\n \"\"\"\n exif = image.getexif()\n orientation = exif.get(0x0112, 1) # default 1\n if orientation > 1:\n method = {2: Image.FLIP_LEFT_RIGHT,\n 3: Image.ROTATE_180,\n 4: Image.FLIP_TOP_BOTTOM,\n 5: Image.TRANSPOSE,\n 6: Image.ROTATE_270,\n 7: Image.TRANSVERSE,\n 8: Image.ROTATE_90,\n }.get(orientation)\n if method is not None:\n image = image.transpose(method)\n del exif[0x0112]\n image.info[\"exif\"] = exif.tobytes()\n return image\n\n\ndef create_dataloader(path, imgsz, batch_size, stride, single_cls=False, hyp=None, augment=False, cache=False, pad=0.0,\n rect=False, rank=-1, workers=8, image_weights=False, quad=False, prefix='', shuffle=False):\n if rect and shuffle:\n LOGGER.warning('WARNING: --rect is incompatible with DataLoader shuffle, setting shuffle=False')\n shuffle = False\n with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP\n dataset = LoadImagesAndLabels(path, imgsz, batch_size,\n augment=augment, # augmentation\n hyp=hyp, # hyperparameters\n rect=rect, # rectangular batches\n cache_images=cache,\n single_cls=single_cls,\n stride=int(stride),\n pad=pad,\n image_weights=image_weights,\n prefix=prefix)\n\n batch_size = min(batch_size, len(dataset))\n nw = min([os.cpu_count() // WORLD_SIZE, batch_size if batch_size > 1 else 0, workers]) # number of workers\n sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)\n loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates\n return loader(dataset,\n batch_size=batch_size,\n shuffle=shuffle and sampler is None,\n num_workers=nw,\n sampler=sampler,\n pin_memory=True,\n collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn), dataset\n\n\nclass InfiniteDataLoader(dataloader.DataLoader):\n \"\"\" Dataloader that reuses workers\n\n Uses same syntax as vanilla DataLoader\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))\n self.iterator = super().__iter__()\n\n def __len__(self):\n return len(self.batch_sampler.sampler)\n\n def __iter__(self):\n for i in range(len(self)):\n yield next(self.iterator)\n\n\nclass _RepeatSampler:\n \"\"\" Sampler that repeats forever\n\n Args:\n sampler (Sampler)\n \"\"\"\n\n def __init__(self, sampler):\n self.sampler = sampler\n\n def __iter__(self):\n while True:\n yield from iter(self.sampler)\n\n\nclass LoadImages:\n # YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4`\n def __init__(self, path, img_size=640, stride=32, auto=True):\n p = str(Path(path).resolve()) # os-agnostic absolute path\n if '*' in p:\n files = sorted(glob.glob(p, recursive=True)) # glob\n elif os.path.isdir(p):\n files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir\n elif os.path.isfile(p):\n files = [p] # files\n else:\n raise Exception(f'ERROR: {p} does not exist')\n\n images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]\n videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]\n ni, nv = len(images), len(videos)\n\n self.img_size = img_size\n self.stride = stride\n self.files = images + videos\n self.nf = ni + nv # number of files\n self.video_flag = [False] * ni + [True] * nv\n self.mode = 'image'\n self.auto = auto\n if any(videos):\n self.new_video(videos[0]) # new video\n else:\n self.cap = None\n assert self.nf > 0, f'No images or videos found in {p}. ' \\\n f'Supported formats are:\\nimages: {IMG_FORMATS}\\nvideos: {VID_FORMATS}'\n\n def __iter__(self):\n self.count = 0\n return self\n\n def __next__(self):\n if self.count == self.nf:\n raise StopIteration\n path = self.files[self.count]\n\n if self.video_flag[self.count]:\n # Read video\n self.mode = 'video'\n ret_val, img0 = self.cap.read()\n if not ret_val:\n self.count += 1\n self.cap.release()\n if self.count == self.nf: # last video\n raise StopIteration\n else:\n path = self.files[self.count]\n self.new_video(path)\n ret_val, img0 = self.cap.read()\n\n self.frame += 1\n s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: '\n\n else:\n # Read image\n self.count += 1\n img0 = cv2.imread(path) # BGR\n assert img0 is not None, f'Image Not Found {path}'\n s = f'image {self.count}/{self.nf} {path}: '\n\n # Padded resize\n img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0]\n\n # Convert\n img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB\n img = np.ascontiguousarray(img)\n\n return path, img, img0, self.cap, s\n\n def new_video(self, path):\n self.frame = 0\n self.cap = cv2.VideoCapture(path)\n self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\n def __len__(self):\n return self.nf # number of files\n\n\nclass LoadWebcam: # for inference\n # YOLOv5 local webcam dataloader, i.e. `python detect.py --source 0`\n def __init__(self, pipe='0', img_size=640, stride=32):\n self.img_size = img_size\n self.stride = stride\n self.pipe = eval(pipe) if pipe.isnumeric() else pipe\n self.cap = cv2.VideoCapture(self.pipe) # video capture object\n self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size\n\n def __iter__(self):\n self.count = -1\n return self\n\n def __next__(self):\n self.count += 1\n if cv2.waitKey(1) == ord('q'): # q to quit\n self.cap.release()\n cv2.destroyAllWindows()\n raise StopIteration\n\n # Read frame\n ret_val, img0 = self.cap.read()\n img0 = cv2.flip(img0, 1) # flip left-right\n\n # Print\n assert ret_val, f'Camera Error {self.pipe}'\n img_path = 'webcam.jpg'\n s = f'webcam {self.count}: '\n\n # Padded resize\n img = letterbox(img0, self.img_size, stride=self.stride)[0]\n\n # Convert\n img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB\n img = np.ascontiguousarray(img)\n\n return img_path, img, img0, None, s\n\n def __len__(self):\n return 0\n\n\nclass LoadStreams:\n # YOLOv5 streamloader, i.e. `python detect.py --source 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP streams`\n def __init__(self, sources='streams.txt', img_size=640, stride=32, auto=True):\n self.mode = 'stream'\n self.img_size = img_size\n self.stride = stride\n\n if os.path.isfile(sources):\n with open(sources) as f:\n sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]\n else:\n sources = [sources]\n\n n = len(sources)\n self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n\n self.sources = [clean_str(x) for x in sources] # clean source names for later\n self.auto = auto\n for i, s in enumerate(sources): # index, source\n # Start thread to read frames from video stream\n st = f'{i + 1}/{n}: {s}... '\n if 'youtube.com/' in s or 'youtu.be/' in s: # if source is YouTube video\n check_requirements(('pafy', 'youtube_dl'))\n import pafy\n s = pafy.new(s).getbest(preftype=\"mp4\").url # YouTube URL\n s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam\n cap = cv2.VideoCapture(s)\n assert cap.isOpened(), f'{st}Failed to open {s}'\n w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n self.fps[i] = max(cap.get(cv2.CAP_PROP_FPS) % 100, 0) or 30.0 # 30 FPS fallback\n self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback\n\n _, self.imgs[i] = cap.read() # guarantee first frame\n self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True)\n LOGGER.info(f\"{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)\")\n self.threads[i].start()\n LOGGER.info('') # newline\n\n # check for common shapes\n s = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs])\n self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal\n if not self.rect:\n LOGGER.warning('WARNING: Stream shapes differ. For optimal performance supply similarly-shaped streams.')\n\n def update(self, i, cap, stream):\n # Read stream `i` frames in daemon thread\n n, f, read = 0, self.frames[i], 1 # frame number, frame array, inference every 'read' frame\n while cap.isOpened() and n < f:\n n += 1\n # _, self.imgs[index] = cap.read()\n cap.grab()\n if n % read == 0:\n success, im = cap.retrieve()\n if success:\n self.imgs[i] = im\n else:\n LOGGER.warning('WARNING: Video stream unresponsive, please check your IP camera connection.')\n self.imgs[i] *= 0\n cap.open(stream) # re-open stream if signal was lost\n time.sleep(1 / self.fps[i]) # wait time\n\n def __iter__(self):\n self.count = -1\n return self\n\n def __next__(self):\n self.count += 1\n if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'): # q to quit\n cv2.destroyAllWindows()\n raise StopIteration\n\n # Letterbox\n img0 = self.imgs.copy()\n img = [letterbox(x, self.img_size, stride=self.stride, auto=self.rect and self.auto)[0] for x in img0]\n\n # Stack\n img = np.stack(img, 0)\n\n # Convert\n img = img[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW\n img = np.ascontiguousarray(img)\n\n return self.sources, img, img0, None, ''\n\n def __len__(self):\n return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years\n\n\ndef img2label_paths(img_paths):\n # Define label paths as a function of image paths\n sa, sb = os.sep + 'images' + os.sep, os.sep + 'annotations' + os.sep # /images/, /labels/ substrings\n return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]\n\n\nclass LoadImagesAndLabels(Dataset):\n # YOLOv5 train_loader/val_loader, loads images and labels for training and validation\n cache_version = 0.6 # dataset labels *.cache version\n\n def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,\n cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''):\n self.img_size = img_size\n self.augment = augment\n self.hyp = hyp\n self.image_weights = image_weights\n self.rect = False if image_weights else rect\n self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)\n self.mosaic_border = [-img_size // 2, -img_size // 2]\n self.stride = stride\n self.path = path\n self.albumentations = Albumentations() if augment else None\n\n try:\n f = [] # image files\n for p in path if isinstance(path, list) else [path]:\n p = Path(p) # os-agnostic\n if p.is_dir(): # dir\n f += glob.glob(str(p / '**' / '*.*'), recursive=True)\n # f = list(p.rglob('*.*')) # pathlib\n elif p.is_file(): # file\n with open(p) as t:\n t = t.read().strip().splitlines()\n parent = str(p.parent) + os.sep\n f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path\n # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)\n else:\n raise Exception(f'{prefix}{p} does not exist')\n self.img_files = sorted(x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS)\n # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS]) # pathlib\n assert self.img_files, f'{prefix}No images found'\n except Exception as e:\n raise Exception(f'{prefix}Error loading data from {path}: {e}\\nSee {HELP_URL}')\n\n # Check cache\n self.label_files = img2label_paths(self.img_files) # labels\n cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache')\n try:\n cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict\n assert cache['version'] == self.cache_version # same version\n assert cache['hash'] == get_hash(self.label_files + self.img_files) # same hash\n except:\n cache, exists = self.cache_labels(cache_path, prefix), False # cache\n\n # Display cache\n nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total\n if exists:\n d = f\"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted\"\n tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results\n if cache['msgs']:\n LOGGER.info('\\n'.join(cache['msgs'])) # display warnings\n assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {HELP_URL}'\n\n # Read cache\n [cache.pop(k) for k in ('hash', 'version', 'msgs')] # remove items\n labels, shapes, self.segments = zip(*cache.values())\n self.labels = list(labels)\n self.shapes = np.array(shapes, dtype=np.float64)\n self.img_files = list(cache.keys()) # update\n self.label_files = img2label_paths(cache.keys()) # update\n n = len(shapes) # number of images\n bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index\n nb = bi[-1] + 1 # number of batches\n self.batch = bi # batch index of image\n self.n = n\n self.indices = range(n)\n\n # Update labels\n include_class = [] # filter labels to include only these classes (optional)\n include_class_array = np.array(include_class).reshape(1, -1)\n for i, (label, segment) in enumerate(zip(self.labels, self.segments)):\n if include_class:\n j = (label[:, 0:1] == include_class_array).any(1)\n self.labels[i] = label[j]\n if segment:\n self.segments[i] = segment[j]\n if single_cls: # single-class training, merge all classes into 0\n self.labels[i][:, 0] = 0\n if segment:\n self.segments[i][:, 0] = 0\n\n # Rectangular Training\n if self.rect:\n # Sort by aspect ratio\n s = self.shapes # wh\n ar = s[:, 1] / s[:, 0] # aspect ratio\n irect = ar.argsort()\n self.img_files = [self.img_files[i] for i in irect]\n self.label_files = [self.label_files[i] for i in irect]\n self.labels = [self.labels[i] for i in irect]\n self.shapes = s[irect] # wh\n ar = ar[irect]\n\n # Set training image shapes\n shapes = [[1, 1]] * nb\n for i in range(nb):\n ari = ar[bi == i]\n mini, maxi = ari.min(), ari.max()\n if maxi < 1:\n shapes[i] = [maxi, 1]\n elif mini > 1:\n shapes[i] = [1, 1 / mini]\n\n self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride\n\n # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)\n self.imgs, self.img_npy = [None] * n, [None] * n\n if cache_images:\n if cache_images == 'disk':\n self.im_cache_dir = Path(Path(self.img_files[0]).parent.as_posix() + '_npy')\n self.img_npy = [self.im_cache_dir / Path(f).with_suffix('.npy').name for f in self.img_files]\n self.im_cache_dir.mkdir(parents=True, exist_ok=True)\n gb = 0 # Gigabytes of cached images\n self.img_hw0, self.img_hw = [None] * n, [None] * n\n results = ThreadPool(NUM_THREADS).imap(lambda x: load_image(*x), zip(repeat(self), range(n)))\n pbar = tqdm(enumerate(results), total=n)\n for i, x in pbar:\n if cache_images == 'disk':\n if not self.img_npy[i].exists():\n np.save(self.img_npy[i].as_posix(), x[0])\n gb += self.img_npy[i].stat().st_size\n else:\n self.imgs[i], self.img_hw0[i], self.img_hw[i] = x # im, hw_orig, hw_resized = load_image(self, i)\n gb += self.imgs[i].nbytes\n pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB {cache_images})'\n pbar.close()\n\n def cache_labels(self, path=Path('./labels.cache'), prefix=''):\n # Cache dataset labels, check images and read shapes\n x = {} # dict\n nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages\n desc = f\"{prefix}Scanning '{path.parent / path.stem}' images and labels...\"\n with Pool(NUM_THREADS) as pool:\n pbar = tqdm(pool.imap(verify_image_label, zip(self.img_files, self.label_files, repeat(prefix))),\n desc=desc, total=len(self.img_files))\n for im_file, l, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:\n nm += nm_f\n nf += nf_f\n ne += ne_f\n nc += nc_f\n if im_file:\n x[im_file] = [l, shape, segments]\n if msg:\n msgs.append(msg)\n pbar.desc = f\"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupted\"\n\n pbar.close()\n if msgs:\n LOGGER.info('\\n'.join(msgs))\n if nf == 0:\n LOGGER.warning(f'{prefix}WARNING: No labels found in {path}. See {HELP_URL}')\n x['hash'] = get_hash(self.label_files + self.img_files)\n x['results'] = nf, nm, ne, nc, len(self.img_files)\n x['msgs'] = msgs # warnings\n x['version'] = self.cache_version # cache version\n try:\n np.save(path, x) # save cache for next time\n path.with_suffix('.cache.npy').rename(path) # remove .npy suffix\n LOGGER.info(f'{prefix}New cache created: {path}')\n except Exception as e:\n LOGGER.warning(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # not writeable\n return x\n\n def __len__(self):\n return len(self.img_files)\n\n # def __iter__(self):\n # self.count = -1\n # print('ran dataset iter')\n # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)\n # return self\n\n def __getitem__(self, index):\n index = self.indices[index] # linear, shuffled, or image_weights\n\n hyp = self.hyp\n mosaic = self.mosaic and random.random() < hyp['mosaic']\n if mosaic:\n # Load mosaic\n img, labels = load_mosaic(self, index)\n shapes = None\n\n # MixUp augmentation\n if random.random() < hyp['mixup']:\n img, labels = mixup(img, labels, *load_mosaic(self, random.randint(0, self.n - 1)))\n\n else:\n # Load image\n img, (h0, w0), (h, w) = load_image(self, index)\n\n # Letterbox\n shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape\n img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)\n shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling\n\n labels = self.labels[index].copy()\n if labels.size: # normalized xywh to pixel xyxy format\n labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])\n\n if self.augment:\n img, labels = random_perspective(img, labels,\n degrees=hyp['degrees'],\n translate=hyp['translate'],\n scale=hyp['scale'],\n shear=hyp['shear'],\n perspective=hyp['perspective'])\n\n nl = len(labels) # number of labels\n if nl:\n labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1E-3)\n\n if self.augment:\n # Albumentations\n img, labels = self.albumentations(img, labels)\n nl = len(labels) # update after albumentations\n\n # HSV color-space\n augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])\n\n # Flip up-down\n if random.random() < hyp['flipud']:\n img = np.flipud(img)\n if nl:\n labels[:, 2] = 1 - labels[:, 2]\n\n # Flip left-right\n if random.random() < hyp['fliplr']:\n img = np.fliplr(img)\n if nl:\n labels[:, 1] = 1 - labels[:, 1]\n\n # Cutouts\n # labels = cutout(img, labels, p=0.5)\n\n labels_out = torch.zeros((nl, 6))\n if nl:\n labels_out[:, 1:] = torch.from_numpy(labels)\n\n # Convert\n img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB\n img = np.ascontiguousarray(img)\n\n return torch.from_numpy(img), labels_out, self.img_files[index], shapes\n\n @staticmethod\n def collate_fn(batch):\n img, label, path, shapes = zip(*batch) # transposed\n for i, l in enumerate(label):\n l[:, 0] = i # add target image index for build_targets()\n return torch.stack(img, 0), torch.cat(label, 0), path, shapes\n\n @staticmethod\n def collate_fn4(batch):\n img, label, path, shapes = zip(*batch) # transposed\n n = len(shapes) // 4\n img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]\n\n ho = torch.tensor([[0.0, 0, 0, 1, 0, 0]])\n wo = torch.tensor([[0.0, 0, 1, 0, 0, 0]])\n s = torch.tensor([[1, 1, 0.5, 0.5, 0.5, 0.5]]) # scale\n for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW\n i *= 4\n if random.random() < 0.5:\n im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2.0, mode='bilinear', align_corners=False)[\n 0].type(img[i].type())\n l = label[i]\n else:\n im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)\n l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s\n img4.append(im)\n label4.append(l)\n\n for i, l in enumerate(label4):\n l[:, 0] = i # add target image index for build_targets()\n\n return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4\n\n\n# Ancillary functions --------------------------------------------------------------------------------------------------\ndef load_image(self, i):\n # loads 1 image from dataset index 'i', returns im, original hw, resized hw\n im = self.imgs[i]\n if im is None: # not cached in ram\n npy = self.img_npy[i]\n if npy and npy.exists(): # load npy\n im = np.load(npy)\n else: # read image\n path = self.img_files[i]\n im = cv2.imread(path) # BGR\n assert im is not None, f'Image Not Found {path}'\n h0, w0 = im.shape[:2] # orig hw\n r = self.img_size / max(h0, w0) # ratio\n if r != 1: # if sizes are not equal\n im = cv2.resize(im, (int(w0 * r), int(h0 * r)),\n interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR)\n return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized\n else:\n return self.imgs[i], self.img_hw0[i], self.img_hw[i] # im, hw_original, hw_resized\n\n\ndef load_mosaic(self, index):\n # YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic\n labels4, segments4 = [], []\n s = self.img_size\n yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y\n indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices\n random.shuffle(indices)\n for i, index in enumerate(indices):\n # Load image\n img, _, (h, w) = load_image(self, index)\n\n # place img in img4\n if i == 0: # top left\n img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles\n x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)\n x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)\n elif i == 1: # top right\n x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc\n x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h\n elif i == 2: # bottom left\n x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)\n x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)\n elif i == 3: # bottom right\n x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)\n x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)\n\n img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]\n padw = x1a - x1b\n padh = y1a - y1b\n\n # Labels\n labels, segments = self.labels[index].copy(), self.segments[index].copy()\n if labels.size:\n labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format\n segments = [xyn2xy(x, w, h, padw, padh) for x in segments]\n labels4.append(labels)\n segments4.extend(segments)\n\n # Concat/clip labels\n labels4 = np.concatenate(labels4, 0)\n for x in (labels4[:, 1:], *segments4):\n np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()\n # img4, labels4 = replicate(img4, labels4) # replicate\n\n # Augment\n img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp['copy_paste'])\n img4, labels4 = random_perspective(img4, labels4, segments4,\n degrees=self.hyp['degrees'],\n translate=self.hyp['translate'],\n scale=self.hyp['scale'],\n shear=self.hyp['shear'],\n perspective=self.hyp['perspective'],\n border=self.mosaic_border) # border to remove\n\n return img4, labels4\n\n\ndef load_mosaic9(self, index):\n # YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic\n labels9, segments9 = [], []\n s = self.img_size\n indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices\n random.shuffle(indices)\n for i, index in enumerate(indices):\n # Load image\n img, _, (h, w) = load_image(self, index)\n\n # place img in img9\n if i == 0: # center\n img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles\n h0, w0 = h, w\n c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates\n elif i == 1: # top\n c = s, s - h, s + w, s\n elif i == 2: # top right\n c = s + wp, s - h, s + wp + w, s\n elif i == 3: # right\n c = s + w0, s, s + w0 + w, s + h\n elif i == 4: # bottom right\n c = s + w0, s + hp, s + w0 + w, s + hp + h\n elif i == 5: # bottom\n c = s + w0 - w, s + h0, s + w0, s + h0 + h\n elif i == 6: # bottom left\n c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h\n elif i == 7: # left\n c = s - w, s + h0 - h, s, s + h0\n elif i == 8: # top left\n c = s - w, s + h0 - hp - h, s, s + h0 - hp\n\n padx, pady = c[:2]\n x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coords\n\n # Labels\n labels, segments = self.labels[index].copy(), self.segments[index].copy()\n if labels.size:\n labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format\n segments = [xyn2xy(x, w, h, padx, pady) for x in segments]\n labels9.append(labels)\n segments9.extend(segments)\n\n # Image\n img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax]\n hp, wp = h, w # height, width previous\n\n # Offset\n yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border) # mosaic center x, y\n img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]\n\n # Concat/clip labels\n labels9 = np.concatenate(labels9, 0)\n labels9[:, [1, 3]] -= xc\n labels9[:, [2, 4]] -= yc\n c = np.array([xc, yc]) # centers\n segments9 = [x - c for x in segments9]\n\n for x in (labels9[:, 1:], *segments9):\n np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()\n # img9, labels9 = replicate(img9, labels9) # replicate\n\n # Augment\n img9, labels9 = random_perspective(img9, labels9, segments9,\n degrees=self.hyp['degrees'],\n translate=self.hyp['translate'],\n scale=self.hyp['scale'],\n shear=self.hyp['shear'],\n perspective=self.hyp['perspective'],\n border=self.mosaic_border) # border to remove\n\n return img9, labels9\n\n\ndef create_folder(path='./new'):\n # Create folder\n if os.path.exists(path):\n shutil.rmtree(path) # delete output folder\n os.makedirs(path) # make new output folder\n\n\ndef flatten_recursive(path='../datasets/coco128'):\n # Flatten a recursive directory by bringing all files to top level\n new_path = Path(path + '_flat')\n create_folder(new_path)\n for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):\n shutil.copyfile(file, new_path / Path(file).name)\n\n\ndef extract_boxes(path='../datasets/coco128'): # from utils.datasets import *; extract_boxes()\n # Convert detection dataset into classification dataset, with one directory per class\n path = Path(path) # images dir\n shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing\n files = list(path.rglob('*.*'))\n n = len(files) # number of files\n for im_file in tqdm(files, total=n):\n if im_file.suffix[1:] in IMG_FORMATS:\n # image\n im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB\n h, w = im.shape[:2]\n\n # labels\n lb_file = Path(img2label_paths([str(im_file)])[0])\n if Path(lb_file).exists():\n with open(lb_file) as f:\n lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels\n\n for j, x in enumerate(lb):\n c = int(x[0]) # class\n f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename\n if not f.parent.is_dir():\n f.parent.mkdir(parents=True)\n\n b = x[1:] * [w, h, w, h] # box\n # b[2:] = b[2:].max() # rectangle to square\n b[2:] = b[2:] * 1.2 + 3 # pad\n b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)\n\n b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image\n b[[1, 3]] = np.clip(b[[1, 3]], 0, h)\n assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'\n\n\ndef autosplit(path='../datasets/coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False):\n \"\"\" Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files\n Usage: from utils.datasets import *; autosplit()\n Arguments\n path: Path to images directory\n weights: Train, val, test weights (list, tuple)\n annotated_only: Only use images with an annotated txt file\n \"\"\"\n path = Path(path) # images dir\n files = sorted(x for x in path.rglob('*.*') if x.suffix[1:].lower() in IMG_FORMATS) # image files only\n n = len(files) # number of files\n random.seed(0) # for reproducibility\n indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split\n\n txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files\n [(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing\n\n print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)\n for i, img in tqdm(zip(indices, files), total=n):\n if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label\n with open(path.parent / txt[i], 'a') as f:\n f.write('./' + img.relative_to(path.parent).as_posix() + '\\n') # add image to txt file\n\n\ndef verify_image_label(args):\n # Verify one image-label pair\n im_file, lb_file, prefix = args\n nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', [] # number (missing, found, empty, corrupt), message, segments\n try:\n # verify images\n im = Image.open(im_file)\n im.verify() # PIL verify\n shape = exif_size(im) # image size\n assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'\n assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}'\n if im.format.lower() in ('jpg', 'jpeg'):\n with open(im_file, 'rb') as f:\n f.seek(-2, 2)\n if f.read() != b'\\xff\\xd9': # corrupt JPEG\n ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100)\n msg = f'{prefix}WARNING: {im_file}: corrupt JPEG restored and saved'\n\n # verify labels\n if os.path.isfile(lb_file):\n nf = 1 # label found\n with open(lb_file) as f:\n l = [x.split() for x in f.read().strip().splitlines() if len(x)]\n if any([len(x) > 8 for x in l]): # is segment\n classes = np.array([x[0] for x in l], dtype=np.float32)\n segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)\n l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)\n l = np.array(l, dtype=np.float32)\n nl = len(l)\n if nl:\n assert l.shape[1] == 5, f'labels require 5 columns, {l.shape[1]} columns detected'\n assert (l >= 0).all(), f'negative label values {l[l < 0]}'\n assert (l[:, 1:] <= 1).all(), f'non-normalized or out of bounds coordinates {l[:, 1:][l[:, 1:] > 1]}'\n _, i = np.unique(l, axis=0, return_index=True)\n if len(i) < nl: # duplicate row check\n l = l[i] # remove duplicates\n if segments:\n segments = segments[i]\n msg = f'{prefix}WARNING: {im_file}: {nl - len(i)} duplicate labels removed'\n else:\n ne = 1 # label empty\n l = np.zeros((0, 5), dtype=np.float32)\n else:\n nm = 1 # label missing\n l = np.zeros((0, 5), dtype=np.float32)\n return im_file, l, shape, segments, nm, nf, ne, nc, msg\n except Exception as e:\n nc = 1\n msg = f'{prefix}WARNING: {im_file}: ignoring corrupt image/label: {e}'\n return [None, None, None, None, nm, nf, ne, nc, msg]\n\n\ndef dataset_stats(path='coco128.yaml', autodownload=False, verbose=False, profile=False, hub=False):\n \"\"\" Return dataset statistics dictionary with images and instances counts per split per class\n To run in parent directory: export PYTHONPATH=\"$PWD/yolov5\"\n Usage1: from utils.datasets import *; dataset_stats('coco128.yaml', autodownload=True)\n Usage2: from utils.datasets import *; dataset_stats('../datasets/coco128_with_yaml.zip')\n Arguments\n path: Path to data.yaml or data.zip (with data.yaml inside data.zip)\n autodownload: Attempt to download dataset if not found locally\n verbose: Print stats dictionary\n \"\"\"\n\n def round_labels(labels):\n # Update labels to integer class and 6 decimal place floats\n return [[int(c), *(round(x, 4) for x in points)] for c, *points in labels]\n\n def unzip(path):\n # Unzip data.zip TODO: CONSTRAINT: path/to/abc.zip MUST unzip to 'path/to/abc/'\n if str(path).endswith('.zip'): # path is data.zip\n assert Path(path).is_file(), f'Error unzipping {path}, file not found'\n ZipFile(path).extractall(path=path.parent) # unzip\n dir = path.with_suffix('') # dataset directory == zip name\n return True, str(dir), next(dir.rglob('*.yaml')) # zipped, data_dir, yaml_path\n else: # path is data.yaml\n return False, None, path\n\n def hub_ops(f, max_dim=1920):\n # HUB ops for 1 image 'f': resize and save at reduced quality in /dataset-hub for web/app viewing\n f_new = im_dir / Path(f).name # dataset-hub image filename\n try: # use PIL\n im = Image.open(f)\n r = max_dim / max(im.height, im.width) # ratio\n if r < 1.0: # image too large\n im = im.resize((int(im.width * r), int(im.height * r)))\n im.save(f_new, 'JPEG', quality=75, optimize=True) # save\n except Exception as e: # use OpenCV\n print(f'WARNING: HUB ops PIL failure {f}: {e}')\n im = cv2.imread(f)\n im_height, im_width = im.shape[:2]\n r = max_dim / max(im_height, im_width) # ratio\n if r < 1.0: # image too large\n im = cv2.resize(im, (int(im_width * r), int(im_height * r)), interpolation=cv2.INTER_LINEAR)\n cv2.imwrite(str(f_new), im)\n\n zipped, data_dir, yaml_path = unzip(Path(path))\n with open(check_yaml(yaml_path), errors='ignore') as f:\n data = yaml.safe_load(f) # data dict\n if zipped:\n data['path'] = data_dir # TODO: should this be dir.resolve()?\n check_dataset(data, autodownload) # download dataset if missing\n hub_dir = Path(data['path'] + ('-hub' if hub else ''))\n stats = {'nc': data['nc'], 'names': data['names']} # statistics dictionary\n for split in 'train', 'val', 'test':\n if data.get(split) is None:\n stats[split] = None # i.e. no test set\n continue\n x = []\n dataset = LoadImagesAndLabels(data[split]) # load dataset\n for label in tqdm(dataset.labels, total=dataset.n, desc='Statistics'):\n x.append(np.bincount(label[:, 0].astype(int), minlength=data['nc']))\n x = np.array(x) # shape(128x80)\n stats[split] = {'instance_stats': {'total': int(x.sum()), 'per_class': x.sum(0).tolist()},\n 'image_stats': {'total': dataset.n, 'unlabelled': int(np.all(x == 0, 1).sum()),\n 'per_class': (x > 0).sum(0).tolist()},\n 'labels': [{str(Path(k).name): round_labels(v.tolist())} for k, v in\n zip(dataset.img_files, dataset.labels)]}\n\n if hub:\n im_dir = hub_dir / 'images'\n im_dir.mkdir(parents=True, exist_ok=True)\n for _ in tqdm(ThreadPool(NUM_THREADS).imap(hub_ops, dataset.img_files), total=dataset.n, desc='HUB Ops'):\n pass\n\n # Profile\n stats_path = hub_dir / 'stats.json'\n if profile:\n for _ in range(1):\n file = stats_path.with_suffix('.npy')\n t1 = time.time()\n np.save(file, stats)\n t2 = time.time()\n x = np.load(file, allow_pickle=True)\n print(f'stats.npy times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write')\n\n file = stats_path.with_suffix('.json')\n t1 = time.time()\n with open(file, 'w') as f:\n json.dump(stats, f) # save stats *.json\n t2 = time.time()\n with open(file) as f:\n x = json.load(f) # load hyps dict\n print(f'stats.json times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write')\n\n # Save, print and return\n if hub:\n print(f'Saving {stats_path.resolve()}...')\n with open(stats_path, 'w') as f:\n json.dump(stats, f) # save stats.json\n if verbose:\n print(json.dumps(stats, indent=2, sort_keys=False))\n return stats\n" ]
[ [ "torch.cat", "torch.stack", "numpy.load", "numpy.concatenate", "numpy.full", "numpy.save", "numpy.flipud", "torch.tensor", "numpy.arange", "torch.zeros", "numpy.array", "numpy.zeros", "numpy.stack", "numpy.clip", "numpy.fliplr", "numpy.ascontiguousarray", "torch.from_numpy", "torch.utils.data.distributed.DistributedSampler", "numpy.all", "numpy.unique" ] ]
EsdeathYZH/oneflow
[ "963cc01bd8dfcae2043a565d9ff1305aa70bb325" ]
[ "python/oneflow/test/modules/test_slice.py" ]
[ "\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport unittest\nfrom collections import OrderedDict\n\nimport numpy as np\nfrom test_util import GenArgList\n\nimport oneflow as flow\nimport oneflow.unittest\n\n\ndef _test_slice(test_case, device):\n np_arr = np.random.randn(3, 6, 9).astype(np.float32)\n x = flow.Tensor(np_arr, device=flow.device(device))\n tup_list = [[None, None, None], [0, 5, 2], [0, 6, 3]]\n y = flow.slice(x, slice_tup_list=tup_list)\n tmp = np_arr[0:3, 0:5, 0:6]\n np_out = tmp[::1, ::2, ::3]\n test_case.assertTrue(np.array_equal(y.numpy(), np_out))\n\n\ndef _test_slice_1_dim(test_case, device):\n np_arr = np.random.randn(100).astype(np.float32)\n x = flow.Tensor(np_arr, device=flow.device(device))\n test_case.assertTrue(np.allclose(x[1].numpy(), np_arr[1], 1e-05, 1e-05))\n test_case.assertTrue(np.allclose(x[99].numpy(), np_arr[99], 1e-05, 1e-05))\n test_case.assertTrue(np.allclose(x[0:2].numpy(), np_arr[0:2], 1e-05, 1e-05))\n\n\ndef _test_slice_3_dim(test_case, device):\n np_arr = np.random.randn(2, 3, 4).astype(np.float32)\n x = flow.Tensor(np_arr, device=flow.device(device))\n test_case.assertTrue(np.allclose(x[:, 0].numpy(), np_arr[:, 0], 1e-05, 1e-05))\n\n\ndef _test_slice_4_dim(test_case, device):\n np_arr = np.random.randn(5, 3, 6, 9).astype(np.float32)\n x = flow.Tensor(np_arr, device=flow.device(device))\n tup_list = [[0, 5, 2], [None, None, None], [0, 5, 2], [0, 6, 3]]\n y = flow.slice(x, slice_tup_list=tup_list)\n tmp = np_arr[0:5, 0:3, 0:5, 0:6]\n np_out = tmp[::2, ::1, ::2, ::3]\n test_case.assertTrue(np.array_equal(y.numpy(), np_out))\n\n\ndef _test_slice_with_int_index(test_case, device):\n np_arr = np.random.randn(2, 3, 4).astype(np.float32)\n x = flow.Tensor(np_arr, device=flow.device(device))\n of_out = x[0, 1:2]\n np_out = np_arr[0, 1:2]\n test_case.assertTrue(np.array_equal(of_out.numpy(), np_out))\n np_arr = np.random.randn(2, 3, 4).astype(np.float32)\n x = flow.Tensor(np_arr, device=flow.device(device))\n of_out = x[0, :]\n np_out = np_arr[0, :]\n test_case.assertTrue(np.array_equal(of_out.numpy(), np_out))\n np_arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]).astype(np.float32)\n x = flow.Tensor(np_arr, device=flow.device(device))\n of_out = x[0, :, :]\n np_out = np_arr[0, :, :]\n test_case.assertTrue(np.array_equal(of_out.numpy(), np_out))\n np_arr = np.random.randn(2, 3, 4, 5).astype(np.float32)\n x = flow.Tensor(np_arr, device=flow.device(device))\n of_out = x[0, :, :, :]\n np_out = np_arr[0, :, :, :]\n test_case.assertTrue(np.array_equal(of_out.numpy(), np_out))\n\n\ndef _test_slice_negative_index(test_case, device):\n np_arr = np.random.randn(4, 5, 6)\n x = flow.Tensor(np_arr, device=flow.device(device))\n test_case.assertTrue(np.allclose(x[-1].numpy(), np_arr[-1], 0.0001, 0.0001))\n test_case.assertTrue(np.allclose(x[-2].numpy(), np_arr[-2], 0.0001, 0.0001))\n test_case.assertTrue(np.allclose(x[-3].numpy(), np_arr[-3], 0.0001, 0.0001))\n test_case.assertTrue(np.allclose(x[-4].numpy(), np_arr[-4], 0.0001, 0.0001))\n\n\ndef _test_slice_ellipsis_type(test_case, device):\n np_arr = np.random.randn(2, 3, 4, 5, 6, 7).astype(np.float32)\n x = flow.Tensor(np_arr, device=flow.device(device))\n of_out = x[..., ::2, ::2, 3:4]\n np_out = np_arr[..., ::2, ::2, 3:4]\n test_case.assertTrue(np.array_equal(of_out.numpy(), np_out))\n of_out = x[..., 1:2, ::2, 1, ::3]\n np_out = np_arr[..., 1:2, ::2, 1, ::3]\n test_case.assertTrue(np.array_equal(of_out.numpy(), np_out))\n of_out = x[0, 2, ..., 1, 1:2]\n np_out = np_arr[0, 2, ..., 1, 1:2]\n test_case.assertTrue(np.array_equal(of_out.numpy(), np_out))\n of_out = x[::2, ..., 1:2]\n np_out = np_arr[::2, ..., 1:2]\n test_case.assertTrue(np.array_equal(of_out.numpy(), np_out))\n\n\ndef _test_slice_backward(test_case, device):\n np_arr = np.random.randn(3, 6, 9).astype(np.float32)\n x = flow.Tensor(np_arr, device=flow.device(device), requires_grad=True)\n tup_list = [[None, None, None], [0, 5, 2], [0, 6, 3]]\n y = flow.slice(x, slice_tup_list=tup_list)\n z = y.sum()\n z.backward()\n np_grad = np.zeros((3, 6, 9))\n np_grad[0:3, 0:5, 0:6][::1, ::2, ::3] = 1\n test_case.assertTrue(np.array_equal(x.grad.numpy(), np_grad))\n\n\[email protected]_unless_1n1d()\nclass TestSlice(flow.unittest.TestCase):\n def test_slice(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"test_fun\"] = [\n _test_slice,\n _test_slice_1_dim,\n _test_slice_3_dim,\n _test_slice_4_dim,\n _test_slice_with_int_index,\n _test_slice_negative_index,\n _test_slice_ellipsis_type,\n _test_slice_backward,\n ]\n arg_dict[\"device\"] = [\"cpu\", \"cuda\"]\n for arg in GenArgList(arg_dict):\n arg[0](test_case, *arg[1:])\n\n\[email protected]_unless_1n1d()\nclass TestSliceUpdate(flow.unittest.TestCase):\n def test_slice_update(test_case):\n x = np.array([1, 1, 1, 1, 1]).astype(np.float32)\n input = flow.Tensor(x, requires_grad=True)\n update = flow.Tensor(np.array([2, 3, 4]).astype(np.float32), requires_grad=True)\n output = np.array([1.0, 2.0, 3.0, 4.0, 1.0])\n y = flow.slice_update(input, update, slice_tup_list=[[1, 4, 1]])\n z = y.sum()\n z.backward()\n test_case.assertTrue(np.array_equal(y.numpy(), output))\n np_grad = np.zeros(x.shape)\n np_grad[0] = 1\n np_grad[4] = 1\n test_case.assertTrue(np.array_equal(input.grad.numpy(), np_grad))\n test_case.assertTrue(np.array_equal(update.grad.numpy(), np.ones(update.shape)))\n\n\[email protected]_unless_1n1d()\nclass TestLogicalSliceAssign(flow.unittest.TestCase):\n def test_logical_slice_assign(test_case):\n x = np.array([1, 1, 1, 1, 1]).astype(np.float32)\n input = flow.Tensor(x)\n update = flow.Tensor(np.array([2, 3, 4]).astype(np.float32))\n output = np.array([1.0, 2.0, 3.0, 4.0, 1.0])\n flow.tmp.logical_slice_assign(input, update, slice_tup_list=[[1, 4, 1]])\n test_case.assertTrue(np.array_equal(input.numpy(), output))\n\n def test_logical_slice_assign_negative_index(test_case):\n np_arr = np.zeros(shape=(2, 3, 4))\n input = flow.Tensor(np_arr)\n np_arr[-1] = 1\n input[-1] = 1\n test_case.assertTrue(np.array_equal(input.numpy(), np_arr))\n\n def test_logical_slice_assign_ellipsis_type(test_case):\n np_arr = np.zeros(shape=(2, 3, 4, 5, 6))\n input = flow.Tensor(np_arr)\n np_arr[0, ::1, ..., 2:3] = 1\n input[0, ::1, ..., 2:3] = 1\n test_case.assertTrue(np.array_equal(input.numpy(), np_arr))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.array", "numpy.ones", "numpy.random.randn", "numpy.zeros" ] ]
lachieggg/PyDataScienceNotes
[ "551edcbdc326d2feb2a1f93d3f3ea335d87ca983" ]
[ "pca.py" ]
[ "# Code for PCA\n#\n\nfrom sklearn.datasets import load_iris\nfrom sklearn.decomposition import PCA\nimport pylab as pl\nfrom itertools import cycle\n\n# Load in the famed Iris dataset \niris = load_iris()\n\nnumSamples, numFeatures = iris.data.shape\n# Print the data so we have an intuition about\n# what we are looking at\nprint(numSamples)\nprint(numFeatures)\nprint(list(iris.target_names))\nprint(iris)\n\nX = iris.data\n# Transform or \"flatten\" it to two dimensions\n#\npca = PCA(n_components=2, whiten=True).fit(X)\nX_pca = pca.transform(X)\n\nprint(pca.components_)\n\n# Determine how much variance we have preserved\nprint(pca.explained_variance_ratio_)\nprint(sum(pca.explained_variance_ratio_))" ]
[ [ "sklearn.decomposition.PCA", "sklearn.datasets.load_iris" ] ]
XYPB/myMaskRCNN-mxnet
[ "88a626b783cee9d8c1b4a6d54a53b95a9ed4a2eb" ]
[ "symnet/proposal_target.py" ]
[ "\"\"\"\nProposal Target Operator selects foreground and background roi and assigns label, bbox_transform to them.\n\"\"\"\n\nimport mxnet as mx\nimport numpy as np\n\nfrom symdata.bbox import bbox_overlaps, bbox_transform\n\n\ndef sample_rois(rois, gt_boxes, num_classes, rois_per_image, fg_rois_per_image, fg_overlap, box_stds):\n \"\"\"\n generate random sample of ROIs comprising foreground and background examples\n :param rois: [n, 5] (batch_index, x1, y1, x2, y2)\n :param gt_boxes: [n, 5] (x1, y1, x2, y2, cls)\n :param num_classes: number of classes\n :param rois_per_image: total roi number\n :param fg_rois_per_image: foreground roi number\n :param fg_overlap: overlap threshold for fg rois\n :param box_stds: std var of bbox reg\n :return: (labels, rois, bbox_targets, bbox_weights)\n \"\"\"\n overlaps = bbox_overlaps(rois[:, 1:], gt_boxes[:,:4])\n # print('rois are:\\n', rois[:, 1:])\n # print('gt boxes are:\\n', gt_boxes[:,:4])\n gt_assignment = overlaps.argmax(axis=1)\n labels = gt_boxes[gt_assignment, 4]\n max_overlaps = overlaps.max(axis=1)\n\n # select foreground RoI with FG_THRESH overlap\n fg_indexes = np.where(max_overlaps >= fg_overlap)[0]\n # guard against the case when an image has fewer than fg_rois_per_image foreground RoIs\n fg_rois_this_image = min(fg_rois_per_image, len(fg_indexes))\n # sample foreground regions without replacement\n if len(fg_indexes) > fg_rois_this_image:\n fg_indexes = np.random.choice(fg_indexes, size=fg_rois_this_image, replace=False)\n\n # select background RoIs as those within [0, FG_THRESH)\n # print('max_overlaps are:\\n', max_overlaps)\n bg_indexes = np.where(max_overlaps < fg_overlap)[0]\n # print('bg_indexes are :', bg_indexes)\n # compute number of background RoIs to take from this image (guarding against there being fewer than desired)\n bg_rois_this_image = rois_per_image - fg_rois_this_image\n bg_rois_this_image = min(bg_rois_this_image, len(bg_indexes))\n # sample bg rois without replacement\n if len(bg_indexes) > bg_rois_this_image:\n bg_indexes = np.random.choice(bg_indexes, size=bg_rois_this_image, replace=False)\n\n # indexes selected\n keep_indexes = np.append(fg_indexes, bg_indexes)\n # pad more bg rois to ensure a fixed minibatch size\n while len(keep_indexes) < rois_per_image:\n gap = min(len(bg_indexes), rois_per_image - len(keep_indexes))\n gap_indexes = np.random.choice(range(len(bg_indexes)), size=gap, replace=False)\n keep_indexes = np.append(keep_indexes, bg_indexes[gap_indexes])\n\n # sample rois and labels\n rois = rois[keep_indexes]\n labels = labels[keep_indexes]\n # set labels of bg rois to be 0\n labels[fg_rois_this_image:] = 0\n\n # load or compute bbox_target\n targets = bbox_transform(rois[:, 1:], gt_boxes[gt_assignment[keep_indexes], :4], box_stds=box_stds)\n bbox_targets = np.zeros((rois_per_image, 4 * num_classes), dtype=np.float32)\n bbox_weights = np.zeros((rois_per_image, 4 * num_classes), dtype=np.float32)\n for i in range(fg_rois_this_image):\n cls_ind = int(labels[i])\n bbox_targets[i, cls_ind * 4:(cls_ind + 1) * 4] = targets[i]\n bbox_weights[i, cls_ind * 4:(cls_ind + 1) * 4] = 1\n\n return rois, labels, bbox_targets, bbox_weights\n\n\nclass ProposalTargetOperator(mx.operator.CustomOp):\n def __init__(self, num_classes, batch_images, batch_rois, fg_fraction, fg_overlap, box_stds):\n super(ProposalTargetOperator, self).__init__()\n self._num_classes = num_classes\n self._batch_images = batch_images\n self._batch_rois = batch_rois\n self._rois_per_image = int(batch_rois / batch_images)\n self._fg_rois_per_image = int(round(fg_fraction * self._rois_per_image))\n self._fg_overlap = fg_overlap\n self._box_stds = box_stds\n\n def forward(self, is_train, req, in_data, out_data, aux):\n assert self._batch_images == in_data[1].shape[0], 'check batch size of gt_boxes'\n\n all_rois = in_data[0].asnumpy()\n all_gt_boxes = in_data[1].asnumpy()\n\n rois = np.empty((0, 5), dtype=np.float32)\n labels = np.empty((0, ), dtype=np.float32)\n bbox_targets = np.empty((0, 4 * self._num_classes), dtype=np.float32)\n bbox_weights = np.empty((0, 4 * self._num_classes), dtype=np.float32)\n for batch_idx in range(self._batch_images):\n b_rois = all_rois[np.where(all_rois[:, 0] == batch_idx)[0]]\n b_gt_boxes = all_gt_boxes[batch_idx]\n b_gt_boxes = b_gt_boxes[np.where(b_gt_boxes[:, -1] > 0)[0]]\n\n # Include ground-truth boxes in the set of candidate rois\n batch_pad = batch_idx * np.ones((b_gt_boxes.shape[0], 1), dtype=b_gt_boxes.dtype)\n b_rois = np.vstack((b_rois, np.hstack((batch_pad, b_gt_boxes[:, :-1]))))\n\n b_rois, b_labels, b_bbox_targets, b_bbox_weights = \\\n sample_rois(b_rois, b_gt_boxes, num_classes=self._num_classes, rois_per_image=self._rois_per_image,\n fg_rois_per_image=self._fg_rois_per_image, fg_overlap=self._fg_overlap, box_stds=self._box_stds)\n\n rois = np.vstack((rois, b_rois))\n labels = np.hstack((labels, b_labels))\n bbox_targets = np.vstack((bbox_targets, b_bbox_targets))\n bbox_weights = np.vstack((bbox_weights, b_bbox_weights))\n\n self.assign(out_data[0], req[0], rois)\n self.assign(out_data[1], req[1], labels)\n self.assign(out_data[2], req[2], bbox_targets)\n self.assign(out_data[3], req[3], bbox_weights)\n\n def backward(self, req, out_grad, in_data, out_data, in_grad, aux):\n self.assign(in_grad[0], req[0], 0)\n self.assign(in_grad[1], req[1], 0)\n\n\[email protected]('proposal_target')\nclass ProposalTargetProp(mx.operator.CustomOpProp):\n def __init__(self, num_classes='21', batch_images='1', batch_rois='128', fg_fraction='0.25',\n fg_overlap='0.5', box_stds='(0.1, 0.1, 0.2, 0.2)'):\n super(ProposalTargetProp, self).__init__(need_top_grad=False)\n self._num_classes = int(num_classes)\n self._batch_images = int(batch_images)\n self._batch_rois = int(batch_rois)\n self._fg_fraction = float(fg_fraction)\n self._fg_overlap = float(fg_overlap)\n self._box_stds = tuple(np.fromstring(box_stds[1:-1], dtype=float, sep=','))\n\n def list_arguments(self):\n return ['rois', 'gt_boxes']\n\n def list_outputs(self):\n return ['rois_output', 'label', 'bbox_target', 'bbox_weight']\n\n def infer_shape(self, in_shape):\n assert self._batch_rois % self._batch_images == 0, \\\n 'BATCHIMAGES {} must devide BATCH_ROIS {}'.format(self._batch_images, self._batch_rois)\n\n rpn_rois_shape = in_shape[0]\n gt_boxes_shape = in_shape[1]\n\n output_rois_shape = (self._batch_rois, 5)\n label_shape = (self._batch_rois, )\n bbox_target_shape = (self._batch_rois, self._num_classes * 4)\n bbox_weight_shape = (self._batch_rois, self._num_classes * 4)\n\n return [rpn_rois_shape, gt_boxes_shape], \\\n [output_rois_shape, label_shape, bbox_target_shape, bbox_weight_shape]\n\n def create_operator(self, ctx, shapes, dtypes):\n return ProposalTargetOperator(self._num_classes, self._batch_images, self._batch_rois, self._fg_fraction,\n self._fg_overlap, self._box_stds)\n\n def declare_backward_dependency(self, out_grad, in_data, out_data):\n return []\n" ]
[ [ "numpy.empty", "numpy.random.choice", "numpy.zeros", "numpy.ones", "numpy.where", "numpy.append", "numpy.hstack", "numpy.fromstring", "numpy.vstack" ] ]
eordanis/CIS-700
[ "4f5977ca2bc55c8995d034774b4340351f25c24d" ]
[ "models/gsgan/GsganDiscriminator.py" ]
[ "import numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.ops import control_flow_ops\n\n\nclass Discriminator():\n def __init__(self, embedding_size, vocab_size, non_static, hidden_unit, sequence_length, batch_size,\n num_classes, filter_sizes, num_filters, l2_reg_lambda=0.0, start_token=0):\n embedding_size = vocab_size\n self.num_vocabulary = vocab_size\n self.emb_dim = embedding_size\n self.hidden_dim = hidden_unit\n self.num_classes = num_classes\n self.sequence_length = sequence_length\n self.batch_size = tf.compat.v1.constant(value=[batch_size])\n self.batch_size_scale = batch_size\n self.hidden_unit = hidden_unit\n self.d_params = []\n l2_loss = tf.compat.v1.constant(0.0)\n self.start_token = tf.compat.v1.constant([start_token] * batch_size, dtype=tf.compat.v1.int32)\n\n with tf.compat.v1.variable_scope('discriminator'):\n self.g_recurrent_unit = self.create_recurrent_unit(self.d_params) # maps h_tm1 to h_t for generator\n self.g_output_unit = self.create_output_unit(self.d_params) # maps h_t to o_t (output token logits)\n\n self.input_x = tf.compat.v1.placeholder(tf.compat.v1.float32, [batch_size, sequence_length, vocab_size], name='input_x')\n self.input_y = tf.compat.v1.placeholder(tf.compat.v1.float32, [batch_size, num_classes], name='input_y')\n self.one_hot = tf.compat.v1.constant(np.eye(vocab_size), dtype=tf.compat.v1.float32)\n self.h_0 = tf.compat.v1.constant(value=0, dtype=tf.compat.v1.float32, shape=[batch_size, hidden_unit])\n self.c_0 = tf.compat.v1.constant(value=0, dtype=tf.compat.v1.float32, shape=[batch_size, hidden_unit])\n self.h0 = tf.compat.v1.stack([self.h_0, self.c_0])\n\n score = self.predict(input_x=self.input_x)\n self.score = score\n\n with tf.compat.v1.name_scope('Dloss'):\n pred_loss = tf.compat.v1.nn.softmax_cross_entropy_with_logits(logits=score, labels=self.input_y)\n # todo reg loss\n reg_loss = 0\n self.loss = tf.compat.v1.reduce_mean(pred_loss)\n\n self.params = [param for param in tf.compat.v1.trainable_variables() if 'discriminator' in param.name]\n d_optimizer = tf.compat.v1.train.AdamOptimizer(1e-4)\n self.grad_clip = 5.0\n self.pretrain_grad, _ = tf.compat.v1.clip_by_global_norm(tf.compat.v1.gradients(self.loss, self.params), self.grad_clip)\n self.train_op = d_optimizer.apply_gradients(zip(self.pretrain_grad, self.params))\n return\n\n def predict(self, input_x, h_0=None):\n if h_0 is None:\n h_0 = self.h_0\n def _g_recurrence(i, x_t, h_tm1, o_t):\n h_t = self.g_recurrent_unit(x_t, h_tm1) # hidden_memory_tuple\n o_t = self.g_output_unit(h_t) # batch x vocab , logits not prob\n x_tp1 = tf.compat.v1.squeeze(tf.compat.v1.slice(input_x, begin=[0, i, 0], size=[self.batch_size_scale, 1, self.num_vocabulary]))\n return i + 1, x_tp1, h_t, o_t\n\n o_0 = tf.compat.v1.constant(np.zeros(shape=[self.batch_size_scale, self.num_classes]))\n o_0 = tf.compat.v1.cast(o_0, dtype=tf.compat.v1.float32)\n _, _, h_t, output = control_flow_ops.while_loop(\n cond=lambda i, _1, _2, _3: i < self.sequence_length,\n body=_g_recurrence,\n loop_vars=(tf.compat.v1.constant(0, dtype=tf.compat.v1.int32),\n tf.compat.v1.nn.embedding_lookup(self.one_hot, self.start_token), self.h0, o_0))\n\n return output\n\n def init_matrix(self, shape):\n return tf.compat.v1.random_normal(shape, stddev=0.1)\n\n def create_recurrent_unit(self, params):\n # Weights and Bias for input and hidden tensor\n self.Wi = tf.compat.v1.Variable(self.init_matrix([self.emb_dim, self.hidden_dim]))\n self.Ui = tf.compat.v1.Variable(self.init_matrix([self.hidden_dim, self.hidden_dim]))\n self.bi = tf.compat.v1.Variable(self.init_matrix([self.hidden_dim]))\n\n self.Wf = tf.compat.v1.Variable(self.init_matrix([self.emb_dim, self.hidden_dim]))\n self.Uf = tf.compat.v1.Variable(self.init_matrix([self.hidden_dim, self.hidden_dim]))\n self.bf = tf.compat.v1.Variable(self.init_matrix([self.hidden_dim]))\n\n self.Wog = tf.compat.v1.Variable(self.init_matrix([self.emb_dim, self.hidden_dim]))\n self.Uog = tf.compat.v1.Variable(self.init_matrix([self.hidden_dim, self.hidden_dim]))\n self.bog = tf.compat.v1.Variable(self.init_matrix([self.hidden_dim]))\n\n self.Wc = tf.compat.v1.Variable(self.init_matrix([self.emb_dim, self.hidden_dim]))\n self.Uc = tf.compat.v1.Variable(self.init_matrix([self.hidden_dim, self.hidden_dim]))\n self.bc = tf.compat.v1.Variable(self.init_matrix([self.hidden_dim]))\n params.extend([\n self.Wi, self.Ui, self.bi,\n self.Wf, self.Uf, self.bf,\n self.Wog, self.Uog, self.bog,\n self.Wc, self.Uc, self.bc])\n\n def unit(x, hidden_memory_tm1):\n previous_hidden_state, c_prev = tf.compat.v1.unstack(hidden_memory_tm1)\n\n # Input Gate\n i = tf.compat.v1.sigmoid(\n tf.compat.v1.matmul(x, self.Wi) +\n tf.compat.v1.matmul(previous_hidden_state, self.Ui) + self.bi\n )\n\n # Forget Gate\n f = tf.compat.v1.sigmoid(\n tf.compat.v1.matmul(x, self.Wf) +\n tf.compat.v1.matmul(previous_hidden_state, self.Uf) + self.bf\n )\n\n # Output Gate\n o = tf.compat.v1.sigmoid(\n tf.compat.v1.matmul(x, self.Wog) +\n tf.compat.v1.matmul(previous_hidden_state, self.Uog) + self.bog\n )\n\n # New Memory Cell\n c_ = tf.compat.v1.nn.tanh(\n tf.compat.v1.matmul(x, self.Wc) +\n tf.compat.v1.matmul(previous_hidden_state, self.Uc) + self.bc\n )\n\n # Final Memory cell\n c = f * c_prev + i * c_\n\n # Current Hidden state\n current_hidden_state = o * tf.compat.v1.nn.tanh(c)\n\n return tf.compat.v1.stack([current_hidden_state, c])\n\n return unit\n\n def create_output_unit(self, params):\n self.Wo = tf.compat.v1.Variable(self.init_matrix([self.hidden_dim, self.num_classes]))\n self.bo = tf.compat.v1.Variable(self.init_matrix([self.num_classes]))\n params.extend([self.Wo, self.bo])\n\n def unit(hidden_memory_tuple):\n hidden_state, c_prev = tf.compat.v1.unstack(hidden_memory_tuple)\n logits = tf.compat.v1.nn.softmax(tf.compat.v1.matmul(hidden_state, self.Wo) + self.bo)\n return logits\n\n return unit\n" ]
[ [ "tensorflow.compat.v1.matmul", "tensorflow.compat.v1.trainable_variables", "tensorflow.compat.v1.constant", "tensorflow.compat.v1.placeholder", "tensorflow.compat.v1.name_scope", "tensorflow.compat.v1.train.AdamOptimizer", "tensorflow.compat.v1.gradients", "tensorflow.compat.v1.unstack", "tensorflow.compat.v1.stack", "numpy.eye", "tensorflow.compat.v1.slice", "tensorflow.compat.v1.reduce_mean", "tensorflow.compat.v1.cast", "numpy.zeros", "tensorflow.compat.v1.nn.softmax_cross_entropy_with_logits", "tensorflow.compat.v1.variable_scope", "tensorflow.compat.v1.nn.tanh", "tensorflow.compat.v1.nn.embedding_lookup", "tensorflow.compat.v1.random_normal" ] ]
fumiyo0607/ETM
[ "c9525d11491f9a4b86d2a0dc1231e6a0aef58c7c" ]
[ "main.py" ]
[ "#/usr/bin/python\n\nfrom __future__ import print_function\n\nimport argparse\nimport torch\nimport pickle \nimport numpy as np \nimport os \nimport math \nimport random \nimport sys\nimport matplotlib.pyplot as plt \nimport data\nimport scipy.io\nimport pandas as pd\n\nfrom torch import nn, optim\nfrom torch.nn import functional as F\n\nfrom etm import ETM\nfrom utils import nearest_neighbors, get_topic_coherence, get_topic_diversity\n\nparser = argparse.ArgumentParser(description='The Embedded Topic Model')\n\n### data and file related arguments\nparser.add_argument('--dataset', type=str, default='20ng', help='name of corpus')\nparser.add_argument('--data_path', type=str, default='data/20ng', help='directory containing data')\nparser.add_argument('--emb_path', type=str, default='data/20ng_embeddings.txt', help='directory containing word embeddings')\nparser.add_argument('--save_path', type=str, default='./results', help='path to save results')\nparser.add_argument('--batch_size', type=int, default=1000, help='input batch size for training')\n\n### model-related arguments\nparser.add_argument('--num_topics', type=int, default=50, help='number of topics')\nparser.add_argument('--rho_size', type=int, default=300, help='dimension of rho')\nparser.add_argument('--emb_size', type=int, default=300, help='dimension of embeddings')\nparser.add_argument('--t_hidden_size', type=int, default=800, help='dimension of hidden space of q(theta)')\nparser.add_argument('--theta_act', type=str, default='relu', help='tanh, softplus, relu, rrelu, leakyrelu, elu, selu, glu)')\nparser.add_argument('--train_embeddings', type=int, default=0, help='whether to fix rho or train it')\n\n### optimization-related arguments\nparser.add_argument('--lr', type=float, default=0.005, help='learning rate')\nparser.add_argument('--lr_factor', type=float, default=4.0, help='divide learning rate by this...')\nparser.add_argument('--epochs', type=int, default=20, help='number of epochs to train...150 for 20ng 100 for others')\nparser.add_argument('--mode', type=str, default='train', help='train or eval model')\nparser.add_argument('--optimizer', type=str, default='adam', help='choice of optimizer')\nparser.add_argument('--seed', type=int, default=2019, help='random seed (default: 1)')\nparser.add_argument('--enc_drop', type=float, default=0.0, help='dropout rate on encoder')\nparser.add_argument('--clip', type=float, default=0.0, help='gradient clipping')\nparser.add_argument('--nonmono', type=int, default=10, help='number of bad hits allowed')\nparser.add_argument('--wdecay', type=float, default=1.2e-6, help='some l2 regularization')\nparser.add_argument('--anneal_lr', type=int, default=0, help='whether to anneal the learning rate or not')\nparser.add_argument('--bow_norm', type=int, default=1, help='normalize the bows or not')\n\n### evaluation, visualization, and logging-related arguments\nparser.add_argument('--num_words', type=int, default=10, help='number of words for topic viz')\nparser.add_argument('--log_interval', type=int, default=2, help='when to log training')\nparser.add_argument('--visualize_every', type=int, default=10, help='when to visualize results')\nparser.add_argument('--eval_batch_size', type=int, default=1000, help='input batch size for evaluation')\nparser.add_argument('--load_from', type=str, default='', help='the name of the ckpt to eval from')\nparser.add_argument('--tc', type=int, default=0, help='whether to compute topic coherence or not')\nparser.add_argument('--td', type=int, default=0, help='whether to compute topic diversity or not')\n\nargs = parser.parse_args()\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\ndata_name = args.data_path.split('/')[1]\n\nepoch_list = []\nlr_list = [] \ncur_kl_theta_list = []\ncur_loss_list = [] \ncur_real_loss_list = []\n\nprint('\\n')\nnp.random.seed(args.seed)\ntorch.manual_seed(args.seed)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(args.seed)\n\n## get data\n# 1. vocabulary\nvocab, train, valid, test = data.get_data(os.path.join(args.data_path))\nvocab_size = len(vocab)\nargs.vocab_size = vocab_size\n\n# 1. training data\ntrain_tokens = train['tokens']\ntrain_counts = train['counts']\nargs.num_docs_train = len(train_tokens)\n\n# 2. dev set\nvalid_tokens = valid['tokens']\nvalid_counts = valid['counts']\nargs.num_docs_valid = len(valid_tokens)\n\n# 3. test data\ntest_tokens = test['tokens']\ntest_counts = test['counts']\nargs.num_docs_test = len(test_tokens)\ntest_1_tokens = test['tokens_1']\ntest_1_counts = test['counts_1']\nargs.num_docs_test_1 = len(test_1_tokens)\ntest_2_tokens = test['tokens_2']\ntest_2_counts = test['counts_2']\nargs.num_docs_test_2 = len(test_2_tokens)\n\nembeddings = None\nif not args.train_embeddings:\n emb_path = args.emb_path\n vect_path = os.path.join(args.data_path.split('/')[0], 'embeddings.pkl') \n vectors = {}\n with open(emb_path, 'rb') as f:\n for l in f:\n line = l.decode().split()\n word = line[0]\n if word in vocab:\n vect = np.array(line[1:]).astype(np.float)\n vectors[word] = vect\n embeddings = np.zeros((vocab_size, args.emb_size))\n words_found = 0\n for i, word in enumerate(vocab):\n try: \n embeddings[i] = vectors[word]\n words_found += 1\n except KeyError:\n embeddings[i] = np.random.normal(scale=0.6, size=(args.emb_size, ))\n embeddings = torch.from_numpy(embeddings).to()\n args.embeddings_dim = embeddings.size()\n\nprint('=*'*100)\nprint('Training an Embedded Topic Model on {} with the following settings: {}'.format(args.dataset.upper(), args))\nprint('=*'*100)\n\nprint('vocab num = {}'.format(len(vocab)))\n\n## define checkpoint\nif not os.path.exists(args.save_path):\n os.makedirs(args.save_path)\n\nif args.mode == 'eval':\n ckpt = args.load_from\nelse:\n data_name = args.data_path.split('/')[1]\n ckpt = os.path.join(args.save_path, \n 'etm_{}_K_{}_Htheta_{}_Optim_{}_Clip_{}_ThetaAct_{}_Lr_{}_Bsz_{}_RhoSize_{}_trainEmbeddings_{}'.format(\n data_name, args.num_topics, args.t_hidden_size, args.optimizer, args.clip, args.theta_act, \n args.lr, args.batch_size, args.rho_size, args.train_embeddings))\n\n## define model and optimizer\nmodel = ETM(args.num_topics, vocab_size, args.t_hidden_size, args.rho_size, args.emb_size, \n args.theta_act, embeddings, args.train_embeddings, args.enc_drop).to(device)\n\nprint('model: {}'.format(model))\n\nif args.optimizer == 'adam':\n optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.wdecay)\nelif args.optimizer == 'adagrad':\n optimizer = optim.Adagrad(model.parameters(), lr=args.lr, weight_decay=args.wdecay)\nelif args.optimizer == 'adadelta':\n optimizer = optim.Adadelta(model.parameters(), lr=args.lr, weight_decay=args.wdecay)\nelif args.optimizer == 'rmsprop':\n optimizer = optim.RMSprop(model.parameters(), lr=args.lr, weight_decay=args.wdecay)\nelif args.optimizer == 'asgd':\n optimizer = optim.ASGD(model.parameters(), lr=args.lr, t0=0, lambd=0., weight_decay=args.wdecay)\nelse:\n print('Defaulting to vanilla SGD')\n optimizer = optim.SGD(model.parameters(), lr=args.lr)\n\ndef train(epoch):\n model.train()\n acc_loss = 0\n acc_kl_theta_loss = 0\n cnt = 0\n indices = torch.randperm(args.num_docs_train)\n indices = torch.split(indices, args.batch_size)\n for idx, ind in enumerate(indices):\n optimizer.zero_grad()\n model.zero_grad()\n data_batch = data.get_batch(train_tokens, train_counts, ind, args.vocab_size, device)\n sums = data_batch.sum(1).unsqueeze(1)\n if args.bow_norm:\n normalized_data_batch = data_batch / sums\n else:\n normalized_data_batch = data_batch\n recon_loss, kld_theta = model(data_batch, normalized_data_batch)\n total_loss = recon_loss + kld_theta\n total_loss.backward()\n\n if args.clip > 0:\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)\n optimizer.step()\n\n acc_loss += torch.sum(recon_loss).item()\n acc_kl_theta_loss += torch.sum(kld_theta).item()\n cnt += 1\n\n if idx % args.log_interval == 0 and idx > 0:\n cur_loss = round(acc_loss / cnt, 2) \n cur_kl_theta = round(acc_kl_theta_loss / cnt, 2) \n cur_real_loss = round(cur_loss + cur_kl_theta, 2)\n\n print('Epoch: {} .. batch: {}/{} .. LR: {} .. KL_theta: {} .. Rec_loss: {} .. NELBO: {}'.format(\n epoch, idx, len(indices), optimizer.param_groups[0]['lr'], cur_kl_theta, cur_loss, cur_real_loss))\n\n epoch_list.append(epoch)\n lr_list.append(optimizer.param_groups[0]['lr'])\n cur_kl_theta_list.append(cur_kl_theta)\n cur_loss_list.append(cur_kl_theta)\n cur_real_loss_list.append(cur_real_loss)\n \n cur_loss = round(acc_loss / cnt, 2) \n cur_kl_theta = round(acc_kl_theta_loss / cnt, 2) \n cur_real_loss = round(cur_loss + cur_kl_theta, 2)\n print('*'*100)\n print('Epoch----->{} .. LR: {} .. KL_theta: {} .. Rec_loss: {} .. NELBO: {}'.format(\n epoch, optimizer.param_groups[0]['lr'], cur_kl_theta, cur_loss, cur_real_loss))\n print('*'*100)\n\n epoch_list.append(epoch)\n lr_list.append(optimizer.param_groups[0]['lr'])\n cur_kl_theta_list.append(cur_kl_theta)\n cur_loss_list.append(cur_loss)\n cur_real_loss_list.append(cur_real_loss)\n\n train_df = pd.DataFrame(data = {\n 'Epoch' : epoch_list,\n 'LR' : lr_list,\n 'KL_theta' : cur_kl_theta_list,\n 'Rec_loss' : cur_loss_list,\n 'NELBO' : cur_real_loss_list \n })\n\n if not os.path.exists('./experiments/{}'.format(data_name)):\n os.makedirs('./experiments/{}'.format(data_name))\n \n train_df.to_csv('./experiments/etm_{}_K_{}_Htheta_{}_Optim_{}_Clip_{}_ThetaAct_{}_Lr_{}_Bsz_{}_RhoSize_{}_trainEmbeddings_{}.csv'.format(\n data_name, args.dataset, args.num_topics, args.t_hidden_size, args.optimizer, args.clip, args.theta_act, \n args.lr, args.batch_size, args.rho_size, args.train_embeddings))\n\n\ndef visualize(m, show_emb=True):\n if not os.path.exists('./results'):\n os.makedirs('./results')\n\n m.eval()\n\n queries = ['andrew', 'computer', 'sports', 'religion', 'man', 'love', \n 'intelligence', 'money', 'politics', 'health', 'people', 'family']\n\n ## visualize topics using monte carlo\n with torch.no_grad():\n print('#'*100)\n print('Visualize topics...')\n topics_words = []\n gammas = m.get_beta()\n for k in range(args.num_topics):\n gamma = gammas[k]\n top_words = list(gamma.cpu().numpy().argsort()[-args.num_words+1:][::-1])\n topic_words = [vocab[a] for a in top_words]\n topics_words.append(' '.join(topic_words))\n print('Topic {}: {}'.format(k, topic_words))\n\n if show_emb:\n ## visualize word embeddings by using V to get nearest neighbors\n print('#'*100)\n print('Visualize word embeddings by using output embedding matrix')\n try:\n embeddings = m.rho.weight # Vocab_size x E\n except:\n embeddings = m.rho # Vocab_size x E\n neighbors = []\n for word in queries:\n print('word: {} .. neighbors: {}'.format(\n word, nearest_neighbors(word, embeddings, vocab)))\n print('#'*100)\n\ndef evaluate(m, source, tc=False, td=False):\n \"\"\"Compute perplexity on document completion.\n \"\"\"\n m.eval()\n with torch.no_grad():\n if source == 'val':\n indices = torch.split(torch.tensor(range(args.num_docs_valid)), args.eval_batch_size)\n tokens = valid_tokens\n counts = valid_counts\n else: \n indices = torch.split(torch.tensor(range(args.num_docs_test)), args.eval_batch_size)\n tokens = test_tokens\n counts = test_counts\n\n ## get \\beta here\n beta = m.get_beta()\n\n ### do dc and tc here\n acc_loss = 0\n cnt = 0\n indices_1 = torch.split(torch.tensor(range(args.num_docs_test_1)), args.eval_batch_size)\n for idx, ind in enumerate(indices_1):\n ## get theta from first half of docs\n data_batch_1 = data.get_batch(test_1_tokens, test_1_counts, ind, args.vocab_size, device)\n sums_1 = data_batch_1.sum(1).unsqueeze(1)\n if args.bow_norm:\n normalized_data_batch_1 = data_batch_1 / sums_1\n else:\n normalized_data_batch_1 = data_batch_1\n theta, _ = m.get_theta(normalized_data_batch_1)\n\n ## get prediction loss using second half\n data_batch_2 = data.get_batch(test_2_tokens, test_2_counts, ind, args.vocab_size, device)\n sums_2 = data_batch_2.sum(1).unsqueeze(1)\n res = torch.mm(theta, beta)\n preds = torch.log(res)\n recon_loss = -(preds * data_batch_2).sum(1)\n \n loss = recon_loss / sums_2.squeeze()\n loss = loss.mean().item()\n acc_loss += loss\n cnt += 1\n cur_loss = acc_loss / cnt\n ppl_dc = round(math.exp(cur_loss), 1)\n print('*'*100)\n print('{} Doc Completion PPL: {}'.format(source.upper(), ppl_dc))\n print('*'*100)\n if tc or td:\n beta = beta.data.cpu().numpy()\n if tc:\n print('Computing topic coherence...')\n get_topic_coherence(beta, train_tokens, vocab)\n if td:\n print('Computing topic diversity...')\n get_topic_diversity(beta, 25)\n return ppl_dc\n\nif args.mode == 'train':\n ## train model on data \n best_epoch = 0\n best_val_ppl = 1e9\n all_val_ppls = []\n print('\\n')\n print('Visualizing model quality before training...')\n visualize(model)\n print('\\n')\n for epoch in range(1, args.epochs):\n train(epoch)\n val_ppl = evaluate(model, 'val')\n if val_ppl < best_val_ppl:\n with open(ckpt, 'wb') as f:\n torch.save(model, f)\n best_epoch = epoch\n best_val_ppl = val_ppl\n else:\n ## check whether to anneal lr\n lr = optimizer.param_groups[0]['lr']\n if args.anneal_lr and (len(all_val_ppls) > args.nonmono and val_ppl > min(all_val_ppls[:-args.nonmono]) and lr > 1e-5):\n optimizer.param_groups[0]['lr'] /= args.lr_factor\n if epoch % args.visualize_every == 0:\n visualize(model)\n all_val_ppls.append(val_ppl)\n with open(ckpt, 'rb') as f:\n model = torch.load(f)\n model = model.to(device)\n val_ppl = evaluate(model, 'val')\nelse: \n with open(ckpt, 'rb') as f:\n # model = torch.load(f)\n model = torch.load(f, map_location=torch.device('cpu'))\n model = model.to(device)\n model.eval()\n\n with torch.no_grad():\n ## get document completion perplexities\n test_ppl = evaluate(model, 'test', tc=args.tc, td=args.td)\n\n ## get most used topics\n indices = torch.tensor(range(args.num_docs_train))\n indices = torch.split(indices, args.batch_size)\n thetaAvg = torch.zeros(1, args.num_topics).to(device)\n thetaWeightedAvg = torch.zeros(1, args.num_topics).to(device)\n cnt = 0\n for idx, ind in enumerate(indices):\n data_batch = data.get_batch(train_tokens, train_counts, ind, args.vocab_size, device)\n sums = data_batch.sum(1).unsqueeze(1)\n cnt += sums.sum(0).squeeze().cpu().numpy()\n if args.bow_norm:\n normalized_data_batch = data_batch / sums\n else:\n normalized_data_batch = data_batch\n theta, _ = model.get_theta(normalized_data_batch)\n thetaAvg += theta.sum(0).unsqueeze(0) / args.num_docs_train\n weighed_theta = sums * theta\n thetaWeightedAvg += weighed_theta.sum(0).unsqueeze(0)\n if idx % 100 == 0 and idx > 0:\n print('batch: {}/{}'.format(idx, len(indices)))\n thetaWeightedAvg = thetaWeightedAvg.squeeze().cpu().numpy() / cnt\n thetaWeightedAvg_list = list(thetaWeightedAvg)\n topicNum = list(range(0, args.num_topics ,1))\n\n topic_probability_df = pd.DataFrame(data = {\n 'topic_num' : topicNum,\n 'probability' : thetaWeightedAvg_list\n })\n\n data_name = args.data_path.split('/')[1]\n\n if not os.path.exists('./experiments/{}_K={}'.format(data_name, args.num_topics)):\n os.makedirs('./experiments/{}_K={}'.format(data_name, args.num_topics))\n topic_probability_df.to_csv(('./experiments/{}_K={}/topic_probability.csv'.format(data_name, args.num_topics)))\n \n\n print('*'*100)\n print('thetaWeightedAvg = \\n {}'.format(thetaWeightedAvg))\n print('\\nThe 10 most used topics are {}'.format(thetaWeightedAvg.argsort()[::-1][:10]))\n\n ## show topics\n beta = model.get_beta()\n topic_indices = list(np.random.choice(args.num_topics, 10)) # 10 random topics\n print('\\n')\n\n topic_words_list = []\n topic_words_probability_list = []\n topic_list = []\n\n for k in range(args.num_topics):#topic_indices:\n gamma = beta[k]\n gamma_list = list(gamma.cpu().numpy())\n top_words = list(gamma.cpu().numpy().argsort()[-args.num_words:][::-1])\n topic_words = [vocab[a] for a in top_words]\n topic_words_probability = [gamma_list[a] for a in top_words]\n print('Topic {}: {}'.format(k, topic_words))\n\n # add top words..\n topic_list += [k] * args.num_words\n topic_words_list += topic_words\n topic_words_probability_list += topic_words_probability\n \n topic_words_probability_df = pd.DataFrame( data= {\n 'topic' : topic_list,\n 'word' : topic_words_list,\n 'probability' : topic_words_probability_list,\n })\n\n data_name = args.data_path.split('/')[1]\n\n if not os.path.exists('./experiments/{}_K={}'.format(data_name, args.num_topics)):\n os.makedirs('./experiments/{}_K={}'.format(data_name, args.num_topics))\n topic_words_probability_df.to_csv(('./experiments/{}_K={}/topic_words_probability.csv'.format(data_name, args.num_topics)))\n \n\n if args.train_embeddings:\n ## show etm embeddings \n try:\n rho_etm = model.rho.weight.cpu()\n except:\n rho_etm = model.rho.cpu()\n queries = ['andrew', 'woman', 'computer', 'sports', 'religion', 'man', 'love', \n 'intelligence', 'money', 'politics', 'health', 'people', 'family']\n print('\\n')\n print('ETM embeddings...')\n for word in queries:\n print('word: {} .. etm neighbors: {}'.format(word, nearest_neighbors(word, rho_etm, vocab)))\n print('\\n')\n" ]
[ [ "torch.cuda.manual_seed", "numpy.random.choice", "torch.randperm", "torch.cuda.is_available", "torch.load", "torch.sum", "numpy.random.normal", "pandas.DataFrame", "torch.manual_seed", "torch.zeros", "torch.device", "numpy.array", "numpy.zeros", "torch.save", "torch.mm", "torch.log", "numpy.random.seed", "torch.split", "torch.no_grad", "torch.from_numpy" ] ]
snailfrying/nlp_cv_recommendation_papers
[ "03d1c048ebb2ea1487aa8eaf344c4b1c1474bff9" ]
[ "cv_papers/ResNet/ResNetXt.py" ]
[ "# -*- coding: utf-8 -*-\n# @File : ResNetXt.py\n# @Author: snailfrying\n# @Time : 2021/9/22 10:30\n# @Software: PyCharm\n\nimport numpy as np\n\nfrom tensorflow import keras\nfrom tensorflow.keras import layers, utils, regularizers\nfrom tensorflow.python.keras import backend\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.python.keras.engine import training\n\n# Model / data parameters\nnum_classes = 10\ninput_shape = (224, 224, 3)\n\n\ndef read_data():\n # the data, split between train and test sets\n (x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()\n # Scale images to the [0, 1] range\n x_train = x_train.astype(\"float32\") / 255\n x_test = x_test.astype(\"float32\") / 255\n # Make sure images have shape (28, 28, 1)\n x_train = [image.smart_resize(img, (224, 224)) for img in x_train]\n x_test = [image.smart_resize(img, (224, 224)) for img in x_test]\n x_train, x_test = np.array(x_train), np.array(x_test)\n\n print(\"x_train shape:\", x_train.shape)\n print(x_train.shape[0], \"train samples\")\n print(x_test.shape[0], \"test samples\")\n # convert class vectors to binary class matrices\n y_test = utils.to_categorical(y_test, num_classes)\n y_train = utils.to_categorical(y_train, num_classes)\n return x_train, y_train, x_test, y_test\n\n\n# 建立初始化层\ndef initial_conv_block(inputs, weight_decay=5e-4):\n bn_axis = 3 if backend.image_data_format() == 'channels_last' else 1\n\n x = layers.Conv2D(64, (7, 7), strides=2, padding='same', use_bias=False)(inputs)\n x = layers.MaxPooling2D(pool_size=3, strides=2, padding='same')(x)\n x = layers.BatchNormalization(axis=bn_axis)(x)\n x = layers.Activation('relu')(x)\n\n return x\n\n\n# 建立group convolution,即根据cardinality,把输入特征划分cardinality个group,然后对每一个group使用channels-filters提取特征,最后合并。\ndef group_conv(inputs, group_channels, cardinality, kernel_size=3, strides=1, padding='same', weight_decay=5e-4,\n name=None):\n bn_axis = 3 if backend.image_data_format() == 'channels_last' else 1\n\n if cardinality == 1:\n x = layers.Conv2D(group_channels, kernel_size=kernel_size, strides=strides, padding=padding,\n name=name + '_conv2')(inputs)\n x = layers.BatchNormalization(axis=bn_axis, name=name + '_conv2_bn')(x)\n x = layers.Activation(activation='relu', name=name + '_conv2_act')(x)\n return x\n\n feature_map_list = []\n for c in range(cardinality):\n x = layers.Lambda(\n lambda z: z[:, :, :, c * group_channels:(c + 1) * group_channels]\n if backend.image_data_format() == 'channels_last'\n else lambda z: z[:, c * group_channels:(c + 1) * group_channels, :, :]\n )(inputs)\n\n x = layers.Conv2D(filters=group_channels, kernel_size=kernel_size, strides=strides, padding=padding,\n name=name + '_groupconv3_' + str(c))(x)\n feature_map_list.append(x)\n x = layers.concatenate(feature_map_list, axis=bn_axis, name=name + '_groupconv3_concat')\n x = layers.BatchNormalization(axis=bn_axis, name=name + '_groupconv3_bn')(x)\n x = layers.Activation(activation='relu', name=name + '_groupconv3_act')(x)\n return x\n\n\n# 构建ResNetXt的block\ndef bottlencect_block(inputs, filters=64, cardinality=8, strides=1, weight_decay=5e-4, name=None):\n group_channels = filters // cardinality\n assert group_channels == 0\n bn_axis = 3 if backend.image_data_format() == 'channels_last' else 1\n\n init = inputs\n if init.shape[-1] != 2 * filters:\n init = layers.Conv2D(filters * 2, (1, 1), padding='same', strides=(strides, strides), name=name + '_conv')(init)\n init = layers.BatchNormalization(axis=bn_axis, name=name + '_bn')(init)\n # conv 1*1\n x = layers.Conv2D(filters, kernel_size=1, strides=strides, padding='same', name=name + '_conv1')(inputs)\n x = layers.BatchNormalization(axis=bn_axis, name=name + '_conv1_bn1')(x)\n x = layers.Activation(activation='relu', name=name + '_conv1_act')(x)\n # group conv 3*3\n x = group_conv(\n x, group_channels=group_channels, cardinality=cardinality, strides=1, weight_decay=weight_decay, name=name)\n # conv 1*1\n x = layers.Conv2D(2 * filters, kernel_size=1, padding='same', use_bias=False, name=name + '_conv4')(x)\n x = layers.BatchNormalization(axis=bn_axis, name=name + '_conv4_bn')(x)\n # residual\n x = layers.add([init, x])\n x = layers.Activation(activation='relu', name=name + '_conv4_act')(x)\n\n return x\n\n\n# create ResNetXt\n# 为了简洁, 网络没有加初始化和正则化,可根据卷积自行调整\ndef ResNetXt(input_shape, classes, cardinality=8, blocks=None):\n bn_axis = 3 if backend.image_data_format() == 'channels_last' else 1\n img_input = keras.Input(shape=input_shape, name='inputs')\n\n x = initial_conv_block(img_input, weight_decay=5e-4)\n # blocks1\n for i in range(blocks[0]):\n x = bottlencect_block(x, filters=2 * 64, cardinality=cardinality, strides=1, weight_decay=5e-4,\n name='blocks_1_%d' % i)\n # blocks数 2~4\n for i, b in enumerate(blocks[1:]):\n f = 2 ** (i + 2) # 控制filters\n i = i + 2 # 控制blocks id\n for j in range(b):\n # block的第一层,图片减小一倍---同resnet\n if j == 0:\n x = bottlencect_block(x, filters=64 * f, cardinality=cardinality, strides=2, weight_decay=5e-4,\n name='blocks_%d_%d' % (i, j))\n else:\n x = bottlencect_block(x, filters=64 * f, cardinality=cardinality, strides=1, weight_decay=5e-4,\n name='blocks_%d_%d' % (i, j))\n\n x = layers.GlobalAveragePooling2D(name='features')(x)\n x = layers.Dense(classes, use_bias=False, activation='softmax', name='classes')(x)\n\n model = training.Model(img_input, x, name='ResNetXt')\n\n return model\n\n\nif __name__ == '__main__':\n x_train, y_train, x_test, y_test = read_data()\n # 每一个blocks的重复次数 50:[3, 4, 6, 3] 101: [3, 4, 23, 3]\n blocks = [3, 4, 23, 3]\n model = ResNetXt(input_shape=input_shape, classes=num_classes, blocks=blocks)\n # 编译模型\n opt = keras.optimizers.Adam(learning_rate=1e-3, epsilon=1e-7)\n model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\n model.fit(x=x_train, y=y_train, batch_size=500, epochs=10, validation_split=0.2, validation_data=[x_test, y_test])\n model.summary()\n\n pre = model.evaluate(x_test, y_test, batch_size=500)\n print('test_loss: ', pre[0], 'test_acc: ', pre[1])\n" ]
[ [ "tensorflow.python.keras.backend.image_data_format", "tensorflow.keras.utils.to_categorical", "numpy.array", "tensorflow.keras.layers.add", "tensorflow.python.keras.engine.training.Model", "tensorflow.keras.layers.Activation", "tensorflow.keras.preprocessing.image.smart_resize", "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.layers.BatchNormalization", "tensorflow.keras.layers.MaxPooling2D", "tensorflow.keras.layers.GlobalAveragePooling2D", "tensorflow.keras.datasets.cifar10.load_data", "tensorflow.keras.Input", "tensorflow.keras.optimizers.Adam", "tensorflow.keras.layers.concatenate" ] ]
hhuuggoo/pandas
[ "f87ab95c2ecd1be6a3e3acec8f5d81e7f3c8e4bd" ]
[ "pandas/core/generic.py" ]
[ "# pylint: disable=W0231,E1101\nimport warnings\nimport operator\nimport weakref\nimport gc\nimport numpy as np\nimport pandas.lib as lib\n\nimport pandas as pd\nfrom pandas.core.base import PandasObject\nfrom pandas.core.index import (Index, MultiIndex, _ensure_index,\n InvalidIndexError)\nimport pandas.core.indexing as indexing\nfrom pandas.core.indexing import _maybe_convert_indices\nfrom pandas.tseries.index import DatetimeIndex\nfrom pandas.tseries.period import PeriodIndex\nfrom pandas.core.internals import BlockManager\nimport pandas.core.array as pa\nimport pandas.core.common as com\nimport pandas.core.datetools as datetools\nfrom pandas import compat, _np_version_under1p7\nfrom pandas.compat import map, zip, lrange, string_types, isidentifier\nfrom pandas.core.common import (isnull, notnull, is_list_like,\n _values_from_object, _maybe_promote, ABCSeries,\n SettingWithCopyError, SettingWithCopyWarning)\nimport pandas.core.nanops as nanops\nfrom pandas.util.decorators import Appender, Substitution\nfrom pandas.core import config\n\n# goal is to be able to define the docs close to function, while still being\n# able to share\n_shared_docs = dict()\n_shared_doc_kwargs = dict(axes='keywords for axes',\n klass='NDFrame',\n axes_single_arg='int or labels for object',\n args_transpose='axes to permute (int or label for'\n ' object)')\n\n\ndef is_dictlike(x):\n return isinstance(x, (dict, com.ABCSeries))\n\n\ndef _single_replace(self, to_replace, method, inplace, limit):\n if self.ndim != 1:\n raise TypeError('cannot replace {0} with method {1} on a {2}'\n .format(to_replace, method, type(self).__name__))\n\n orig_dtype = self.dtype\n result = self if inplace else self.copy()\n fill_f = com._get_fill_func(method)\n\n mask = com.mask_missing(result.values, to_replace)\n values = fill_f(result.values, limit=limit, mask=mask)\n\n if values.dtype == orig_dtype and inplace:\n return\n\n result = pd.Series(values, index=self.index,\n dtype=self.dtype).__finalize__(self)\n\n if inplace:\n self._update_inplace(result._data)\n return\n\n return result\n\n\nclass NDFrame(PandasObject):\n\n \"\"\"\n N-dimensional analogue of DataFrame. Store multi-dimensional in a\n size-mutable, labeled data structure\n\n Parameters\n ----------\n data : BlockManager\n axes : list\n copy : boolean, default False\n \"\"\"\n _internal_names = ['_data', '_cacher', '_item_cache', '_cache',\n 'is_copy', 'str', '_subtyp', '_index', '_default_kind',\n '_default_fill_value','__array_struct__','__array_interface__']\n _internal_names_set = set(_internal_names)\n _metadata = []\n is_copy = None\n\n def __init__(self, data, axes=None, copy=False, dtype=None,\n fastpath=False):\n\n if not fastpath:\n if dtype is not None:\n data = data.astype(dtype)\n elif copy:\n data = data.copy()\n\n if axes is not None:\n for i, ax in enumerate(axes):\n data = data.reindex_axis(ax, axis=i)\n\n object.__setattr__(self, 'is_copy', None)\n object.__setattr__(self, '_data', data)\n object.__setattr__(self, '_item_cache', {})\n\n def _validate_dtype(self, dtype):\n \"\"\" validate the passed dtype \"\"\"\n\n if dtype is not None:\n dtype = np.dtype(dtype)\n\n # a compound dtype\n if dtype.kind == 'V':\n raise NotImplementedError(\"compound dtypes are not implemented\"\n \"in the {0} constructor\"\n .format(self.__class__.__name__))\n return dtype\n\n def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):\n \"\"\" passed a manager and a axes dict \"\"\"\n for a, axe in axes.items():\n if axe is not None:\n mgr = mgr.reindex_axis(\n axe, axis=self._get_block_manager_axis(a), copy=False)\n\n # do not copy BlockManager unless explicitly done\n if copy and dtype is None:\n mgr = mgr.copy()\n elif dtype is not None:\n # avoid copy if we can\n if len(mgr.blocks) > 1 or mgr.blocks[0].values.dtype != dtype:\n mgr = mgr.astype(dtype=dtype)\n return mgr\n\n #----------------------------------------------------------------------\n # Construction\n\n @property\n def _constructor(self):\n raise NotImplementedError\n\n def __unicode__(self):\n # unicode representation based upon iterating over self\n # (since, by definition, `PandasContainers` are iterable)\n prepr = '[%s]' % ','.join(map(com.pprint_thing, self))\n return '%s(%s)' % (self.__class__.__name__, prepr)\n\n def _local_dir(self):\n \"\"\" add the string-like attributes from the info_axis \"\"\"\n return [c for c in self._info_axis\n if isinstance(c, string_types) and isidentifier(c)]\n\n @property\n def _constructor_sliced(self):\n raise NotImplementedError\n\n #----------------------------------------------------------------------\n # Axis\n\n @classmethod\n def _setup_axes(\n cls, axes, info_axis=None, stat_axis=None, aliases=None, slicers=None,\n axes_are_reversed=False, build_axes=True, ns=None):\n \"\"\" provide axes setup for the major PandasObjects\n\n axes : the names of the axes in order (lowest to highest)\n info_axis_num : the axis of the selector dimension (int)\n stat_axis_num : the number of axis for the default stats (int)\n aliases : other names for a single axis (dict)\n slicers : how axes slice to others (dict)\n axes_are_reversed : boolean whether to treat passed axes as\n reversed (DataFrame)\n build_axes : setup the axis properties (default True)\n \"\"\"\n\n cls._AXIS_ORDERS = axes\n cls._AXIS_NUMBERS = dict((a, i) for i, a in enumerate(axes))\n cls._AXIS_LEN = len(axes)\n cls._AXIS_ALIASES = aliases or dict()\n cls._AXIS_IALIASES = dict((v, k)\n for k, v in cls._AXIS_ALIASES.items())\n cls._AXIS_NAMES = dict(enumerate(axes))\n cls._AXIS_SLICEMAP = slicers or None\n cls._AXIS_REVERSED = axes_are_reversed\n\n # typ\n setattr(cls, '_typ', cls.__name__.lower())\n\n # indexing support\n cls._ix = None\n\n if info_axis is not None:\n cls._info_axis_number = info_axis\n cls._info_axis_name = axes[info_axis]\n\n if stat_axis is not None:\n cls._stat_axis_number = stat_axis\n cls._stat_axis_name = axes[stat_axis]\n\n # setup the actual axis\n if build_axes:\n\n def set_axis(a, i):\n setattr(cls, a, lib.AxisProperty(i))\n\n if axes_are_reversed:\n m = cls._AXIS_LEN - 1\n for i, a in cls._AXIS_NAMES.items():\n set_axis(a, m - i)\n else:\n for i, a in cls._AXIS_NAMES.items():\n set_axis(a, i)\n\n # addtl parms\n if isinstance(ns, dict):\n for k, v in ns.items():\n setattr(cls, k, v)\n\n def _construct_axes_dict(self, axes=None, **kwargs):\n \"\"\" return an axes dictionary for myself \"\"\"\n d = dict([(a, self._get_axis(a)) for a in (axes or self._AXIS_ORDERS)])\n d.update(kwargs)\n return d\n\n @staticmethod\n def _construct_axes_dict_from(self, axes, **kwargs):\n \"\"\" return an axes dictionary for the passed axes \"\"\"\n d = dict([(a, ax) for a, ax in zip(self._AXIS_ORDERS, axes)])\n d.update(kwargs)\n return d\n\n def _construct_axes_dict_for_slice(self, axes=None, **kwargs):\n \"\"\" return an axes dictionary for myself \"\"\"\n d = dict([(self._AXIS_SLICEMAP[a], self._get_axis(a))\n for a in (axes or self._AXIS_ORDERS)])\n d.update(kwargs)\n return d\n\n def _construct_axes_from_arguments(self, args, kwargs, require_all=False):\n \"\"\" construct and returns axes if supplied in args/kwargs\n if require_all, raise if all axis arguments are not supplied\n return a tuple of (axes, kwargs) \"\"\"\n\n # construct the args\n args = list(args)\n for a in self._AXIS_ORDERS:\n\n # if we have an alias for this axis\n alias = self._AXIS_IALIASES.get(a)\n if alias is not None:\n if a in kwargs:\n if alias in kwargs:\n raise TypeError(\n \"arguments are mutually exclusive for [%s,%s]\" %\n (a, alias)\n )\n continue\n if alias in kwargs:\n kwargs[a] = kwargs.pop(alias)\n continue\n\n # look for a argument by position\n if a not in kwargs:\n try:\n kwargs[a] = args.pop(0)\n except (IndexError):\n if require_all:\n raise TypeError(\n \"not enough/duplicate arguments specified!\")\n\n axes = dict([(a, kwargs.get(a)) for a in self._AXIS_ORDERS])\n return axes, kwargs\n\n @classmethod\n def _from_axes(cls, data, axes):\n # for construction from BlockManager\n if isinstance(data, BlockManager):\n return cls(data)\n else:\n if cls._AXIS_REVERSED:\n axes = axes[::-1]\n d = cls._construct_axes_dict_from(cls, axes, copy=False)\n return cls(data, **d)\n\n def _get_axis_number(self, axis):\n axis = self._AXIS_ALIASES.get(axis, axis)\n if com.is_integer(axis):\n if axis in self._AXIS_NAMES:\n return axis\n else:\n try:\n return self._AXIS_NUMBERS[axis]\n except:\n pass\n raise ValueError('No axis named {0} for object type {1}'\n .format(axis, type(self)))\n\n def _get_axis_name(self, axis):\n axis = self._AXIS_ALIASES.get(axis, axis)\n if isinstance(axis, string_types):\n if axis in self._AXIS_NUMBERS:\n return axis\n else:\n try:\n return self._AXIS_NAMES[axis]\n except:\n pass\n raise ValueError('No axis named {0} for object type {1}'\n .format(axis, type(self)))\n\n def _get_axis(self, axis):\n name = self._get_axis_name(axis)\n return getattr(self, name)\n\n def _get_block_manager_axis(self, axis):\n \"\"\" map the axis to the block_manager axis \"\"\"\n axis = self._get_axis_number(axis)\n if self._AXIS_REVERSED:\n m = self._AXIS_LEN - 1\n return m - axis\n return axis\n\n def _get_axis_resolvers(self, axis):\n # index or columns\n axis_index = getattr(self, axis)\n d = dict()\n prefix = axis[0]\n\n for i, name in enumerate(axis_index.names):\n if name is not None:\n key = level = name\n else:\n # prefix with 'i' or 'c' depending on the input axis\n # e.g., you must do ilevel_0 for the 0th level of an unnamed\n # multiiindex\n key = '{prefix}level_{i}'.format(prefix=prefix, i=i)\n level = i\n\n level_values = axis_index.get_level_values(level)\n s = level_values.to_series()\n s.index = axis_index\n d[key] = s\n\n # put the index/columns itself in the dict\n if isinstance(axis_index, MultiIndex):\n dindex = axis_index\n else:\n dindex = axis_index.to_series()\n\n d[axis] = dindex\n return d\n\n def _get_resolvers(self):\n d = {}\n for axis_name in self._AXIS_ORDERS:\n d.update(self._get_axis_resolvers(axis_name))\n return d\n\n @property\n def _info_axis(self):\n return getattr(self, self._info_axis_name)\n\n @property\n def _stat_axis(self):\n return getattr(self, self._stat_axis_name)\n\n @property\n def shape(self):\n \"tuple of axis dimensions\"\n return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS)\n\n @property\n def axes(self):\n \"index(es) of the NDFrame\"\n # we do it this way because if we have reversed axes, then\n # the block manager shows then reversed\n return [self._get_axis(a) for a in self._AXIS_ORDERS]\n\n @property\n def ndim(self):\n \"Number of axes / array dimensions\"\n return self._data.ndim\n\n def _expand_axes(self, key):\n new_axes = []\n for k, ax in zip(key, self.axes):\n if k not in ax:\n if type(k) != ax.dtype.type:\n ax = ax.astype('O')\n new_axes.append(ax.insert(len(ax), k))\n else:\n new_axes.append(ax)\n\n return new_axes\n\n def _set_axis(self, axis, labels):\n self._data.set_axis(axis, labels)\n self._clear_item_cache()\n\n _shared_docs['transpose'] = \"\"\"\n Permute the dimensions of the %(klass)s\n\n Parameters\n ----------\n args : %(args_transpose)s\n copy : boolean, default False\n Make a copy of the underlying data. Mixed-dtype data will\n always result in a copy\n\n Examples\n --------\n >>> p.transpose(2, 0, 1)\n >>> p.transpose(2, 0, 1, copy=True)\n\n Returns\n -------\n y : same as input\n \"\"\"\n\n @Appender(_shared_docs['transpose'] % _shared_doc_kwargs)\n def transpose(self, *args, **kwargs):\n\n # construct the args\n axes, kwargs = self._construct_axes_from_arguments(\n args, kwargs, require_all=True)\n axes_names = tuple([self._get_axis_name(axes[a])\n for a in self._AXIS_ORDERS])\n axes_numbers = tuple([self._get_axis_number(axes[a])\n for a in self._AXIS_ORDERS])\n\n # we must have unique axes\n if len(axes) != len(set(axes)):\n raise ValueError('Must specify %s unique axes' % self._AXIS_LEN)\n\n new_axes = self._construct_axes_dict_from(\n self, [self._get_axis(x) for x in axes_names])\n new_values = self.values.transpose(axes_numbers)\n if kwargs.get('copy') or (len(args) and args[-1]):\n new_values = new_values.copy()\n return self._constructor(new_values, **new_axes).__finalize__(self)\n\n def swapaxes(self, axis1, axis2, copy=True):\n \"\"\"\n Interchange axes and swap values axes appropriately\n\n Returns\n -------\n y : same as input\n \"\"\"\n i = self._get_axis_number(axis1)\n j = self._get_axis_number(axis2)\n\n if i == j:\n if copy:\n return self.copy()\n return self\n\n mapping = {i: j, j: i}\n\n new_axes = (self._get_axis(mapping.get(k, k))\n for k in range(self._AXIS_LEN))\n new_values = self.values.swapaxes(i, j)\n if copy:\n new_values = new_values.copy()\n\n return self._constructor(new_values, *new_axes).__finalize__(self)\n\n def pop(self, item):\n \"\"\"\n Return item and drop from frame. Raise KeyError if not found.\n \"\"\"\n result = self[item]\n del self[item]\n return result\n\n def squeeze(self):\n \"\"\" squeeze length 1 dimensions \"\"\"\n try:\n return self.ix[tuple([slice(None) if len(a) > 1 else a[0]\n for a in self.axes])]\n except:\n return self\n\n def swaplevel(self, i, j, axis=0):\n \"\"\"\n Swap levels i and j in a MultiIndex on a particular axis\n\n Parameters\n ----------\n i, j : int, string (can be mixed)\n Level of index to be swapped. Can pass level name as string.\n\n Returns\n -------\n swapped : type of caller (new object)\n \"\"\"\n axis = self._get_axis_number(axis)\n result = self.copy()\n labels = result._data.axes[axis]\n result._data.set_axis(axis, labels.swaplevel(i, j))\n return result\n\n #----------------------------------------------------------------------\n # Rename\n\n # TODO: define separate funcs for DataFrame, Series and Panel so you can\n # get completion on keyword arguments.\n _shared_docs['rename'] = \"\"\"\n Alter axes input function or functions. Function / dict values must be\n unique (1-to-1). Labels not contained in a dict / Series will be left\n as-is.\n\n Parameters\n ----------\n %(axes)s : dict-like or function, optional\n Transformation to apply to that axis values\n\n copy : boolean, default True\n Also copy underlying data\n inplace : boolean, default False\n Whether to return a new %(klass)s. If True then value of copy is\n ignored.\n\n Returns\n -------\n renamed : %(klass)s (new object)\n \"\"\"\n\n @Appender(_shared_docs['rename'] % dict(axes='axes keywords for this'\n ' object', klass='NDFrame'))\n def rename(self, *args, **kwargs):\n\n axes, kwargs = self._construct_axes_from_arguments(args, kwargs)\n copy = kwargs.get('copy', True)\n inplace = kwargs.get('inplace', False)\n\n if (com._count_not_none(*axes.values()) == 0):\n raise TypeError('must pass an index to rename')\n\n # renamer function if passed a dict\n def _get_rename_function(mapper):\n if isinstance(mapper, (dict, ABCSeries)):\n def f(x):\n if x in mapper:\n return mapper[x]\n else:\n return x\n else:\n f = mapper\n\n return f\n\n self._consolidate_inplace()\n result = self if inplace else self.copy(deep=copy)\n\n # start in the axis order to eliminate too many copies\n for axis in lrange(self._AXIS_LEN):\n v = axes.get(self._AXIS_NAMES[axis])\n if v is None:\n continue\n f = _get_rename_function(v)\n\n baxis = self._get_block_manager_axis(axis)\n result._data = result._data.rename(f, axis=baxis, copy=copy)\n result._clear_item_cache()\n\n if inplace:\n self._update_inplace(result._data)\n else:\n return result.__finalize__(self)\n\n rename.__doc__ = _shared_docs['rename']\n\n def rename_axis(self, mapper, axis=0, copy=True, inplace=False):\n \"\"\"\n Alter index and / or columns using input function or functions.\n Function / dict values must be unique (1-to-1). Labels not contained in\n a dict / Series will be left as-is.\n\n Parameters\n ----------\n mapper : dict-like or function, optional\n axis : int or string, default 0\n copy : boolean, default True\n Also copy underlying data\n inplace : boolean, default False\n\n Returns\n -------\n renamed : type of caller\n \"\"\"\n axis = self._get_axis_name(axis)\n d = {'copy': copy, 'inplace': inplace}\n d[axis] = mapper\n return self.rename(**d)\n\n #----------------------------------------------------------------------\n # Comparisons\n\n def _indexed_same(self, other):\n return all([self._get_axis(a).equals(other._get_axis(a))\n for a in self._AXIS_ORDERS])\n\n def __neg__(self):\n arr = operator.neg(_values_from_object(self))\n return self._wrap_array(arr, self.axes, copy=False)\n\n def __invert__(self):\n arr = operator.inv(_values_from_object(self))\n return self._wrap_array(arr, self.axes, copy=False)\n\n def equals(self, other):\n \"\"\"\n Determines if two NDFrame objects contain the same elements. NaNs in the\n same location are considered equal.\n \"\"\"\n if not isinstance(other, self._constructor):\n return False\n return self._data.equals(other._data)\n\n #----------------------------------------------------------------------\n # Iteration\n\n def __hash__(self):\n raise TypeError('{0!r} objects are mutable, thus they cannot be'\n ' hashed'.format(self.__class__.__name__))\n\n def __iter__(self):\n \"\"\"\n Iterate over infor axis\n \"\"\"\n return iter(self._info_axis)\n\n # can we get a better explanation of this?\n def keys(self):\n \"\"\"Get the 'info axis' (see Indexing for more)\n\n This is index for Series, columns for DataFrame and major_axis for\n Panel.\"\"\"\n return self._info_axis\n\n def iteritems(self):\n \"\"\"Iterate over (label, values) on info axis\n\n This is index for Series, columns for DataFrame, major_axis for Panel,\n and so on.\n \"\"\"\n for h in self._info_axis:\n yield h, self[h]\n\n # originally used to get around 2to3's changes to iteritems.\n # Now unnecessary. Sidenote: don't want to deprecate this for a while,\n # otherwise libraries that use 2to3 will have issues.\n def iterkv(self, *args, **kwargs):\n \"iteritems alias used to get around 2to3. Deprecated\"\n warnings.warn(\"iterkv is deprecated and will be removed in a future \"\n \"release, use ``iteritems`` instead.\",\n DeprecationWarning)\n return self.iteritems(*args, **kwargs)\n\n def __len__(self):\n \"\"\"Returns length of info axis \"\"\"\n return len(self._info_axis)\n\n def __contains__(self, key):\n \"\"\"True if the key is in the info axis \"\"\"\n return key in self._info_axis\n\n @property\n def empty(self):\n \"True if NDFrame is entirely empty [no items]\"\n return not all(len(self._get_axis(a)) > 0 for a in self._AXIS_ORDERS)\n\n def __nonzero__(self):\n raise ValueError(\"The truth value of a {0} is ambiguous. \"\n \"Use a.empty, a.bool(), a.item(), a.any() or a.all().\"\n .format(self.__class__.__name__))\n\n __bool__ = __nonzero__\n\n def bool(self):\n \"\"\" Return the bool of a single element PandasObject\n This must be a boolean scalar value, either True or False\n\n Raise a ValueError if the PandasObject does not have exactly\n 1 element, or that element is not boolean \"\"\"\n v = self.squeeze()\n if isinstance(v, (bool, np.bool_)):\n return bool(v)\n elif np.isscalar(v):\n raise ValueError(\"bool cannot act on a non-boolean single element \"\n \"{0}\".format(self.__class__.__name__))\n\n self.__nonzero__()\n\n def __abs__(self):\n return self.abs()\n\n #----------------------------------------------------------------------\n # Array Interface\n\n def _wrap_array(self, arr, axes, copy=False):\n d = self._construct_axes_dict_from(self, axes, copy=copy)\n return self._constructor(arr, **d).__finalize__(self)\n\n def __array__(self, dtype=None):\n return _values_from_object(self)\n\n def __array_wrap__(self, result):\n d = self._construct_axes_dict(self._AXIS_ORDERS, copy=False)\n return self._constructor(result, **d).__finalize__(self)\n\n # ideally we would define this to avoid the getattr checks, but\n # is slower\n #@property\n #def __array_interface__(self):\n # \"\"\" provide numpy array interface method \"\"\"\n # values = self.values\n # return dict(typestr=values.dtype.str,shape=values.shape,data=values)\n\n def to_dense(self):\n \"Return dense representation of NDFrame (as opposed to sparse)\"\n # compat\n return self\n\n #----------------------------------------------------------------------\n # Picklability\n\n def __getstate__(self):\n return self._data\n\n def __setstate__(self, state):\n\n if isinstance(state, BlockManager):\n self._data = state\n elif isinstance(state, dict):\n typ = state.get('_typ')\n if typ is not None:\n\n # set in the order of internal names\n # to avoid definitional recursion\n # e.g. say fill_value needing _data to be\n # defined\n meta = set(self._internal_names + self._metadata)\n for k in list(meta):\n if k in state:\n v = state[k]\n object.__setattr__(self, k, v)\n\n for k, v in state.items():\n if k not in meta:\n object.__setattr__(self, k, v)\n\n else:\n self._unpickle_series_compat(state)\n elif isinstance(state[0], dict):\n if len(state) == 5:\n self._unpickle_sparse_frame_compat(state)\n else:\n self._unpickle_frame_compat(state)\n elif len(state) == 4:\n self._unpickle_panel_compat(state)\n elif len(state) == 2:\n self._unpickle_series_compat(state)\n else: # pragma: no cover\n # old pickling format, for compatibility\n self._unpickle_matrix_compat(state)\n\n self._item_cache = {}\n\n #----------------------------------------------------------------------\n # IO\n\n #----------------------------------------------------------------------\n # I/O Methods\n\n def to_json(self, path_or_buf=None, orient=None, date_format='epoch',\n double_precision=10, force_ascii=True, date_unit='ms',\n default_handler=None):\n \"\"\"\n Convert the object to a JSON string.\n\n Note NaN's and None will be converted to null and datetime objects\n will be converted to UNIX timestamps.\n\n Parameters\n ----------\n path_or_buf : the path or buffer to write the result string\n if this is None, return a StringIO of the converted string\n orient : string\n\n * Series\n\n - default is 'index'\n - allowed values are: {'split','records','index'}\n\n * DataFrame\n\n - default is 'columns'\n - allowed values are:\n {'split','records','index','columns','values'}\n\n * The format of the JSON string\n\n - split : dict like\n {index -> [index], columns -> [columns], data -> [values]}\n - records : list like\n [{column -> value}, ... , {column -> value}]\n - index : dict like {index -> {column -> value}}\n - columns : dict like {column -> {index -> value}}\n - values : just the values array\n\n date_format : {'epoch', 'iso'}\n Type of date conversion. `epoch` = epoch milliseconds,\n `iso`` = ISO8601, default is epoch.\n double_precision : The number of decimal places to use when encoding\n floating point values, default 10.\n force_ascii : force encoded string to be ASCII, default True.\n date_unit : string, default 'ms' (milliseconds)\n The time unit to encode to, governs timestamp and ISO8601\n precision. One of 's', 'ms', 'us', 'ns' for second, millisecond,\n microsecond, and nanosecond respectively.\n default_handler : callable, default None\n Handler to call if object cannot otherwise be converted to a\n suitable format for JSON. Should receive a single argument which is\n the object to convert and return a serialisable object.\n\n Returns\n -------\n same type as input object with filtered info axis\n\n \"\"\"\n\n from pandas.io import json\n return json.to_json(\n path_or_buf=path_or_buf,\n obj=self, orient=orient,\n date_format=date_format,\n double_precision=double_precision,\n force_ascii=force_ascii,\n date_unit=date_unit,\n default_handler=default_handler)\n\n def to_hdf(self, path_or_buf, key, **kwargs):\n \"\"\" activate the HDFStore\n\n Parameters\n ----------\n path_or_buf : the path (string) or buffer to put the store\n key : string\n indentifier for the group in the store\n mode : optional, {'a', 'w', 'r', 'r+'}, default 'a'\n\n ``'r'``\n Read-only; no data can be modified.\n ``'w'``\n Write; a new file is created (an existing file with the same\n name would be deleted).\n ``'a'``\n Append; an existing file is opened for reading and writing,\n and if the file does not exist it is created.\n ``'r+'``\n It is similar to ``'a'``, but the file must already exist.\n format : 'fixed(f)|table(t)', default is 'fixed'\n fixed(f) : Fixed format\n Fast writing/reading. Not-appendable, nor searchable\n table(t) : Table format\n Write as a PyTables Table structure which may perform\n worse but allow more flexible operations like searching\n / selecting subsets of the data\n append : boolean, default False\n For Table formats, append the input data to the existing\n complevel : int, 1-9, default 0\n If a complib is specified compression will be applied\n where possible\n complib : {'zlib', 'bzip2', 'lzo', 'blosc', None}, default None\n If complevel is > 0 apply compression to objects written\n in the store wherever possible\n fletcher32 : bool, default False\n If applying compression use the fletcher32 checksum\n\n \"\"\"\n\n from pandas.io import pytables\n return pytables.to_hdf(path_or_buf, key, self, **kwargs)\n\n def to_msgpack(self, path_or_buf=None, **kwargs):\n \"\"\"\n msgpack (serialize) object to input file path\n\n THIS IS AN EXPERIMENTAL LIBRARY and the storage format\n may not be stable until a future release.\n\n Parameters\n ----------\n path : string File path, buffer-like, or None\n if None, return generated string\n append : boolean whether to append to an existing msgpack\n (default is False)\n compress : type of compressor (zlib or blosc), default to None (no\n compression)\n \"\"\"\n\n from pandas.io import packers\n return packers.to_msgpack(path_or_buf, self, **kwargs)\n\n def to_pickle(self, path):\n \"\"\"\n Pickle (serialize) object to input file path\n\n Parameters\n ----------\n path : string\n File path\n \"\"\"\n from pandas.io.pickle import to_pickle\n return to_pickle(self, path)\n\n def save(self, path): # TODO remove in 0.14\n \"Deprecated. Use to_pickle instead\"\n import warnings\n from pandas.io.pickle import to_pickle\n warnings.warn(\"save is deprecated, use to_pickle\", FutureWarning)\n return to_pickle(self, path)\n\n def load(self, path): # TODO remove in 0.14\n \"Deprecated. Use read_pickle instead.\"\n import warnings\n from pandas.io.pickle import read_pickle\n warnings.warn(\"load is deprecated, use pd.read_pickle\", FutureWarning)\n return read_pickle(path)\n\n def to_clipboard(self, excel=None, sep=None, **kwargs):\n \"\"\"\n Attempt to write text representation of object to the system clipboard\n This can be pasted into Excel, for example.\n\n Parameters\n ----------\n excel : boolean, defaults to True\n if True, use the provided separator, writing in a csv\n format for allowing easy pasting into excel.\n if False, write a string representation of the object\n to the clipboard\n sep : optional, defaults to tab\n other keywords are passed to to_csv\n\n Notes\n -----\n Requirements for your platform\n - Linux: xclip, or xsel (with gtk or PyQt4 modules)\n - Windows: none\n - OS X: none\n \"\"\"\n from pandas.io import clipboard\n clipboard.to_clipboard(self, excel=excel, sep=sep, **kwargs)\n\n #----------------------------------------------------------------------\n # Fancy Indexing\n\n @classmethod\n def _create_indexer(cls, name, indexer):\n \"\"\" create an indexer like _name in the class \"\"\"\n\n if getattr(cls, name, None) is None:\n iname = '_%s' % name\n setattr(cls, iname, None)\n\n def _indexer(self):\n i = getattr(self, iname)\n if i is None:\n i = indexer(self, name)\n setattr(self, iname, i)\n return i\n\n setattr(cls, name, property(_indexer))\n\n # add to our internal names set\n cls._internal_names_set.add(iname)\n\n def get(self, key, default=None):\n \"\"\"\n Get item from object for given key (DataFrame column, Panel slice,\n etc.). Returns default value if not found\n\n Parameters\n ----------\n key : object\n\n Returns\n -------\n value : type of items contained in object\n \"\"\"\n try:\n return self[key]\n except (KeyError, ValueError):\n return default\n\n def __getitem__(self, item):\n return self._get_item_cache(item)\n\n def _get_item_cache(self, item):\n cache = self._item_cache\n res = cache.get(item)\n if res is None:\n values = self._data.get(item)\n res = self._box_item_values(item, values)\n cache[item] = res\n res._set_as_cached(item, self)\n\n # for a chain\n res.is_copy = self.is_copy\n return res\n\n def _set_as_cached(self, item, cacher):\n \"\"\" set the _cacher attribute on the calling object with\n a weakref to cacher \"\"\"\n self._cacher = (item, weakref.ref(cacher))\n\n def _box_item_values(self, key, values):\n raise NotImplementedError\n\n def _maybe_cache_changed(self, item, value):\n \"\"\"\n the object has called back to us saying\n maybe it has changed\n\n numpy < 1.8 has an issue with object arrays and aliasing\n GH6026\n \"\"\"\n self._data.set(item, value, check=pd._np_version_under1p8)\n\n @property\n def _is_cached(self):\n \"\"\" boolean : return if I am cached \"\"\"\n cacher = getattr(self, '_cacher', None)\n return cacher is not None\n\n def _maybe_update_cacher(self, clear=False):\n \"\"\" see if we need to update our parent cacher\n if clear, then clear our cache \"\"\"\n cacher = getattr(self, '_cacher', None)\n if cacher is not None:\n ref = cacher[1]()\n\n # we are trying to reference a dead referant, hence\n # a copy\n if ref is None:\n del self._cacher\n else:\n try:\n ref._maybe_cache_changed(cacher[0], self)\n except:\n pass\n\n # check if we are a copy\n self._check_setitem_copy(stacklevel=5, t='referant')\n\n if clear:\n self._clear_item_cache()\n\n def _clear_item_cache(self, i=None):\n if i is not None:\n self._item_cache.pop(i, None)\n else:\n self._item_cache.clear()\n\n def _set_item(self, key, value):\n self._data.set(key, value)\n self._clear_item_cache()\n\n def _set_is_copy(self, ref=None, copy=True):\n if not copy:\n self.is_copy = None\n else:\n if ref is not None:\n self.is_copy = weakref.ref(ref)\n else:\n self.is_copy = None\n\n def _check_setitem_copy(self, stacklevel=4, t='setting'):\n \"\"\" validate if we are doing a settitem on a chained copy.\n\n If you call this function, be sure to set the stacklevel such that the\n user will see the error *at the level of setting*\"\"\"\n if self.is_copy:\n\n value = config.get_option('mode.chained_assignment')\n if value is None:\n return\n\n # see if the copy is not actually refererd; if so, then disolve\n # the copy weakref\n try:\n gc.collect(2)\n if not gc.get_referents(self.is_copy()):\n self.is_copy = None\n return\n except:\n pass\n\n if t == 'referant':\n t = (\"A value is trying to be set on a copy of a slice from a \"\n \"DataFrame\")\n else:\n t = (\"A value is trying to be set on a copy of a slice from a \"\n \"DataFrame.\\nTry using .loc[row_index,col_indexer] = value \"\n \"instead\")\n if value == 'raise':\n raise SettingWithCopyError(t)\n elif value == 'warn':\n warnings.warn(t, SettingWithCopyWarning, stacklevel=stacklevel)\n\n def __delitem__(self, key):\n \"\"\"\n Delete item\n \"\"\"\n deleted = False\n\n maybe_shortcut = False\n if hasattr(self, 'columns') and isinstance(self.columns, MultiIndex):\n try:\n maybe_shortcut = key not in self.columns._engine\n except TypeError:\n pass\n\n if maybe_shortcut:\n # Allow shorthand to delete all columns whose first len(key)\n # elements match key:\n if not isinstance(key, tuple):\n key = (key,)\n for col in self.columns:\n if isinstance(col, tuple) and col[:len(key)] == key:\n del self[col]\n deleted = True\n if not deleted:\n # If the above loop ran and didn't delete anything because\n # there was no match, this call should raise the appropriate\n # exception:\n self._data.delete(key)\n\n try:\n del self._item_cache[key]\n except KeyError:\n pass\n\n def take(self, indices, axis=0, convert=True, is_copy=True):\n \"\"\"\n Analogous to ndarray.take\n\n Parameters\n ----------\n indices : list / array of ints\n axis : int, default 0\n convert : translate neg to pos indices (default)\n is_copy : mark the returned frame as a copy\n\n Returns\n -------\n taken : type of caller\n \"\"\"\n\n # check/convert indicies here\n if convert:\n axis = self._get_axis_number(axis)\n indices = _maybe_convert_indices(\n indices, len(self._get_axis(axis)))\n\n baxis = self._get_block_manager_axis(axis)\n if baxis == 0:\n labels = self._get_axis(axis)\n new_items = labels.take(indices)\n new_data = self._data.reindex_axis(new_items, indexer=indices,\n axis=baxis)\n else:\n new_data = self._data.take(indices, axis=baxis)\n\n result = self._constructor(new_data).__finalize__(self)\n\n # maybe set copy if we didn't actually change the index\n if is_copy and not result._get_axis(axis).equals(self._get_axis(axis)):\n result._set_is_copy(self)\n\n return result\n\n def xs(self, key, axis=0, level=None, copy=True, drop_level=True):\n \"\"\"\n Returns a cross-section (row(s) or column(s)) from the Series/DataFrame.\n Defaults to cross-section on the rows (axis=0).\n\n Parameters\n ----------\n key : object\n Some label contained in the index, or partially in a MultiIndex\n axis : int, default 0\n Axis to retrieve cross-section on\n level : object, defaults to first n levels (n=1 or len(key))\n In case of a key partially contained in a MultiIndex, indicate\n which levels are used. Levels can be referred by label or position.\n copy : boolean, default True\n Whether to make a copy of the data\n drop_level : boolean, default True\n If False, returns object with same levels as self.\n\n Examples\n --------\n >>> df\n A B C\n a 4 5 2\n b 4 0 9\n c 9 7 3\n >>> df.xs('a')\n A 4\n B 5\n C 2\n Name: a\n >>> df.xs('C', axis=1)\n a 2\n b 9\n c 3\n Name: C\n >>> s = df.xs('a', copy=False)\n >>> s['A'] = 100\n >>> df\n A B C\n a 100 5 2\n b 4 0 9\n c 9 7 3\n\n\n >>> df\n A B C D\n first second third\n bar one 1 4 1 8 9\n two 1 7 5 5 0\n baz one 1 6 6 8 0\n three 2 5 3 5 3\n >>> df.xs(('baz', 'three'))\n A B C D\n third\n 2 5 3 5 3\n >>> df.xs('one', level=1)\n A B C D\n first third\n bar 1 4 1 8 9\n baz 1 6 6 8 0\n >>> df.xs(('baz', 2), level=[0, 'third'])\n A B C D\n second\n three 5 3 5 3\n\n Returns\n -------\n xs : Series or DataFrame\n\n \"\"\"\n axis = self._get_axis_number(axis)\n labels = self._get_axis(axis)\n if level is not None:\n loc, new_ax = labels.get_loc_level(key, level=level,\n drop_level=drop_level)\n\n if not copy and not isinstance(loc, slice):\n raise ValueError('Cannot retrieve view (copy=False)')\n\n # convert to a label indexer if needed\n if isinstance(loc, slice):\n lev_num = labels._get_level_number(level)\n if labels.levels[lev_num].inferred_type == 'integer':\n loc = labels[loc]\n\n # create the tuple of the indexer\n indexer = [slice(None)] * self.ndim\n indexer[axis] = loc\n indexer = tuple(indexer)\n\n result = self.ix[indexer]\n setattr(result, result._get_axis_name(axis), new_ax)\n return result\n\n if axis == 1:\n data = self[key]\n if copy:\n data = data.copy()\n return data\n\n self._consolidate_inplace()\n\n index = self.index\n if isinstance(index, MultiIndex):\n loc, new_index = self.index.get_loc_level(key,\n drop_level=drop_level)\n else:\n loc = self.index.get_loc(key)\n\n if isinstance(loc, np.ndarray):\n if loc.dtype == np.bool_:\n inds, = loc.nonzero()\n return self.take(inds, axis=axis, convert=False)\n else:\n return self.take(loc, axis=axis, convert=True)\n\n if not np.isscalar(loc):\n new_index = self.index[loc]\n\n if np.isscalar(loc):\n from pandas import Series\n new_values, copy = self._data.fast_2d_xs(loc, copy=copy)\n result = Series(new_values, index=self.columns,\n name=self.index[loc])\n\n else:\n result = self[loc]\n result.index = new_index\n\n result._set_is_copy(self)\n return result\n\n _xs = xs\n\n # TODO: Check if this was clearer in 0.12\n def select(self, crit, axis=0):\n \"\"\"\n Return data corresponding to axis labels matching criteria\n\n Parameters\n ----------\n crit : function\n To be called on each index (label). Should return True or False\n axis : int\n\n Returns\n -------\n selection : type of caller\n \"\"\"\n axis = self._get_axis_number(axis)\n axis_name = self._get_axis_name(axis)\n axis_values = self._get_axis(axis)\n\n if len(axis_values) > 0:\n new_axis = axis_values[\n np.asarray([bool(crit(label)) for label in axis_values])]\n else:\n new_axis = axis_values\n\n return self.reindex(**{axis_name: new_axis})\n\n def reindex_like(self, other, method=None, copy=True, limit=None):\n \"\"\" return an object with matching indicies to myself\n\n Parameters\n ----------\n other : Object\n method : string or None\n copy : boolean, default True\n limit : int, default None\n Maximum size gap to forward or backward fill\n\n Notes\n -----\n Like calling s.reindex(index=other.index, columns=other.columns,\n method=...)\n\n Returns\n -------\n reindexed : same as input\n \"\"\"\n d = other._construct_axes_dict(method=method)\n return self.reindex(**d)\n\n def drop(self, labels, axis=0, level=None, inplace=False, **kwargs):\n \"\"\"\n Return new object with labels in requested axis removed\n\n Parameters\n ----------\n labels : single label or list-like\n axis : int or axis name\n level : int or name, default None\n For MultiIndex\n inplace : bool, default False\n If True, do operation inplace and return None.\n\n Returns\n -------\n dropped : type of caller\n \"\"\"\n axis = self._get_axis_number(axis)\n axis_name = self._get_axis_name(axis)\n axis, axis_ = self._get_axis(axis), axis\n\n if axis.is_unique:\n if level is not None:\n if not isinstance(axis, MultiIndex):\n raise AssertionError('axis must be a MultiIndex')\n new_axis = axis.drop(labels, level=level)\n else:\n new_axis = axis.drop(labels)\n dropped = self.reindex(**{axis_name: new_axis})\n try:\n dropped.axes[axis_].set_names(axis.names, inplace=True)\n except AttributeError:\n pass\n result = dropped\n\n else:\n labels = com._index_labels_to_array(labels)\n if level is not None:\n if not isinstance(axis, MultiIndex):\n raise AssertionError('axis must be a MultiIndex')\n indexer = -lib.ismember(axis.get_level_values(level),\n set(labels))\n else:\n indexer = -axis.isin(labels)\n\n slicer = [slice(None)] * self.ndim\n slicer[self._get_axis_number(axis_name)] = indexer\n\n result = self.ix[tuple(slicer)]\n\n if inplace:\n self._update_inplace(result)\n else:\n return result\n\n def _update_inplace(self, result):\n \"replace self internals with result.\"\n # NOTE: This does *not* call __finalize__ and that's an explicit\n # decision that we may revisit in the future.\n self._reset_cache()\n self._clear_item_cache()\n self._data = getattr(result,'_data',result)\n self._maybe_update_cacher()\n\n def add_prefix(self, prefix):\n \"\"\"\n Concatenate prefix string with panel items names.\n\n Parameters\n ----------\n prefix : string\n\n Returns\n -------\n with_prefix : type of caller\n \"\"\"\n new_data = self._data.add_prefix(prefix)\n return self._constructor(new_data).__finalize__(self)\n\n def add_suffix(self, suffix):\n \"\"\"\n Concatenate suffix string with panel items names\n\n Parameters\n ----------\n suffix : string\n\n Returns\n -------\n with_suffix : type of caller\n \"\"\"\n new_data = self._data.add_suffix(suffix)\n return self._constructor(new_data).__finalize__(self)\n\n def sort_index(self, axis=0, ascending=True):\n \"\"\"\n Sort object by labels (along an axis)\n\n Parameters\n ----------\n axis : {0, 1}\n Sort index/rows versus columns\n ascending : boolean, default True\n Sort ascending vs. descending\n\n Returns\n -------\n sorted_obj : type of caller\n \"\"\"\n axis = self._get_axis_number(axis)\n axis_name = self._get_axis_name(axis)\n labels = self._get_axis(axis)\n\n sort_index = labels.argsort()\n if not ascending:\n sort_index = sort_index[::-1]\n\n new_axis = labels.take(sort_index)\n return self.reindex(**{axis_name: new_axis})\n _shared_docs['reindex'] = \"\"\"\n Conform %(klass)s to new index with optional filling logic, placing\n NA/NaN in locations having no value in the previous index. A new object\n is produced unless the new index is equivalent to the current one and\n copy=False\n\n Parameters\n ----------\n %(axes)s : array-like, optional (can be specified in order, or as\n keywords)\n New labels / index to conform to. Preferably an Index object to\n avoid duplicating data\n method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None\n Method to use for filling holes in reindexed DataFrame\n pad / ffill: propagate last valid observation forward to next valid\n backfill / bfill: use NEXT valid observation to fill gap\n copy : boolean, default True\n Return a new object, even if the passed indexes are the same\n level : int or name\n Broadcast across a level, matching Index values on the\n passed MultiIndex level\n fill_value : scalar, default np.NaN\n Value to use for missing values. Defaults to NaN, but can be any\n \"compatible\" value\n limit : int, default None\n Maximum size gap to forward or backward fill\n takeable : boolean, default False\n treat the passed as positional values\n\n Examples\n --------\n >>> df.reindex(index=[date1, date2, date3], columns=['A', 'B', 'C'])\n\n Returns\n -------\n reindexed : %(klass)s\n \"\"\"\n # TODO: Decide if we care about having different examples for different\n # kinds\n\n @Appender(_shared_docs['reindex'] % dict(axes=\"axes\", klass=\"NDFrame\"))\n def reindex(self, *args, **kwargs):\n\n # construct the args\n axes, kwargs = self._construct_axes_from_arguments(args, kwargs)\n method = com._clean_fill_method(kwargs.get('method'))\n level = kwargs.get('level')\n copy = kwargs.get('copy', True)\n limit = kwargs.get('limit')\n fill_value = kwargs.get('fill_value', np.nan)\n takeable = kwargs.get('takeable', False)\n\n self._consolidate_inplace()\n\n # check if we are a multi reindex\n if self._needs_reindex_multi(axes, method, level):\n try:\n return self._reindex_multi(axes, copy, fill_value)\n except:\n pass\n\n # if all axes that are requested to reindex are equal, then only copy\n # if indicated must have index names equal here as well as values\n if all([self._get_axis(axis).identical(ax)\n for axis, ax in axes.items() if ax is not None]):\n if copy:\n return self.copy()\n return self\n\n # perform the reindex on the axes\n return self._reindex_axes(axes, level, limit,\n method, fill_value, copy,\n takeable=takeable).__finalize__(self)\n\n def _reindex_axes(self, axes, level, limit, method, fill_value, copy,\n takeable=False):\n \"\"\" perform the reinxed for all the axes \"\"\"\n obj = self\n for a in self._AXIS_ORDERS:\n labels = axes[a]\n if labels is None:\n continue\n\n # convert to an index if we are not a multi-selection\n if level is None:\n labels = _ensure_index(labels)\n\n axis = self._get_axis_number(a)\n ax = self._get_axis(a)\n try:\n new_index, indexer = ax.reindex(\n labels, level=level, limit=limit, method=method,\n takeable=takeable)\n except (ValueError):\n\n # catch trying to reindex a non-monotonic index with a\n # specialized indexer e.g. pad, so fallback to the regular\n # indexer this will show up on reindexing a not-naturally\n # ordering series,\n # e.g.\n # Series(\n # [1,2,3,4], index=['a','b','c','d']\n # ).reindex(['c','b','g'], method='pad')\n new_index, indexer = ax.reindex(\n labels, level=level, limit=limit, method=None,\n takeable=takeable)\n\n obj = obj._reindex_with_indexers(\n {axis: [new_index, indexer]}, method=method,\n fill_value=fill_value, limit=limit, copy=copy)\n\n return obj\n\n def _needs_reindex_multi(self, axes, method, level):\n \"\"\" check if we do need a multi reindex \"\"\"\n return ((com._count_not_none(*axes.values()) == self._AXIS_LEN) and\n method is None and level is None and not self._is_mixed_type)\n\n def _reindex_multi(self, axes, copy, fill_value):\n return NotImplemented\n\n _shared_docs['reindex_axis'] = (\n \"\"\"Conform input object to new index with optional filling logic,\n placing NA/NaN in locations having no value in the previous index. A\n new object is produced unless the new index is equivalent to the\n current one and copy=False\n\n Parameters\n ----------\n index : array-like, optional\n New labels / index to conform to. Preferably an Index object to\n avoid duplicating data\n axis : %(axes_single_arg)s\n method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None\n Method to use for filling holes in reindexed object.\n pad / ffill: propagate last valid observation forward to next valid\n backfill / bfill: use NEXT valid observation to fill gap\n copy : boolean, default True\n Return a new object, even if the passed indexes are the same\n level : int or name\n Broadcast across a level, matching Index values on the\n passed MultiIndex level\n limit : int, default None\n Maximum size gap to forward or backward fill\n\n Examples\n --------\n >>> df.reindex_axis(['A', 'B', 'C'], axis=1)\n\n See also\n --------\n reindex, reindex_like\n\n Returns\n -------\n reindexed : %(klass)s\n \"\"\")\n\n @Appender(_shared_docs['reindex_axis'] % _shared_doc_kwargs)\n def reindex_axis(self, labels, axis=0, method=None, level=None, copy=True,\n limit=None, fill_value=np.nan):\n self._consolidate_inplace()\n\n axis_name = self._get_axis_name(axis)\n axis_values = self._get_axis(axis_name)\n method = com._clean_fill_method(method)\n new_index, indexer = axis_values.reindex(\n labels, method, level, limit=limit, copy_if_needed=True)\n return self._reindex_with_indexers(\n {axis: [new_index, indexer]}, method=method, fill_value=fill_value,\n limit=limit, copy=copy).__finalize__(self)\n\n def _reindex_with_indexers(self, reindexers, method=None,\n fill_value=np.nan, limit=None, copy=False,\n allow_dups=False):\n \"\"\" allow_dups indicates an internal call here \"\"\"\n\n # reindex doing multiple operations on different axes if indiciated\n new_data = self._data\n for axis in sorted(reindexers.keys()):\n index, indexer = reindexers[axis]\n baxis = self._get_block_manager_axis(axis)\n\n if index is None:\n continue\n index = _ensure_index(index)\n\n # reindex the axis\n if method is not None:\n new_data = new_data.reindex_axis(\n index, indexer=indexer, method=method, axis=baxis,\n fill_value=fill_value, limit=limit, copy=copy)\n\n elif indexer is not None:\n # TODO: speed up on homogeneous DataFrame objects\n indexer = com._ensure_int64(indexer)\n new_data = new_data.reindex_indexer(index, indexer, axis=baxis,\n fill_value=fill_value,\n allow_dups=allow_dups)\n\n elif (baxis == 0 and index is not None and\n index is not new_data.axes[baxis]):\n new_data = new_data.reindex_items(index, copy=copy,\n fill_value=fill_value)\n\n elif (baxis > 0 and index is not None and\n index is not new_data.axes[baxis]):\n new_data = new_data.copy(deep=copy)\n new_data.set_axis(baxis, index)\n\n if copy and new_data is self._data:\n new_data = new_data.copy()\n\n return self._constructor(new_data).__finalize__(self)\n\n def _reindex_axis(self, new_index, fill_method, axis, copy):\n new_data = self._data.reindex_axis(new_index, axis=axis,\n method=fill_method, copy=copy)\n\n if new_data is self._data and not copy:\n return self\n else:\n return self._constructor(new_data).__finalize__(self)\n\n def filter(self, items=None, like=None, regex=None, axis=None):\n \"\"\"\n Restrict the info axis to set of items or wildcard\n\n Parameters\n ----------\n items : list-like\n List of info axis to restrict to (must not all be present)\n like : string\n Keep info axis where \"arg in col == True\"\n regex : string (regular expression)\n Keep info axis with re.search(regex, col) == True\n\n Notes\n -----\n Arguments are mutually exclusive, but this is not checked for\n\n \"\"\"\n import re\n\n if axis is None:\n axis = self._info_axis_name\n axis_name = self._get_axis_name(axis)\n axis_values = self._get_axis(axis_name)\n\n if items is not None:\n return self.reindex(**{axis_name: [r for r in items\n if r in axis_values]})\n elif like:\n matchf = lambda x: (like in x if isinstance(x, string_types)\n else like in str(x))\n return self.select(matchf, axis=axis_name)\n elif regex:\n matcher = re.compile(regex)\n return self.select(lambda x: matcher.search(x) is not None,\n axis=axis_name)\n else:\n raise TypeError('Must pass either `items`, `like`, or `regex`')\n\n def head(self, n=5):\n \"\"\"\n Returns first n rows\n \"\"\"\n l = len(self)\n if l == 0 or n==0:\n return self\n return self.iloc[:n]\n\n def tail(self, n=5):\n \"\"\"\n Returns last n rows\n \"\"\"\n l = len(self)\n if l == 0 or n == 0:\n return self\n return self.iloc[-n:]\n\n #----------------------------------------------------------------------\n # Attribute access\n\n def __finalize__(self, other, method=None, **kwargs):\n \"\"\"\n propagate metadata from other to self\n\n Parameters\n ----------\n other : the object from which to get the attributes that we are going\n to propagate\n method : optional, a passed method name ; possibly to take different\n types of propagation actions based on this\n\n \"\"\"\n for name in self._metadata:\n object.__setattr__(self, name, getattr(other, name, None))\n return self\n\n def __getattr__(self, name):\n \"\"\"After regular attribute access, try looking up the name of a the\n info.\n\n This allows simpler access to columns for interactive use.\n \"\"\"\n if name in self._internal_names_set:\n return object.__getattribute__(self, name)\n elif name in self._metadata:\n return object.__getattribute__(self, name)\n else:\n if name in self._info_axis:\n return self[name]\n raise AttributeError(\"'%s' object has no attribute '%s'\" %\n (type(self).__name__, name))\n\n def __setattr__(self, name, value):\n \"\"\"After regular attribute access, try looking up the name of the info\n This allows simpler access to columns for interactive use.\"\"\"\n if name in self._internal_names_set:\n object.__setattr__(self, name, value)\n elif name in self._metadata:\n return object.__setattr__(self, name, value)\n else:\n try:\n existing = getattr(self, name)\n if isinstance(existing, Index):\n object.__setattr__(self, name, value)\n elif name in self._info_axis:\n self[name] = value\n else:\n object.__setattr__(self, name, value)\n except (AttributeError, TypeError):\n object.__setattr__(self, name, value)\n\n #----------------------------------------------------------------------\n # Getting and setting elements\n\n #----------------------------------------------------------------------\n # Consolidation of internals\n\n def _consolidate_inplace(self):\n f = lambda: self._data.consolidate()\n self._data = self._protect_consolidate(f)\n\n def consolidate(self, inplace=False):\n \"\"\"\n Compute NDFrame with \"consolidated\" internals (data of each dtype\n grouped together in a single ndarray). Mainly an internal API function,\n but available here to the savvy user\n\n Parameters\n ----------\n inplace : boolean, default False\n If False return new object, otherwise modify existing object\n\n Returns\n -------\n consolidated : type of caller\n \"\"\"\n if inplace:\n self._consolidate_inplace()\n else:\n f = lambda: self._data.consolidate()\n cons_data = self._protect_consolidate(f)\n if cons_data is self._data:\n cons_data = cons_data.copy()\n return self._constructor(cons_data).__finalize__(self)\n\n @property\n def _is_mixed_type(self):\n f = lambda: self._data.is_mixed_type\n return self._protect_consolidate(f)\n\n @property\n def _is_numeric_mixed_type(self):\n f = lambda: self._data.is_numeric_mixed_type\n return self._protect_consolidate(f)\n\n @property\n def _is_datelike_mixed_type(self):\n f = lambda: self._data.is_datelike_mixed_type\n return self._protect_consolidate(f)\n\n def _protect_consolidate(self, f):\n blocks_before = len(self._data.blocks)\n result = f()\n if len(self._data.blocks) != blocks_before:\n self._clear_item_cache()\n return result\n\n def _get_numeric_data(self):\n return self._constructor(\n self._data.get_numeric_data()).__finalize__(self)\n\n def _get_bool_data(self):\n return self._constructor(self._data.get_bool_data()).__finalize__(self)\n\n #----------------------------------------------------------------------\n # Internal Interface Methods\n\n def as_matrix(self, columns=None):\n \"\"\"\n Convert the frame to its Numpy-array matrix representation. Columns\n are presented in sorted order unless a specific list of columns is\n provided.\n\n NOTE: the dtype will be a lower-common-denominator dtype (implicit\n upcasting) that is to say if the dtypes (even of numeric types)\n are mixed, the one that accommodates all will be chosen use this\n with care if you are not dealing with the blocks\n\n e.g. if the dtypes are float16,float32 -> float32\n float16,float32,float64 -> float64\n int32,uint8 -> int32\n\n\n Returns\n -------\n values : ndarray\n If the caller is heterogeneous and contains booleans or objects,\n the result will be of dtype=object\n \"\"\"\n self._consolidate_inplace()\n if self._AXIS_REVERSED:\n return self._data.as_matrix(columns).T\n return self._data.as_matrix(columns)\n\n @property\n def values(self):\n \"Numpy representation of NDFrame\"\n return self.as_matrix()\n\n @property\n def _get_values(self):\n # compat\n return self.as_matrix()\n\n def get_values(self):\n \"\"\" same as values (but handles sparseness conversions) \"\"\"\n return self.as_matrix()\n\n def get_dtype_counts(self):\n \"\"\" Return the counts of dtypes in this object \"\"\"\n from pandas import Series\n return Series(self._data.get_dtype_counts())\n\n def get_ftype_counts(self):\n \"\"\" Return the counts of ftypes in this object \"\"\"\n from pandas import Series\n return Series(self._data.get_ftype_counts())\n\n @property\n def dtypes(self):\n \"\"\" Return the dtypes in this object \"\"\"\n from pandas import Series\n return Series(self._data.get_dtypes(),index=self._info_axis)\n\n @property\n def ftypes(self):\n \"\"\"\n Return the ftypes (indication of sparse/dense and dtype)\n in this object.\n \"\"\"\n from pandas import Series\n return Series(self._data.get_ftypes(),index=self._info_axis)\n\n def as_blocks(self, columns=None):\n \"\"\"\n Convert the frame to a dict of dtype -> Constructor Types that each has\n a homogeneous dtype.\n\n are presented in sorted order unless a specific list of columns is\n provided.\n\n NOTE: the dtypes of the blocks WILL BE PRESERVED HERE (unlike in\n as_matrix)\n\n Parameters\n ----------\n columns : array-like\n Specific column order\n\n Returns\n -------\n values : a list of Object\n \"\"\"\n self._consolidate_inplace()\n\n bd = dict()\n for b in self._data.blocks:\n b = b.reindex_items_from(columns or b.items)\n bd[str(b.dtype)] = self._constructor(\n BlockManager([b], [b.items, self.index])).__finalize__(self)\n return bd\n\n @property\n def blocks(self):\n \"Internal property, property synonym for as_blocks()\"\n return self.as_blocks()\n\n def astype(self, dtype, copy=True, raise_on_error=True):\n \"\"\"\n Cast object to input numpy.dtype\n Return a copy when copy = True (be really careful with this!)\n\n Parameters\n ----------\n dtype : numpy.dtype or Python type\n raise_on_error : raise on invalid input\n\n Returns\n -------\n casted : type of caller\n \"\"\"\n\n mgr = self._data.astype(\n dtype=dtype, copy=copy, raise_on_error=raise_on_error)\n return self._constructor(mgr).__finalize__(self)\n\n def copy(self, deep=True):\n \"\"\"\n Make a copy of this object\n\n Parameters\n ----------\n deep : boolean, default True\n Make a deep copy, i.e. also copy data\n\n Returns\n -------\n copy : type of caller\n \"\"\"\n data = self._data\n if deep:\n data = data.copy()\n return self._constructor(data).__finalize__(self)\n\n def convert_objects(self, convert_dates=True, convert_numeric=False,\n convert_timedeltas=True, copy=True):\n \"\"\"\n Attempt to infer better dtype for object columns\n\n Parameters\n ----------\n convert_dates : if True, attempt to soft convert dates, if 'coerce',\n force conversion (and non-convertibles get NaT)\n convert_numeric : if True attempt to coerce to numbers (including\n strings), non-convertibles get NaN\n convert_timedeltas : if True, attempt to soft convert timedeltas, if 'coerce',\n force conversion (and non-convertibles get NaT)\n copy : Boolean, if True, return copy, default is True\n\n Returns\n -------\n converted : asm as input object\n \"\"\"\n return self._constructor(\n self._data.convert(convert_dates=convert_dates,\n convert_numeric=convert_numeric,\n convert_timedeltas=convert_timedeltas,\n copy=copy)).__finalize__(self)\n\n #----------------------------------------------------------------------\n # Filling NA's\n\n def fillna(self, value=None, method=None, axis=0, inplace=False,\n limit=None, downcast=None):\n \"\"\"\n Fill NA/NaN values using the specified method\n\n Parameters\n ----------\n method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None\n Method to use for filling holes in reindexed Series\n pad / ffill: propagate last valid observation forward to next valid\n backfill / bfill: use NEXT valid observation to fill gap\n value : scalar, dict, or Series\n Value to use to fill holes (e.g. 0), alternately a dict/Series of\n values specifying which value to use for each index (for a Series) or\n column (for a DataFrame). (values not in the dict/Series will not be\n filled). This value cannot be a list.\n axis : {0, 1}, default 0\n * 0: fill column-by-column\n * 1: fill row-by-row\n inplace : boolean, default False\n If True, fill in place. Note: this will modify any\n other views on this object, (e.g. a no-copy slice for a column in a\n DataFrame).\n limit : int, default None\n Maximum size gap to forward or backward fill\n downcast : dict, default is None\n a dict of item->dtype of what to downcast if possible,\n or the string 'infer' which will try to downcast to an appropriate\n equal type (e.g. float64 to int64 if possible)\n\n See also\n --------\n reindex, asfreq\n\n Returns\n -------\n filled : same type as caller\n \"\"\"\n if isinstance(value, (list, tuple)):\n raise TypeError('\"value\" parameter must be a scalar or dict, but '\n 'you passed a \"{0}\"'.format(type(value).__name__))\n self._consolidate_inplace()\n\n axis = self._get_axis_number(axis)\n method = com._clean_fill_method(method)\n\n if value is None:\n if method is None:\n raise ValueError('must specify a fill method or value')\n if self._is_mixed_type and axis == 1:\n if inplace:\n raise NotImplementedError()\n result = self.T.fillna(method=method, limit=limit).T\n\n # need to downcast here because of all of the transposes\n result._data = result._data.downcast()\n\n return result\n\n # > 3d\n if self.ndim > 3:\n raise NotImplementedError(\n 'Cannot fillna with a method for > 3dims'\n )\n\n # 3d\n elif self.ndim == 3:\n\n # fill in 2d chunks\n result = dict([(col, s.fillna(method=method, value=value))\n for col, s in compat.iteritems(self)])\n return self._constructor.from_dict(result).__finalize__(self)\n\n # 2d or less\n method = com._clean_fill_method(method)\n new_data = self._data.interpolate(method=method,\n axis=axis,\n limit=limit,\n inplace=inplace,\n coerce=True,\n downcast=downcast)\n else:\n if method is not None:\n raise ValueError('cannot specify both a fill method and value')\n\n if len(self._get_axis(axis)) == 0:\n return self\n\n if self.ndim == 1 and value is not None:\n if isinstance(value, (dict, com.ABCSeries)):\n from pandas import Series\n value = Series(value)\n\n new_data = self._data.fillna(value=value, inplace=inplace,\n downcast=downcast)\n\n elif isinstance(value, (dict, com.ABCSeries)):\n if axis == 1:\n raise NotImplementedError('Currently only can fill '\n 'with dict/Series column '\n 'by column')\n\n result = self if inplace else self.copy()\n for k, v in compat.iteritems(value):\n if k not in result:\n continue\n obj = result[k]\n obj.fillna(v, inplace=True)\n return result\n else:\n new_data = self._data.fillna(value=value, inplace=inplace,\n downcast=downcast)\n\n if inplace:\n self._update_inplace(new_data)\n else:\n return self._constructor(new_data).__finalize__(self)\n\n def ffill(self, axis=0, inplace=False, limit=None, downcast=None):\n \"Synonym for NDFrame.fillna(method='ffill')\"\n return self.fillna(method='ffill', axis=axis, inplace=inplace,\n limit=limit, downcast=downcast)\n\n def bfill(self, axis=0, inplace=False, limit=None, downcast=None):\n \"Synonym for NDFrame.fillna(method='bfill')\"\n return self.fillna(method='bfill', axis=axis, inplace=inplace,\n limit=limit, downcast=downcast)\n\n def replace(self, to_replace=None, value=None, inplace=False, limit=None,\n regex=False, method='pad', axis=None):\n \"\"\"\n Replace values given in 'to_replace' with 'value'.\n\n Parameters\n ----------\n to_replace : str, regex, list, dict, Series, numeric, or None\n\n * str or regex:\n\n - str: string exactly matching `to_replace` will be replaced\n with `value`\n - regex: regexs matching `to_replace` will be replaced with\n `value`\n\n * list of str, regex, or numeric:\n\n - First, if `to_replace` and `value` are both lists, they\n **must** be the same length.\n - Second, if ``regex=True`` then all of the strings in **both**\n lists will be interpreted as regexs otherwise they will match\n directly. This doesn't matter much for `value` since there\n are only a few possible substitution regexes you can use.\n - str and regex rules apply as above.\n\n * dict:\n\n - Nested dictionaries, e.g., {'a': {'b': nan}}, are read as\n follows: look in column 'a' for the value 'b' and replace it\n with nan. You can nest regular expressions as well. Note that\n column names (the top-level dictionary keys in a nested\n dictionary) **cannot** be regular expressions.\n - Keys map to column names and values map to substitution\n values. You can treat this as a special case of passing two\n lists except that you are specifying the column to search in.\n\n * None:\n\n - This means that the ``regex`` argument must be a string,\n compiled regular expression, or list, dict, ndarray or Series\n of such elements. If `value` is also ``None`` then this\n **must** be a nested dictionary or ``Series``.\n\n See the examples section for examples of each of these.\n value : scalar, dict, list, str, regex, default None\n Value to use to fill holes (e.g. 0), alternately a dict of values\n specifying which value to use for each column (columns not in the\n dict will not be filled). Regular expressions, strings and lists or\n dicts of such objects are also allowed.\n inplace : boolean, default False\n If True, in place. Note: this will modify any\n other views on this object (e.g. a column form a DataFrame).\n Returns the caller if this is True.\n limit : int, default None\n Maximum size gap to forward or backward fill\n regex : bool or same types as `to_replace`, default False\n Whether to interpret `to_replace` and/or `value` as regular\n expressions. If this is ``True`` then `to_replace` *must* be a\n string. Otherwise, `to_replace` must be ``None`` because this\n parameter will be interpreted as a regular expression or a list,\n dict, or array of regular expressions.\n method : string, optional, {'pad', 'ffill', 'bfill'}\n The method to use when for replacement, when ``to_replace`` is a\n ``list``.\n\n See also\n --------\n NDFrame.reindex\n NDFrame.asfreq\n NDFrame.fillna\n\n Returns\n -------\n filled : NDFrame\n\n Raises\n ------\n AssertionError\n * If `regex` is not a ``bool`` and `to_replace` is not ``None``.\n TypeError\n * If `to_replace` is a ``dict`` and `value` is not a ``list``,\n ``dict``, ``ndarray``, or ``Series``\n * If `to_replace` is ``None`` and `regex` is not compilable into a\n regular expression or is a list, dict, ndarray, or Series.\n ValueError\n * If `to_replace` and `value` are ``list`` s or ``ndarray`` s, but\n they are not the same length.\n\n Notes\n -----\n * Regex substitution is performed under the hood with ``re.sub``. The\n rules for substitution for ``re.sub`` are the same.\n * Regular expressions will only substitute on strings, meaning you\n cannot provide, for example, a regular expression matching floating\n point numbers and expect the columns in your frame that have a\n numeric dtype to be matched. However, if those floating point numbers\n *are* strings, then you can do this.\n * This method has *a lot* of options. You are encouraged to experiment\n and play with this method to gain intuition about how it works.\n\n \"\"\"\n if not com.is_bool(regex) and to_replace is not None:\n raise AssertionError(\"'to_replace' must be 'None' if 'regex' is \"\n \"not a bool\")\n if axis is not None:\n from warnings import warn\n warn('the \"axis\" argument is deprecated and will be removed in'\n 'v0.13; this argument has no effect')\n\n self._consolidate_inplace()\n\n if value is None:\n # passing a single value that is scalar like\n # when value is None (GH5319), for compat\n if not is_dictlike(to_replace) and not is_dictlike(regex):\n to_replace = [to_replace]\n\n if isinstance(to_replace, (tuple, list)):\n return _single_replace(self, to_replace, method, inplace,\n limit)\n\n if not is_dictlike(to_replace):\n if not is_dictlike(regex):\n raise TypeError('If \"to_replace\" and \"value\" are both None'\n ' and \"to_replace\" is not a list, then '\n 'regex must be a mapping')\n to_replace = regex\n regex = True\n\n items = list(compat.iteritems(to_replace))\n keys, values = zip(*items)\n\n are_mappings = [is_dictlike(v) for v in values]\n\n if any(are_mappings):\n if not all(are_mappings):\n raise TypeError(\"If a nested mapping is passed, all values\"\n \" of the top level mapping must be \"\n \"mappings\")\n # passed a nested dict/Series\n to_rep_dict = {}\n value_dict = {}\n\n for k, v in items:\n to_rep_dict[k] = v.keys()\n value_dict[k] = v.values()\n\n to_replace, value = to_rep_dict, value_dict\n else:\n to_replace, value = keys, values\n\n return self.replace(to_replace, value, inplace=inplace,\n limit=limit, regex=regex)\n else:\n\n # need a non-zero len on all axes\n for a in self._AXIS_ORDERS:\n if not len(self._get_axis(a)):\n return self\n\n new_data = self._data\n if is_dictlike(to_replace):\n if is_dictlike(value): # {'A' : NA} -> {'A' : 0}\n new_data = self._data\n for c, src in compat.iteritems(to_replace):\n if c in value and c in self:\n new_data = new_data.replace(to_replace=src,\n value=value[c],\n filter=[c],\n inplace=inplace,\n regex=regex)\n\n # {'A': NA} -> 0\n elif not com.is_list_like(value):\n new_data = self._data\n for k, src in compat.iteritems(to_replace):\n if k in self:\n new_data = new_data.replace(to_replace=src,\n value=value,\n filter=[k],\n inplace=inplace,\n regex=regex)\n else:\n raise TypeError('Fill value must be scalar, dict, or '\n 'Series')\n\n elif com.is_list_like(to_replace): # [NA, ''] -> [0, 'missing']\n if com.is_list_like(value):\n if len(to_replace) != len(value):\n raise ValueError('Replacement lists must match '\n 'in length. Expecting %d got %d ' %\n (len(to_replace), len(value)))\n\n new_data = self._data.replace_list(src_list=to_replace,\n dest_list=value,\n inplace=inplace,\n regex=regex)\n\n else: # [NA, ''] -> 0\n new_data = self._data.replace(to_replace=to_replace,\n value=value,\n inplace=inplace,\n regex=regex)\n elif to_replace is None:\n if not (com.is_re_compilable(regex) or\n com.is_list_like(regex) or\n is_dictlike(regex)):\n raise TypeError(\"'regex' must be a string or a compiled \"\n \"regular expression or a list or dict of \"\n \"strings or regular expressions, you \"\n \"passed a\"\n \" {0!r}\".format(type(regex).__name__))\n return self.replace(regex, value, inplace=inplace, limit=limit,\n regex=True)\n else:\n\n # dest iterable dict-like\n if is_dictlike(value): # NA -> {'A' : 0, 'B' : -1}\n new_data = self._data\n\n for k, v in compat.iteritems(value):\n if k in self:\n new_data = new_data.replace(to_replace=to_replace,\n value=v,\n filter=[k],\n inplace=inplace,\n regex=regex)\n\n elif not com.is_list_like(value): # NA -> 0\n new_data = self._data.replace(to_replace=to_replace, value=value,\n inplace=inplace, regex=regex)\n else:\n msg = ('Invalid \"to_replace\" type: '\n '{0!r}').format(type(to_replace).__name__)\n raise TypeError(msg) # pragma: no cover\n\n new_data = new_data.convert(copy=not inplace, convert_numeric=False)\n\n if inplace:\n self._update_inplace(new_data)\n else:\n return self._constructor(new_data).__finalize__(self)\n\n def interpolate(self, method='linear', axis=0, limit=None, inplace=False,\n downcast='infer', **kwargs):\n \"\"\"\n Interpolate values according to different methods.\n\n Parameters\n ----------\n method : {'linear', 'time', 'values', 'index' 'nearest', 'zero',\n 'slinear', 'quadratic', 'cubic', 'barycentric', 'krogh',\n 'polynomial', 'spline' 'piecewise_polynomial', 'pchip'}\n\n * 'linear': ignore the index and treat the values as equally\n spaced. default\n * 'time': interpolation works on daily and higher resolution\n data to interpolate given length of interval\n * 'index': use the actual numerical values of the index\n * 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',\n 'barycentric', 'polynomial' is passed to\n `scipy.interpolate.interp1d` with the order given both\n 'polynomial' and 'spline' requre that you also specify and order\n (int) e.g. df.interpolate(method='polynomial', order=4)\n * 'krogh', 'piecewise_polynomial', 'spline', and 'pchip' are all\n wrappers around the scipy interpolation methods of similar\n names. See the scipy documentation for more on their behavior:\n http://docs.scipy.org/doc/scipy/reference/interpolate.html#univariate-interpolation\n http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html\n\n axis : {0, 1}, default 0\n * 0: fill column-by-column\n * 1: fill row-by-row\n limit : int, default None.\n Maximum number of consecutive NaNs to fill.\n inplace : bool, default False\n Update the NDFrame in place if possible.\n downcast : optional, 'infer' or None, defaults to 'infer'\n Downcast dtypes if possible.\n\n Returns\n -------\n Series or DataFrame of same shape interpolated at the NaNs\n\n See Also\n --------\n reindex, replace, fillna\n\n Examples\n --------\n\n # Filling in NaNs:\n >>> s = pd.Series([0, 1, np.nan, 3])\n >>> s.interpolate()\n 0 0\n 1 1\n 2 2\n 3 3\n dtype: float64\n\n \"\"\"\n\n if self.ndim > 2:\n raise NotImplementedError(\"Interpolate has not been implemented \"\n \"on Panel and Panel 4D objects.\")\n\n if axis == 0:\n ax = self._info_axis_name\n elif axis == 1:\n self = self.T\n ax = 1\n ax = self._get_axis_number(ax)\n\n if self.ndim == 2:\n alt_ax = 1 - ax\n else:\n alt_ax = ax\n\n if isinstance(self.index, MultiIndex) and method != 'linear':\n raise ValueError(\"Only `method=linear` interpolation is supported \"\n \"on MultiIndexes.\")\n\n if self._data.get_dtype_counts().get('object') == len(self.T):\n raise TypeError(\"Cannot interpolate with all NaNs.\")\n\n # create/use the index\n if method == 'linear':\n index = np.arange(len(self._get_axis(alt_ax))) # prior default\n else:\n index = self._get_axis(alt_ax)\n\n if pd.isnull(index).any():\n raise NotImplementedError(\"Interpolation with NaNs in the index \"\n \"has not been implemented. Try filling \"\n \"those NaNs before interpolating.\")\n new_data = self._data.interpolate(method=method,\n axis=ax,\n index=index,\n values=self,\n limit=limit,\n inplace=inplace,\n downcast=downcast,\n **kwargs)\n\n if inplace:\n if axis == 1:\n self._update_inplace(new_data)\n self = self.T\n else:\n self._update_inplace(new_data)\n else:\n res = self._constructor(new_data).__finalize__(self)\n if axis == 1:\n res = res.T\n return res\n\n #----------------------------------------------------------------------\n # Action Methods\n\n def isnull(self):\n \"\"\"\n Return a boolean same-sized object indicating if the values are null\n \"\"\"\n return isnull(self).__finalize__(self)\n\n def notnull(self):\n \"\"\"Return a boolean same-sized object indicating if the values are\n not null\n \"\"\"\n return notnull(self).__finalize__(self)\n\n def clip(self, lower=None, upper=None, out=None):\n \"\"\"\n Trim values at input threshold(s)\n\n Parameters\n ----------\n lower : float, default None\n upper : float, default None\n\n Returns\n -------\n clipped : Series\n \"\"\"\n if out is not None: # pragma: no cover\n raise Exception('out argument is not supported yet')\n\n # GH 2747 (arguments were reversed)\n if lower is not None and upper is not None:\n lower, upper = min(lower, upper), max(lower, upper)\n\n result = self\n if lower is not None:\n result = result.clip_lower(lower)\n if upper is not None:\n result = result.clip_upper(upper)\n\n return result\n\n def clip_upper(self, threshold):\n \"\"\"\n Return copy of input with values above given value truncated\n\n See also\n --------\n clip\n\n Returns\n -------\n clipped : same type as input\n \"\"\"\n if isnull(threshold):\n raise ValueError(\"Cannot use an NA value as a clip threshold\")\n\n return self.where((self <= threshold) | isnull(self), threshold)\n\n def clip_lower(self, threshold):\n \"\"\"\n Return copy of the input with values below given value truncated\n\n See also\n --------\n clip\n\n Returns\n -------\n clipped : same type as input\n \"\"\"\n if isnull(threshold):\n raise ValueError(\"Cannot use an NA value as a clip threshold\")\n\n return self.where((self >= threshold) | isnull(self), threshold)\n\n def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,\n group_keys=True, squeeze=False):\n \"\"\"\n Group series using mapper (dict or key function, apply given function\n to group, return result as series) or by a series of columns\n\n Parameters\n ----------\n by : mapping function / list of functions, dict, Series, or tuple /\n list of column names.\n Called on each element of the object index to determine the groups.\n If a dict or Series is passed, the Series or dict VALUES will be\n used to determine the groups\n axis : int, default 0\n level : int, level name, or sequence of such, default None\n If the axis is a MultiIndex (hierarchical), group by a particular\n level or levels\n as_index : boolean, default True\n For aggregated output, return object with group labels as the\n index. Only relevant for DataFrame input. as_index=False is\n effectively \"SQL-style\" grouped output\n sort : boolean, default True\n Sort group keys. Get better performance by turning this off\n group_keys : boolean, default True\n When calling apply, add group keys to index to identify pieces\n squeeze : boolean, default False\n reduce the dimensionaility of the return type if possible,\n otherwise return a consistent type\n\n Examples\n --------\n # DataFrame result\n >>> data.groupby(func, axis=0).mean()\n\n # DataFrame result\n >>> data.groupby(['col1', 'col2'])['col3'].mean()\n\n # DataFrame with hierarchical index\n >>> data.groupby(['col1', 'col2']).mean()\n\n Returns\n -------\n GroupBy object\n\n \"\"\"\n\n from pandas.core.groupby import groupby\n axis = self._get_axis_number(axis)\n return groupby(self, by, axis=axis, level=level, as_index=as_index,\n sort=sort, group_keys=group_keys, squeeze=squeeze)\n\n def asfreq(self, freq, method=None, how=None, normalize=False):\n \"\"\"\n Convert all TimeSeries inside to specified frequency using DateOffset\n objects. Optionally provide fill method to pad/backfill missing values.\n\n Parameters\n ----------\n freq : DateOffset object, or string\n method : {'backfill', 'bfill', 'pad', 'ffill', None}\n Method to use for filling holes in reindexed Series\n pad / ffill: propagate last valid observation forward to next valid\n backfill / bfill: use NEXT valid observation to fill method\n how : {'start', 'end'}, default end\n For PeriodIndex only, see PeriodIndex.asfreq\n normalize : bool, default False\n Whether to reset output index to midnight\n\n Returns\n -------\n converted : type of caller\n \"\"\"\n from pandas.tseries.resample import asfreq\n return asfreq(self, freq, method=method, how=how,\n normalize=normalize)\n\n def at_time(self, time, asof=False):\n \"\"\"\n Select values at particular time of day (e.g. 9:30AM)\n\n Parameters\n ----------\n time : datetime.time or string\n\n Returns\n -------\n values_at_time : type of caller\n \"\"\"\n try:\n indexer = self.index.indexer_at_time(time, asof=asof)\n return self.take(indexer, convert=False)\n except AttributeError:\n raise TypeError('Index must be DatetimeIndex')\n\n def between_time(self, start_time, end_time, include_start=True,\n include_end=True):\n \"\"\"\n Select values between particular times of the day (e.g., 9:00-9:30 AM)\n\n Parameters\n ----------\n start_time : datetime.time or string\n end_time : datetime.time or string\n include_start : boolean, default True\n include_end : boolean, default True\n\n Returns\n -------\n values_between_time : type of caller\n \"\"\"\n try:\n indexer = self.index.indexer_between_time(\n start_time, end_time, include_start=include_start,\n include_end=include_end)\n return self.take(indexer, convert=False)\n except AttributeError:\n raise TypeError('Index must be DatetimeIndex')\n\n def resample(self, rule, how=None, axis=0, fill_method=None,\n closed=None, label=None, convention='start',\n kind=None, loffset=None, limit=None, base=0):\n \"\"\"\n Convenience method for frequency conversion and resampling of regular\n time-series data.\n\n Parameters\n ----------\n rule : string\n the offset string or object representing target conversion\n how : string\n method for down- or re-sampling, default to 'mean' for\n downsampling\n axis : int, optional, default 0\n fill_method : string, default None\n fill_method for upsampling\n closed : {'right', 'left'}\n Which side of bin interval is closed\n label : {'right', 'left'}\n Which bin edge label to label bucket with\n convention : {'start', 'end', 's', 'e'}\n kind : \"period\"/\"timestamp\"\n loffset : timedelta\n Adjust the resampled time labels\n limit : int, default None\n Maximum size gap to when reindexing with fill_method\n base : int, default 0\n For frequencies that evenly subdivide 1 day, the \"origin\" of the\n aggregated intervals. For example, for '5min' frequency, base could\n range from 0 through 4. Defaults to 0\n \"\"\"\n from pandas.tseries.resample import TimeGrouper\n axis = self._get_axis_number(axis)\n sampler = TimeGrouper(rule, label=label, closed=closed, how=how,\n axis=axis, kind=kind, loffset=loffset,\n fill_method=fill_method, convention=convention,\n limit=limit, base=base)\n return sampler.resample(self).__finalize__(self)\n\n def first(self, offset):\n \"\"\"\n Convenience method for subsetting initial periods of time series data\n based on a date offset\n\n Parameters\n ----------\n offset : string, DateOffset, dateutil.relativedelta\n\n Examples\n --------\n ts.last('10D') -> First 10 days\n\n Returns\n -------\n subset : type of caller\n \"\"\"\n from pandas.tseries.frequencies import to_offset\n if not isinstance(self.index, DatetimeIndex):\n raise NotImplementedError\n\n if len(self.index) == 0:\n return self\n\n offset = to_offset(offset)\n end_date = end = self.index[0] + offset\n\n # Tick-like, e.g. 3 weeks\n if not offset.isAnchored() and hasattr(offset, '_inc'):\n if end_date in self.index:\n end = self.index.searchsorted(end_date, side='left')\n\n return self.ix[:end]\n\n def last(self, offset):\n \"\"\"\n Convenience method for subsetting final periods of time series data\n based on a date offset\n\n Parameters\n ----------\n offset : string, DateOffset, dateutil.relativedelta\n\n Examples\n --------\n ts.last('5M') -> Last 5 months\n\n Returns\n -------\n subset : type of caller\n \"\"\"\n from pandas.tseries.frequencies import to_offset\n if not isinstance(self.index, DatetimeIndex):\n raise NotImplementedError\n\n if len(self.index) == 0:\n return self\n\n offset = to_offset(offset)\n\n start_date = start = self.index[-1] - offset\n start = self.index.searchsorted(start_date, side='right')\n return self.ix[start:]\n\n def align(self, other, join='outer', axis=None, level=None, copy=True,\n fill_value=None, method=None, limit=None, fill_axis=0):\n \"\"\"\n Align two object on their axes with the\n specified join method for each axis Index\n\n Parameters\n ----------\n other : DataFrame or Series\n join : {'outer', 'inner', 'left', 'right'}, default 'outer'\n axis : allowed axis of the other object, default None\n Align on index (0), columns (1), or both (None)\n level : int or name\n Broadcast across a level, matching Index values on the\n passed MultiIndex level\n copy : boolean, default True\n Always returns new objects. If copy=False and no reindexing is\n required then original objects are returned.\n fill_value : scalar, default np.NaN\n Value to use for missing values. Defaults to NaN, but can be any\n \"compatible\" value\n method : str, default None\n limit : int, default None\n fill_axis : {0, 1}, default 0\n Filling axis, method and limit\n\n Returns\n -------\n (left, right) : (type of input, type of other)\n Aligned objects\n \"\"\"\n from pandas import DataFrame, Series\n method = com._clean_fill_method(method)\n\n if axis is not None:\n axis = self._get_axis_number(axis)\n if isinstance(other, DataFrame):\n return self._align_frame(other, join=join, axis=axis, level=level,\n copy=copy, fill_value=fill_value,\n method=method, limit=limit,\n fill_axis=fill_axis)\n elif isinstance(other, Series):\n return self._align_series(other, join=join, axis=axis, level=level,\n copy=copy, fill_value=fill_value,\n method=method, limit=limit,\n fill_axis=fill_axis)\n else: # pragma: no cover\n raise TypeError('unsupported type: %s' % type(other))\n\n def _align_frame(self, other, join='outer', axis=None, level=None,\n copy=True, fill_value=np.nan, method=None, limit=None,\n fill_axis=0):\n # defaults\n join_index, join_columns = None, None\n ilidx, iridx = None, None\n clidx, cridx = None, None\n\n if axis is None or axis == 0:\n if not self.index.equals(other.index):\n join_index, ilidx, iridx = \\\n self.index.join(other.index, how=join, level=level,\n return_indexers=True)\n\n if axis is None or axis == 1:\n if not self.columns.equals(other.columns):\n join_columns, clidx, cridx = \\\n self.columns.join(other.columns, how=join, level=level,\n return_indexers=True)\n\n left = self._reindex_with_indexers({0: [join_index, ilidx],\n 1: [join_columns, clidx]},\n copy=copy, fill_value=fill_value,\n allow_dups=True)\n right = other._reindex_with_indexers({0: [join_index, iridx],\n 1: [join_columns, cridx]},\n copy=copy, fill_value=fill_value,\n allow_dups=True)\n\n if method is not None:\n left = left.fillna(axis=fill_axis, method=method, limit=limit)\n right = right.fillna(axis=fill_axis, method=method, limit=limit)\n\n return left.__finalize__(self), right.__finalize__(other)\n\n def _align_series(self, other, join='outer', axis=None, level=None,\n copy=True, fill_value=None, method=None, limit=None,\n fill_axis=0):\n from pandas import DataFrame\n\n # series/series compat\n if isinstance(self, ABCSeries) and isinstance(other, ABCSeries):\n if axis:\n raise ValueError('cannot align series to a series other than '\n 'axis 0')\n\n join_index, lidx, ridx = self.index.join(other.index, how=join,\n level=level,\n return_indexers=True)\n\n left_result = self._reindex_indexer(join_index, lidx, copy)\n right_result = other._reindex_indexer(join_index, ridx, copy)\n\n else:\n\n # one has > 1 ndim\n fdata = self._data\n if axis == 0:\n join_index = self.index\n lidx, ridx = None, None\n if not self.index.equals(other.index):\n join_index, lidx, ridx = self.index.join(\n other.index, how=join, return_indexers=True)\n\n if lidx is not None:\n fdata = fdata.reindex_indexer(join_index, lidx, axis=1)\n elif axis == 1:\n join_index = self.columns\n lidx, ridx = None, None\n if not self.columns.equals(other.index):\n join_index, lidx, ridx = \\\n self.columns.join(other.index, how=join,\n return_indexers=True)\n\n if lidx is not None:\n fdata = fdata.reindex_indexer(join_index, lidx, axis=0)\n else:\n raise ValueError('Must specify axis=0 or 1')\n\n if copy and fdata is self._data:\n fdata = fdata.copy()\n\n left_result = DataFrame(fdata)\n right_result = other if ridx is None else other.reindex(join_index)\n\n # fill\n fill_na = notnull(fill_value) or (method is not None)\n if fill_na:\n return (left_result.fillna(fill_value, method=method, limit=limit,\n axis=fill_axis),\n right_result.fillna(fill_value, method=method,\n limit=limit))\n else:\n return (left_result.__finalize__(self),\n right_result.__finalize__(other))\n\n def where(self, cond, other=np.nan, inplace=False, axis=None, level=None,\n try_cast=False, raise_on_error=True):\n \"\"\"\n Return an object of same shape as self and whose corresponding\n entries are from self where cond is True and otherwise are from other.\n\n Parameters\n ----------\n cond : boolean NDFrame or array\n other : scalar or NDFrame\n inplace : boolean, default False\n Whether to perform the operation in place on the data\n axis : alignment axis if needed, default None\n level : alignment level if needed, default None\n try_cast : boolean, default False\n try to cast the result back to the input type (if possible),\n raise_on_error : boolean, default True\n Whether to raise on invalid data types (e.g. trying to where on\n strings)\n\n Returns\n -------\n wh : same type as caller\n \"\"\"\n if isinstance(cond, NDFrame):\n cond = cond.reindex(**self._construct_axes_dict())\n else:\n if not hasattr(cond, 'shape'):\n raise ValueError('where requires an ndarray like object for '\n 'its condition')\n if cond.shape != self.shape:\n raise ValueError(\n 'Array conditional must be same shape as self')\n cond = self._constructor(cond, **self._construct_axes_dict())\n\n if inplace:\n cond = -(cond.fillna(True).astype(bool))\n else:\n cond = cond.fillna(False).astype(bool)\n\n # try to align\n try_quick = True\n if hasattr(other, 'align'):\n\n # align with me\n if other.ndim <= self.ndim:\n\n _, other = self.align(other, join='left',\n axis=axis, level=level,\n fill_value=np.nan)\n\n # if we are NOT aligned, raise as we cannot where index\n if (axis is None and\n not all([other._get_axis(i).equals(ax)\n for i, ax in enumerate(self.axes)])):\n raise InvalidIndexError\n\n # slice me out of the other\n else:\n raise NotImplemented(\n \"cannot align with a higher dimensional NDFrame\"\n )\n\n elif is_list_like(other):\n\n if self.ndim == 1:\n\n # try to set the same dtype as ourselves\n new_other = np.array(other, dtype=self.dtype)\n if not (new_other == np.array(other)).all():\n other = np.array(other)\n\n # we can't use our existing dtype\n # because of incompatibilities\n try_quick = False\n else:\n other = new_other\n else:\n\n other = np.array(other)\n\n if isinstance(other, np.ndarray):\n\n if other.shape != self.shape:\n\n if self.ndim == 1:\n\n icond = cond.values\n\n # GH 2745 / GH 4192\n # treat like a scalar\n if len(other) == 1:\n other = np.array(other[0])\n\n # GH 3235\n # match True cond to other\n elif len(cond[icond]) == len(other):\n\n # try to not change dtype at first (if try_quick)\n if try_quick:\n\n try:\n new_other = _values_from_object(self).copy()\n new_other[icond] = other\n other = new_other\n except:\n try_quick = False\n\n # let's create a new (if we failed at the above\n # or not try_quick\n if not try_quick:\n\n dtype, fill_value = _maybe_promote(other.dtype)\n new_other = np.empty(len(icond), dtype=dtype)\n new_other.fill(fill_value)\n com._maybe_upcast_putmask(new_other, icond, other)\n other = new_other\n\n else:\n raise ValueError(\n 'Length of replacements must equal series length')\n\n else:\n raise ValueError('other must be the same shape as self '\n 'when an ndarray')\n\n # we are the same shape, so create an actual object for alignment\n else:\n other = self._constructor(other, **self._construct_axes_dict())\n\n if inplace:\n # we may have different type blocks come out of putmask, so\n # reconstruct the block manager\n new_data = self._data.putmask(mask=cond, new=other, align=axis is None,\n inplace=True)\n self._update_inplace(new_data)\n\n else:\n new_data = self._data.where(other=other, cond=cond, align=axis is None,\n raise_on_error=raise_on_error,\n try_cast=try_cast)\n\n return self._constructor(new_data).__finalize__(self)\n\n def mask(self, cond):\n \"\"\"\n Returns copy whose values are replaced with nan if the\n inverted condition is True\n\n Parameters\n ----------\n cond : boolean NDFrame or array\n\n Returns\n -------\n wh: same as input\n \"\"\"\n return self.where(~cond, np.nan)\n\n def shift(self, periods=1, freq=None, axis=0, **kwds):\n \"\"\"\n Shift index by desired number of periods with an optional time freq\n\n Parameters\n ----------\n periods : int\n Number of periods to move, can be positive or negative\n freq : DateOffset, timedelta, or time rule string, optional\n Increment to use from datetools module or time rule (e.g. 'EOM')\n\n Notes\n -----\n If freq is specified then the index values are shifted but the data\n if not realigned\n\n Returns\n -------\n shifted : same type as caller\n \"\"\"\n if periods == 0:\n return self\n\n if freq is None and not len(kwds):\n block_axis = self._get_block_manager_axis(axis)\n indexer = com._shift_indexer(len(self), periods)\n new_data = self._data.shift(indexer=indexer, periods=periods, axis=block_axis)\n else:\n return self.tshift(periods, freq, **kwds)\n\n return self._constructor(new_data).__finalize__(self)\n\n def tshift(self, periods=1, freq=None, axis=0, **kwds):\n \"\"\"\n Shift the time index, using the index's frequency if available\n\n Parameters\n ----------\n periods : int\n Number of periods to move, can be positive or negative\n freq : DateOffset, timedelta, or time rule string, default None\n Increment to use from datetools module or time rule (e.g. 'EOM')\n axis : int or basestring\n Corresponds to the axis that contains the Index\n\n Notes\n -----\n If freq is not specified then tries to use the freq or inferred_freq\n attributes of the index. If neither of those attributes exist, a\n ValueError is thrown\n\n Returns\n -------\n shifted : NDFrame\n \"\"\"\n from pandas.core.datetools import _resolve_offset\n\n index = self._get_axis(axis)\n if freq is None:\n freq = getattr(index, 'freq', None)\n\n if freq is None:\n freq = getattr(index, 'inferred_freq', None)\n\n if freq is None:\n msg = 'Freq was not given and was not set in the index'\n raise ValueError(msg)\n\n if periods == 0:\n return self\n\n offset = _resolve_offset(freq, kwds)\n\n if isinstance(offset, string_types):\n offset = datetools.to_offset(offset)\n\n block_axis = self._get_block_manager_axis(axis)\n if isinstance(index, PeriodIndex):\n orig_offset = datetools.to_offset(index.freq)\n if offset == orig_offset:\n new_data = self._data.copy()\n new_data.axes[block_axis] = index.shift(periods)\n else:\n msg = ('Given freq %s does not match PeriodIndex freq %s' %\n (offset.rule_code, orig_offset.rule_code))\n raise ValueError(msg)\n else:\n new_data = self._data.copy()\n new_data.axes[block_axis] = index.shift(periods, offset)\n\n return self._constructor(new_data).__finalize__(self)\n\n def truncate(self, before=None, after=None, axis=None, copy=True):\n \"\"\"Truncates a sorted NDFrame before and/or after some particular\n dates.\n\n Parameters\n ----------\n before : date\n Truncate before date\n after : date\n Truncate after date\n axis : the truncation axis, defaults to the stat axis\n copy : boolean, default is True,\n return a copy of the truncated section\n\n Returns\n -------\n truncated : type of caller\n \"\"\"\n\n if axis is None:\n axis = self._stat_axis_number\n axis = self._get_axis_number(axis)\n ax = self._get_axis(axis)\n\n # if we have a date index, convert to dates, otherwise\n # treat like a slice\n if ax.is_all_dates:\n from pandas.tseries.tools import to_datetime\n before = to_datetime(before)\n after = to_datetime(after)\n\n if before is not None and after is not None:\n if before > after:\n raise ValueError('Truncate: %s must be after %s' %\n (after, before))\n\n slicer = [slice(None, None)] * self._AXIS_LEN\n slicer[axis] = slice(before, after)\n result = self.ix[tuple(slicer)]\n\n if isinstance(ax, MultiIndex):\n setattr(result, self._get_axis_name(axis),\n ax.truncate(before, after))\n\n if copy:\n result = result.copy()\n\n return result\n\n def tz_convert(self, tz, axis=0, copy=True):\n \"\"\"\n Convert TimeSeries to target time zone. If it is time zone naive, it\n will be localized to the passed time zone.\n\n Parameters\n ----------\n tz : string or pytz.timezone object\n copy : boolean, default True\n Also make a copy of the underlying data\n\n Returns\n -------\n \"\"\"\n axis = self._get_axis_number(axis)\n ax = self._get_axis(axis)\n\n if not hasattr(ax, 'tz_convert'):\n ax_name = self._get_axis_name(axis)\n raise TypeError('%s is not a valid DatetimeIndex or PeriodIndex' %\n ax_name)\n\n new_data = self._data\n if copy:\n new_data = new_data.copy()\n\n new_obj = self._constructor(new_data)\n new_ax = ax.tz_convert(tz)\n\n if axis == 0:\n new_obj._set_axis(1, new_ax)\n elif axis == 1:\n new_obj._set_axis(0, new_ax)\n self._clear_item_cache()\n\n return new_obj.__finalize__(self)\n\n def tz_localize(self, tz, axis=0, copy=True, infer_dst=False):\n \"\"\"\n Localize tz-naive TimeSeries to target time zone\n\n Parameters\n ----------\n tz : string or pytz.timezone object\n copy : boolean, default True\n Also make a copy of the underlying data\n infer_dst : boolean, default False\n Attempt to infer fall dst-transition times based on order\n\n Returns\n -------\n \"\"\"\n axis = self._get_axis_number(axis)\n ax = self._get_axis(axis)\n\n if not hasattr(ax, 'tz_localize'):\n ax_name = self._get_axis_name(axis)\n raise TypeError('%s is not a valid DatetimeIndex or PeriodIndex' %\n ax_name)\n\n new_data = self._data\n if copy:\n new_data = new_data.copy()\n\n new_obj = self._constructor(new_data)\n new_ax = ax.tz_localize(tz, infer_dst=infer_dst)\n\n if axis == 0:\n new_obj._set_axis(1, new_ax)\n elif axis == 1:\n new_obj._set_axis(0, new_ax)\n self._clear_item_cache()\n\n return new_obj.__finalize__(self)\n\n #----------------------------------------------------------------------\n # Numeric Methods\n def abs(self):\n \"\"\"\n Return an object with absolute value taken. Only applicable to objects\n that are all numeric\n\n Returns\n -------\n abs: type of caller\n \"\"\"\n\n # suprimo numpy 1.6 hacking\n # for timedeltas\n if _np_version_under1p7:\n\n def _convert_timedeltas(x):\n if x.dtype.kind == 'm':\n return np.abs(x.view('i8')).astype(x.dtype)\n return np.abs(x)\n\n if self.ndim == 1:\n return _convert_timedeltas(self)\n elif self.ndim == 2:\n return self.apply(_convert_timedeltas)\n\n return np.abs(self)\n\n def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None,\n **kwds):\n \"\"\"\n Percent change over given number of periods\n\n Parameters\n ----------\n periods : int, default 1\n Periods to shift for forming percent change\n fill_method : str, default 'pad'\n How to handle NAs before computing percent changes\n limit : int, default None\n The number of consecutive NAs to fill before stopping\n freq : DateOffset, timedelta, or offset alias string, optional\n Increment to use from time series API (e.g. 'M' or BDay())\n\n Returns\n -------\n chg : same type as caller\n \"\"\"\n # TODO: Not sure if above is correct - need someone to confirm.\n if fill_method is None:\n data = self\n else:\n data = self.fillna(method=fill_method, limit=limit)\n rs = data / data.shift(periods=periods, freq=freq, **kwds) - 1\n if freq is None:\n mask = com.isnull(_values_from_object(self))\n np.putmask(rs.values, mask, np.nan)\n return rs\n\n def _agg_by_level(self, name, axis=0, level=0, skipna=True, **kwds):\n grouped = self.groupby(level=level, axis=axis)\n if hasattr(grouped, name) and skipna:\n return getattr(grouped, name)(**kwds)\n axis = self._get_axis_number(axis)\n method = getattr(type(self), name)\n applyf = lambda x: method(x, axis=axis, skipna=skipna, **kwds)\n return grouped.aggregate(applyf)\n\n @classmethod\n def _add_numeric_operations(cls):\n \"\"\" add the operations to the cls; evaluate the doc strings again \"\"\"\n\n axis_descr = \"{%s}\" % ', '.join([\n \"{0} ({1})\".format(a, i) for i, a in enumerate(cls._AXIS_ORDERS)\n ])\n name = (cls._constructor_sliced.__name__\n if cls._AXIS_LEN > 1 else 'scalar')\n _num_doc = \"\"\"\n\n%(desc)s\n\nParameters\n----------\naxis : \"\"\" + axis_descr + \"\"\"\nskipna : boolean, default True\n Exclude NA/null values. If an entire row/column is NA, the result\n will be NA\nlevel : int, default None\n If the axis is a MultiIndex (hierarchical), count along a\n particular level, collapsing into a \"\"\" + name + \"\"\"\nnumeric_only : boolean, default None\n Include only float, int, boolean data. If None, will attempt to use\n everything, then use only numeric data\n\nReturns\n-------\n%(outname)s : \"\"\" + name + \" or \" + cls.__name__ + \" (if level specified)\\n\"\n\n _cnum_doc = \"\"\"\n\nParameters\n----------\naxis : \"\"\" + axis_descr + \"\"\"\nskipna : boolean, default True\n Exclude NA/null values. If an entire row/column is NA, the result\n will be NA\n\nReturns\n-------\n%(outname)s : \"\"\" + name + \"\\n\"\n\n def _make_stat_function(name, desc, f):\n\n @Substitution(outname=name, desc=desc)\n @Appender(_num_doc)\n def stat_func(self, axis=None, skipna=None, level=None,\n numeric_only=None, **kwargs):\n if skipna is None:\n skipna = True\n if axis is None:\n axis = self._stat_axis_number\n if level is not None:\n return self._agg_by_level(name, axis=axis, level=level,\n skipna=skipna)\n return self._reduce(f, axis=axis,\n skipna=skipna, numeric_only=numeric_only)\n stat_func.__name__ = name\n return stat_func\n\n cls.sum = _make_stat_function(\n 'sum', 'Return the sum of the values for the requested axis',\n nanops.nansum)\n cls.mean = _make_stat_function(\n 'mean', 'Return the mean of the values for the requested axis',\n nanops.nanmean)\n cls.skew = _make_stat_function(\n 'skew',\n 'Return unbiased skew over requested axis\\nNormalized by N-1',\n nanops.nanskew)\n cls.kurt = _make_stat_function(\n 'kurt',\n 'Return unbiased kurtosis over requested axis\\nNormalized by N-1',\n nanops.nankurt)\n cls.kurtosis = cls.kurt\n cls.prod = _make_stat_function(\n 'prod', 'Return the product of the values for the requested axis',\n nanops.nanprod)\n cls.product = cls.prod\n cls.median = _make_stat_function(\n 'median', 'Return the median of the values for the requested axis',\n nanops.nanmedian)\n cls.max = _make_stat_function('max', \"\"\"\nThis method returns the maximum of the values in the object. If you\nwant the *index* of the maximum, use ``idxmax``. This is the\nequivalent of the ``numpy.ndarray`` method ``argmax``.\"\"\", nanops.nanmax)\n cls.min = _make_stat_function('min', \"\"\"\nThis method returns the minimum of the values in the object. If you\nwant the *index* of the minimum, use ``idxmin``. This is the\nequivalent of the ``numpy.ndarray`` method ``argmin``.\"\"\", nanops.nanmin)\n\n @Substitution(outname='mad',\n desc=\"Return the mean absolute deviation of the values \"\n \"for the requested axis\")\n @Appender(_num_doc)\n def mad(self, axis=None, skipna=None, level=None, **kwargs):\n if skipna is None:\n skipna = True\n if axis is None:\n axis = self._stat_axis_number\n if level is not None:\n return self._agg_by_level('mad', axis=axis, level=level,\n skipna=skipna)\n\n data = self._get_numeric_data()\n if axis == 0:\n demeaned = data - data.mean(axis=0)\n else:\n demeaned = data.sub(data.mean(axis=1), axis=0)\n return np.abs(demeaned).mean(axis=axis, skipna=skipna)\n cls.mad = mad\n\n @Substitution(outname='variance',\n desc=\"Return unbiased variance over requested \"\n \"axis\\nNormalized by N-1\")\n @Appender(_num_doc)\n def var(self, axis=None, skipna=None, level=None, ddof=1, **kwargs):\n if skipna is None:\n skipna = True\n if axis is None:\n axis = self._stat_axis_number\n if level is not None:\n return self._agg_by_level('var', axis=axis, level=level,\n skipna=skipna, ddof=ddof)\n\n return self._reduce(nanops.nanvar, axis=axis, skipna=skipna,\n ddof=ddof)\n cls.var = var\n\n @Substitution(outname='stdev',\n desc=\"Return unbiased standard deviation over requested \"\n \"axis\\nNormalized by N-1\")\n @Appender(_num_doc)\n def std(self, axis=None, skipna=None, level=None, ddof=1, **kwargs):\n if skipna is None:\n skipna = True\n if axis is None:\n axis = self._stat_axis_number\n if level is not None:\n return self._agg_by_level('std', axis=axis, level=level,\n skipna=skipna, ddof=ddof)\n result = self.var(axis=axis, skipna=skipna, ddof=ddof)\n if getattr(result, 'ndim', 0) > 0:\n return result.apply(np.sqrt)\n return np.sqrt(result)\n cls.std = std\n\n @Substitution(outname='compounded',\n desc=\"Return the compound percentage of the values for \"\n \"the requested axis\")\n @Appender(_num_doc)\n def compound(self, axis=None, skipna=None, level=None, **kwargs):\n if skipna is None:\n skipna = True\n return (1 + self).prod(axis=axis, skipna=skipna, level=level) - 1\n cls.compound = compound\n\n def _make_cum_function(name, accum_func, mask_a, mask_b):\n\n @Substitution(outname=name)\n @Appender(\"Return cumulative {0} over requested axis.\".format(name)\n + _cnum_doc)\n def func(self, axis=None, dtype=None, out=None, skipna=True,\n **kwargs):\n if axis is None:\n axis = self._stat_axis_number\n else:\n axis = self._get_axis_number(axis)\n\n y = _values_from_object(self).copy()\n if not issubclass(y.dtype.type, (np.integer, np.bool_)):\n mask = isnull(self)\n if skipna:\n np.putmask(y, mask, mask_a)\n result = accum_func(y, axis)\n if skipna:\n np.putmask(result, mask, mask_b)\n else:\n result = accum_func(y, axis)\n\n d = self._construct_axes_dict()\n d['copy'] = False\n return self._constructor(result, **d).__finalize__(self)\n\n func.__name__ = name\n return func\n\n cls.cummin = _make_cum_function(\n 'min', lambda y, axis: np.minimum.accumulate(y, axis),\n np.inf, np.nan)\n cls.cumsum = _make_cum_function(\n 'sum', lambda y, axis: y.cumsum(axis), 0., np.nan)\n cls.cumprod = _make_cum_function(\n 'prod', lambda y, axis: y.cumprod(axis), 1., np.nan)\n cls.cummax = _make_cum_function(\n 'max', lambda y, axis: np.maximum.accumulate(y, axis),\n -np.inf, np.nan)\n\n# install the indexerse\nfor _name, _indexer in indexing.get_indexers_list():\n NDFrame._create_indexer(_name, _indexer)\n" ]
[ [ "pandas.core.common.is_re_compilable", "pandas.core.datetools.to_offset", "pandas.core.common._values_from_object", "pandas.io.pickle.to_pickle", "pandas.core.common._ensure_int64", "pandas.io.pytables.to_hdf", "pandas.core.common._clean_fill_method", "pandas.core.indexing.get_indexers_list", "pandas.core.common._maybe_promote", "pandas.tseries.resample.TimeGrouper", "pandas.compat.map", "pandas.core.common.isnull", "numpy.dtype", "numpy.putmask", "pandas.compat.iteritems", "pandas.DataFrame", "pandas.core.groupby.groupby", "pandas.core.internals.BlockManager", "pandas.core.common.SettingWithCopyError", "pandas.core.index._ensure_index", "pandas.util.decorators.Substitution", "pandas.core.common.is_list_like", "pandas.core.common.mask_missing", "numpy.sqrt", "pandas.io.clipboard.to_clipboard", "pandas.util.decorators.Appender", "pandas.core.common._index_labels_to_array", "pandas.compat.isidentifier", "pandas.core.config.get_option", "numpy.array", "pandas.core.datetools._resolve_offset", "pandas.tseries.resample.asfreq", "pandas.io.json.to_json", "pandas.core.common._get_fill_func", "pandas.core.common.is_integer", "pandas.compat.lrange", "numpy.isscalar", "pandas.core.common.is_bool", "pandas.isnull", "pandas.tseries.frequencies.to_offset", "numpy.minimum.accumulate", "pandas.core.common._maybe_upcast_putmask", "pandas.compat.zip", "pandas.core.common.notnull", "numpy.maximum.accumulate", "pandas.lib.AxisProperty", "pandas.io.packers.to_msgpack", "pandas.io.pickle.read_pickle", "numpy.abs", "pandas.Series", "pandas.tseries.tools.to_datetime" ] ]
bassio/omicexperiment
[ "323de49bb528e91658b38ed748a47c062e371048" ]
[ "omicexperiment/experiment/experiment.py" ]
[ "import types\nimport functools\nfrom collections import OrderedDict\nimport numpy as np\nfrom pandas import Series, DataFrame\nfrom omicexperiment.transforms import proxy\nfrom omicexperiment.plotting.plot_pygal import plot_table, return_plot, return_plot_tree, plot_to_file\nfrom omicexperiment.plotting.groups import group_plot_tree\nfrom omicexperiment.rarefaction import rarefy_dataframe\nfrom omicexperiment.dataframe import load_dataframe\nfrom omicexperiment.transforms.transform import Transform, Filter\n\n\nclass Experiment(object):\n def __init__(self, data_df, metadata={}):\n self.data_df = load_dataframe(data_df)\n self.metadata = metadata\n\n\nclass OmicExperiment(Experiment):\n Sample = proxy.Sample()\n Observation = proxy.Observation()\n \n def __init__(self, data_df, mapping_df = None, metadata={}):\n Experiment.__init__(self, data_df, metadata)\n #self.data_df = load_dataframe(data_df)\n\n self.mapping_df = load_dataframe(mapping_df, first_col_in_file_as_index=True)\n\n\n def apply(self, transforms, axis=0):\n if isinstance(transforms, Transform) \\\n or \\\n (isinstance(transforms, type) and issubclass(transforms, Transform)):\n transform = transforms #only a single object passed (not a list)\n return transform.__eapply__(self)\n\n elif isinstance(transforms, (types.FunctionType, types.BuiltinFunctionType, functools.partial)):\n func = transforms #only a single object passed (not a list)\n transformed_data_df = DataFrame(self.data_df.apply(func, axis=axis))\n\n #transpose to return the samples as column namess rather than row names\n if axis == 0 : transformed_data_df = transformed_data_df.transpose()\n\n return self.with_data_df(transformed_data_df)\n\n elif isinstance(transforms, list):\n transformed_exp = self\n for transform in transforms:\n transformed_exp = transform.__eapply__(transformed_exp)\n return transformed_exp\n\n else:\n raise NotImplementedError\n\n\n def dapply(self, transforms, axis=0):\n if isinstance(transforms, Transform) \\\n or \\\n (isinstance(transforms, type) and issubclass(transforms, Transform)):\n transform = transforms #only a single object passed (not a list)\n return transform.__dapply__(self)\n else:\n raise NotImplementedError\n\n\n @property\n def samples(self):\n return list(self.data_df.columns)\n\n @property\n def observations(self):\n return list(self.data_df.index)\n\n @property\n def stats_df(self):\n return self.mapping_df.join(self.data_df.transpose(), how='inner')\n\n def get_plot(self):\n plot = return_plot(self.data_df)\n return plot\n\n def get_plot_tree(self):\n plot = return_plot(self.data_df)\n return return_plot_tree(plot)\n\n def plot(self, backend='pygal', outputfile=None):\n if backend == 'pygal':\n plot = self.get_plot()\n tree = self.get_plot_tree()\n\n if outputfile is not None:\n plot_to_file(plot, tree, outputfile)\n\n return tree\n elif backend == 'matplotlib':\n from omicexperiment.plotting.plot_matplotlib import taxa_bar_plot\n return taxa_bar_plot(self.data_df)\n \n def plot_groups(self, mapping_group_col, outputfile=None, **kwargs):\n if isinstance(mapping_group_col, str):\n group_col = self.mapping_df[mapping_group_col]\n\n plot, tree = group_plot_tree(self.data_df, group_col, **kwargs)\n\n if outputfile is not None:\n plot_to_file(plot, tree, outputfile)\n\n return tree\n\n def plot_interactive(self):\n from omicexperiment.plotting.plot_bokeh import plot_interactive\n fig = plot_interactive(self.data_df)\n from bokeh.io import show, output_notebook\n output_notebook()\n show(fig)\n return fig\n\n def plot_matplobli(self):\n from omicexperiment.plotting.plot_bokeh import plot_interactive\n fig = plot_interactive(self.data_df)\n from bokeh.io import show, output_notebook\n output_notebook()\n show(fig)\n return fig\n \n def groupby(self, variable, aggfunc=np.mean):\n from omicexperiment.transforms.sample import SampleGroupBy\n return self.apply(SampleGroupBy(variable, aggfunc))\n\n def to_relative_abundance(self):\n from omicexperiment.transforms.general import RelativeAbundance\n return self.apply(RelativeAbundance)\n\n def __getitem__(self, value):\n return self.apply(value)\n\n def with_data_df(self, new_data_df):\n new_exp = self.__class__(new_data_df, self.mapping_df)\n return new_exp\n\n def with_mapping_df(self, new_mapping_df, reindex_data_df=True):\n if reindex_data_df:\n new_data_df = self.data_df.reindex(columns=new_mapping_df.index)\n else:\n new_data_df = self.data_df\n\n new_exp = self.__class__(new_data_df, new_mapping_df)\n return new_exp\n\n\n def description(self, as_dict=False):\n desc = \\\n (\"\"\n \"Num samples: {num_samples}\\n\"\n \"Num observations: {num_observations}\\n\"\n \"Total count: {total_count}\\n\"\n \"Table density (fraction of non-zero values): {table_density}\\n\"\n \"\\n\"\n \"Counts/sample summary:\\n\"\n \"Min: {min_sample}\\n\"\n \"Max: {max_sample}\\n\"\n \"Median: {median_sample}\\n\"\n \"Mean: {mean_sample}\\n\"\n \"Std. dev.: {std_sample}\\n\"\n \"Sample Metadata Categories: None\\n\"\n \"Observation Metadata Categories: None\\n\"\n \"\\n\"\n \"Counts/sample detail:\\n\"\n \"{sample_counts}\"\n \"\")\n\n d = {}\n d['num_samples'] = len(self.data_df.columns)\n d['num_observations'] = len(self.data_df.index)\n d['total_count'] = self.data_df.sum().sum();\n\n zero_df = (self.data_df==0).apply(lambda x: x.value_counts()).sum(axis=1)\n d['table_density'] = float(zero_df[False]) / zero_df.sum()\n\n sample_sums_df = self.data_df.sum()\n d['sample_counts'] = sample_sums_df.sort_values().to_string()\n\n sample_stats_df = sample_sums_df.describe()\n\n d['min_sample'] = sample_stats_df['min']\n d['max_sample'] = sample_stats_df['max']\n d['mean_sample'] = sample_stats_df['mean']\n d['median_sample'] = sample_stats_df['50%']\n d['std_sample'] = sample_stats_df['std']\n\n if as_dict:\n return d\n else:\n return desc.format(**d)\n \n def describe(self):\n print(self.description())\n \n def compare(self, other_exp):\n self_desc = self.describe(as_dict=True)\n other_desc = other_exp.describe(as_dict=True)\n\n df_dict = OrderedDict()\n df_dict['self'] = self_desc\n df_dict['other'] = other_desc\n\n return DataFrame(df_dict)\n" ]
[ [ "pandas.DataFrame" ] ]
endremborza/parquetranger
[ "993845c78b6d8948f02bd259db08f63c3004a99e" ]
[ "parquetranger/tests/test_diff_cols.py" ]
[ "import pandas as pd\nimport pytest\n\nfrom parquetranger import TableRepo\n\n\[email protected](\n [\"indices\"],\n [\n (None,),\n (pd.Series([1, 2], name=\"fing\"),),\n (pd.MultiIndex.from_product([[\"A\", \"C\"], [1]], names=[\"ix\", \"iy\"]),),\n ],\n)\ndef test_diff_cols(tmp_path, indices):\n\n _df1 = pd.DataFrame({\"A\": [1, 2], \"C\": [\"g1\", \"g1\"]}, index=indices)\n _df2 = pd.DataFrame({\"B\": [1, 2], \"C\": [\"g2\", \"g2\"]}, index=indices)\n\n trepo = TableRepo(\n tmp_path / \"diffcols\", group_cols=\"C\", ensure_same_cols=True\n )\n trepo.extend(_df1)\n trepo.extend(_df2)\n\n df = trepo.get_full_df()\n assert _df1.columns.union(_df2.columns).isin(df.columns).all()\n\n\ndef test_diff_schema(tmp_path):\n\n _df1 = pd.DataFrame({\"A\": [1, 2], \"C\": [\"g1\", \"g1\"]})\n _df2 = pd.DataFrame({\"A\": [1.2, 2.2], \"C\": [\"g2\", \"g2\"]})\n\n trepo = TableRepo(\n tmp_path / \"diffcols\", group_cols=\"C\", ensure_same_cols=True\n )\n trepo.extend(_df1)\n trepo.extend(_df2)\n\n df = trepo.get_full_df()\n assert _df1.columns.union(_df2.columns).isin(df.columns).all()\n" ]
[ [ "pandas.DataFrame", "pandas.MultiIndex.from_product", "pandas.Series" ] ]
dekura/OpenPCDet
[ "5ee5bebcba78615ad07db81dbd7968a625066213" ]
[ "pcdet/datasets/augmentor/database_sampler.py" ]
[ "import pickle\n\nimport numpy as np\n\nfrom ...ops.iou3d_nms import iou3d_nms_utils\nfrom ...utils import box_utils\n\n\nclass DataBaseSampler(object):\n def __init__(self, root_path, sampler_cfg, class_names, logger=None):\n self.root_path = root_path\n self.class_names = class_names\n self.sampler_cfg = sampler_cfg\n self.logger = logger\n self.db_infos = {}\n for class_name in class_names:\n self.db_infos[class_name] = []\n\n for db_info_path in sampler_cfg.DB_INFO_PATH:\n db_info_path = self.root_path.resolve() / db_info_path\n with open(str(db_info_path), 'rb') as f:\n infos = pickle.load(f)\n [self.db_infos[cur_class].extend(infos[cur_class]) for cur_class in class_names]\n\n for func_name, val in sampler_cfg.PREPARE.items():\n self.db_infos = getattr(self, func_name)(self.db_infos, val)\n\n self.sample_groups = {}\n self.sample_class_num = {}\n self.limit_whole_scene = sampler_cfg.get('LIMIT_WHOLE_SCENE', False)\n for x in sampler_cfg.SAMPLE_GROUPS:\n class_name, sample_num = x.split(':')\n if class_name not in class_names:\n continue\n self.sample_class_num[class_name] = sample_num\n self.sample_groups[class_name] = {\n 'sample_num': sample_num,\n 'pointer': len(self.db_infos[class_name]),\n 'indices': np.arange(len(self.db_infos[class_name]))\n }\n\n def __getstate__(self):\n d = dict(self.__dict__)\n del d['logger']\n return d\n\n def __setstate__(self, d):\n self.__dict__.update(d)\n\n def filter_by_difficulty(self, db_infos, removed_difficulty):\n new_db_infos = {}\n for key, dinfos in db_infos.items():\n pre_len = len(dinfos)\n new_db_infos[key] = [\n info for info in dinfos\n if info['difficulty'] not in removed_difficulty\n ]\n if self.logger is not None:\n self.logger.info('Database filter by difficulty %s: %d => %d' % (key, pre_len, len(new_db_infos[key])))\n return new_db_infos\n\n def filter_by_min_points(self, db_infos, min_gt_points_list):\n for name_num in min_gt_points_list:\n name, min_num = name_num.split(':')\n min_num = int(min_num)\n # print(db_infos)\n if min_num > 0 and name in db_infos.keys():\n filtered_infos = []\n for info in db_infos[name]:\n print('num_points_in_gt: ', info['num_points_in_gt'])\n if info['num_points_in_gt'] >= min_num:\n filtered_infos.append(info)\n\n if self.logger is not None:\n self.logger.info('Database filter by min points %s: %d => %d' %\n (name, len(db_infos[name]), len(filtered_infos)))\n db_infos[name] = filtered_infos\n\n return db_infos\n\n def sample_with_fixed_number(self, class_name, sample_group):\n \"\"\"\n Args:\n class_name:\n sample_group:\n Returns:\n\n \"\"\"\n sample_num, pointer, indices = int(sample_group['sample_num']), sample_group['pointer'], sample_group['indices']\n # print(self.db_infos)\n if pointer >= len(self.db_infos[class_name]):\n indices = np.random.permutation(len(self.db_infos[class_name]))\n pointer = 0\n\n sampled_dict = [self.db_infos[class_name][idx] for idx in indices[pointer: pointer + sample_num]]\n pointer += sample_num\n sample_group['pointer'] = pointer\n sample_group['indices'] = indices\n return sampled_dict\n\n @staticmethod\n def put_boxes_on_road_planes(gt_boxes, road_planes, calib):\n \"\"\"\n Only validate in KITTIDataset\n Args:\n gt_boxes: (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...]\n road_planes: [a, b, c, d]\n calib:\n\n Returns:\n \"\"\"\n a, b, c, d = road_planes\n center_cam = calib.lidar_to_rect(gt_boxes[:, 0:3])\n cur_height_cam = (-d - a * center_cam[:, 0] - c * center_cam[:, 2]) / b\n center_cam[:, 1] = cur_height_cam\n cur_lidar_height = calib.rect_to_lidar(center_cam)[:, 2]\n mv_height = gt_boxes[:, 2] - gt_boxes[:, 5] / 2 - cur_lidar_height\n gt_boxes[:, 2] -= mv_height # lidar view\n return gt_boxes, mv_height\n\n def add_sampled_boxes_to_scene(self, data_dict, sampled_gt_boxes, total_valid_sampled_dict):\n gt_boxes_mask = data_dict['gt_boxes_mask']\n gt_boxes = data_dict['gt_boxes'][gt_boxes_mask]\n gt_names = data_dict['gt_names'][gt_boxes_mask]\n points = data_dict['points']\n if self.sampler_cfg.get('USE_ROAD_PLANE', False):\n sampled_gt_boxes, mv_height = self.put_boxes_on_road_planes(\n sampled_gt_boxes, data_dict['road_plane'], data_dict['calib']\n )\n data_dict.pop('calib')\n data_dict.pop('road_plane')\n\n obj_points_list = []\n for idx, info in enumerate(total_valid_sampled_dict):\n file_path = self.root_path / info['path']\n obj_points = np.fromfile(str(file_path), dtype=np.float32).reshape(\n [-1, self.sampler_cfg.NUM_POINT_FEATURES])\n\n obj_points[:, :3] += info['box3d_lidar'][:3]\n\n if self.sampler_cfg.get('USE_ROAD_PLANE', False):\n # mv height\n obj_points[:, 2] -= mv_height[idx]\n\n obj_points_list.append(obj_points)\n\n obj_points = np.concatenate(obj_points_list, axis=0)\n sampled_gt_names = np.array([x['name'] for x in total_valid_sampled_dict])\n\n large_sampled_gt_boxes = box_utils.enlarge_box3d(\n sampled_gt_boxes[:, 0:7], extra_width=self.sampler_cfg.REMOVE_EXTRA_WIDTH\n )\n points = box_utils.remove_points_in_boxes3d(points, large_sampled_gt_boxes)\n points = np.concatenate([obj_points, points], axis=0)\n gt_names = np.concatenate([gt_names, sampled_gt_names], axis=0)\n gt_boxes = np.concatenate([gt_boxes, sampled_gt_boxes], axis=0)\n data_dict['gt_boxes'] = gt_boxes\n data_dict['gt_names'] = gt_names\n data_dict['points'] = points\n return data_dict\n\n def __call__(self, data_dict):\n \"\"\"\n Args:\n data_dict:\n gt_boxes: (N, 7 + C) [x, y, z, dx, dy, dz, heading, ...]\n\n Returns:\n\n \"\"\"\n gt_boxes = data_dict['gt_boxes']\n gt_names = data_dict['gt_names'].astype(str)\n existed_boxes = gt_boxes\n total_valid_sampled_dict = []\n for class_name, sample_group in self.sample_groups.items():\n if self.limit_whole_scene:\n num_gt = np.sum(class_name == gt_names)\n sample_group['sample_num'] = str(int(self.sample_class_num[class_name]) - num_gt)\n if int(sample_group['sample_num']) > 0:\n # print(class_name)\n # print(sample_group)\n sampled_dict = self.sample_with_fixed_number(class_name, sample_group)\n # print(sampled_dict)\n sampled_boxes = np.stack([x['box3d_lidar'] for x in sampled_dict], axis=0).astype(np.float32)\n\n if self.sampler_cfg.get('DATABASE_WITH_FAKELIDAR', False):\n sampled_boxes = box_utils.boxes3d_kitti_fakelidar_to_lidar(sampled_boxes)\n\n iou1 = iou3d_nms_utils.boxes_bev_iou_cpu(sampled_boxes[:, 0:7], existed_boxes[:, 0:7])\n iou2 = iou3d_nms_utils.boxes_bev_iou_cpu(sampled_boxes[:, 0:7], sampled_boxes[:, 0:7])\n iou2[range(sampled_boxes.shape[0]), range(sampled_boxes.shape[0])] = 0\n iou1 = iou1 if iou1.shape[1] > 0 else iou2\n valid_mask = ((iou1.max(axis=1) + iou2.max(axis=1)) == 0).nonzero()[0]\n valid_sampled_dict = [sampled_dict[x] for x in valid_mask]\n valid_sampled_boxes = sampled_boxes[valid_mask]\n\n existed_boxes = np.concatenate((existed_boxes, valid_sampled_boxes), axis=0)\n total_valid_sampled_dict.extend(valid_sampled_dict)\n\n sampled_gt_boxes = existed_boxes[gt_boxes.shape[0]:, :]\n if total_valid_sampled_dict.__len__() > 0:\n data_dict = self.add_sampled_boxes_to_scene(data_dict, sampled_gt_boxes, total_valid_sampled_dict)\n\n data_dict.pop('gt_boxes_mask')\n return data_dict\n" ]
[ [ "numpy.concatenate", "numpy.sum", "numpy.array", "numpy.stack" ] ]
vipulsinghal02/starfish
[ "c3d347954ad40a7a4be9a50d89974f5fbbc2919d" ]
[ "starfish/test/image/test_imagestack.py" ]
[ "import numpy as np\nimport pytest\n\nfrom starfish.imagestack.imagestack import ImageStack\nfrom starfish.intensity_table import IntensityTable\n# don't inspect pytest fixtures in pycharm\n# noinspection PyUnresolvedReferences\nfrom starfish.test.dataset_fixtures import ( # noqa: F401\n codebook_intensities_image_for_single_synthetic_spot,\n loaded_codebook,\n simple_codebook_array,\n simple_codebook_json,\n synthetic_dataset_with_truth_values,\n synthetic_intensity_table,\n synthetic_spot_pass_through_stack,\n)\nfrom starfish.types import Indices\n\n\ndef test_get_slice_simple_index():\n \"\"\"\n Retrieve a slice across one of the indices at the end. For instance, if the dimensions are\n (P, Q0,..., Qn-1, R), slice across either P or R.\n \"\"\"\n stack = ImageStack.synthetic_stack()\n round_ = 1\n imageslice, axes = stack.get_slice(\n {Indices.ROUND: round_}\n )\n assert axes == [Indices.CH, Indices.Z]\n\n y, x = stack.tile_shape\n\n for ch in range(stack.shape[Indices.CH]):\n for z in range(stack.shape[Indices.Z]):\n data = np.empty((y, x))\n data.fill((round_ * stack.shape[Indices.CH] + ch) * stack.shape[Indices.Z] + z)\n\n assert data.all() == imageslice[ch, z].all()\n\n\ndef test_get_slice_middle_index():\n \"\"\"\n Retrieve a slice across one of the indices in the middle. For instance, if the dimensions are\n (P, Q0,..., Qn-1, R), slice across one of the Q axes.\n \"\"\"\n stack = ImageStack.synthetic_stack()\n ch = 1\n imageslice, axes = stack.get_slice(\n {Indices.CH: ch}\n )\n assert axes == [Indices.ROUND, Indices.Z]\n\n y, x = stack.tile_shape\n\n for round_ in range(stack.shape[Indices.ROUND]):\n for z in range(stack.shape[Indices.Z]):\n data = np.empty((y, x))\n data.fill((round_ * stack.shape[Indices.CH] + ch) * stack.shape[Indices.Z] + z)\n\n assert data.all() == imageslice[round_, z].all()\n\n\ndef test_get_slice_range():\n \"\"\"\n Retrieve a slice across a range of one of the dimensions.\n \"\"\"\n stack = ImageStack.synthetic_stack()\n zrange = slice(1, 3)\n imageslice, axes = stack.get_slice(\n {Indices.Z: zrange}\n )\n y, x = stack.tile_shape\n assert axes == [Indices.ROUND, Indices.CH, Indices.Z]\n\n for round_ in range(stack.shape[Indices.ROUND]):\n for ch in range(stack.shape[Indices.CH]):\n for z in range(zrange.stop - zrange.start):\n data = np.empty((y, x))\n data.fill((round_ * stack.shape[Indices.CH] + ch) * stack.shape[Indices.Z] +\n (z + zrange.start))\n\n assert data.all() == imageslice[round_, ch, z].all()\n\n\ndef test_set_slice_simple_index():\n \"\"\"\n Sets a slice across one of the indices at the end. For instance, if the dimensions are\n (P, Q0,..., Qn-1, R), sets a slice across either P or R.\n \"\"\"\n stack = ImageStack.synthetic_stack()\n round_ = 1\n y, x = stack.tile_shape\n\n expected = np.full(\n (stack.shape[Indices.CH], stack.shape[Indices.Z], y, x),\n fill_value=0.5,\n dtype=np.float32\n )\n index = {Indices.ROUND: round_}\n\n stack.set_slice(index, expected)\n\n assert np.array_equal(stack.get_slice(index)[0], expected)\n\n\ndef test_set_slice_middle_index():\n \"\"\"\n Sets a slice across one of the indices in the middle. For instance, if the dimensions are\n (P, Q0,..., Qn-1, R), slice across one of the Q axes.\n \"\"\"\n stack = ImageStack.synthetic_stack()\n ch = 1\n y, x = stack.tile_shape\n\n expected = np.full(\n (stack.shape[Indices.ROUND], stack.shape[Indices.Z], y, x),\n fill_value=0.5,\n dtype=np.float32\n )\n index = {Indices.CH: ch}\n\n stack.set_slice(index, expected)\n\n assert np.array_equal(stack.get_slice(index)[0], expected)\n\n\ndef test_set_slice_range():\n \"\"\"\n Sets a slice across a range of one of the dimensions.\n \"\"\"\n stack = ImageStack.synthetic_stack()\n zrange = slice(1, 3)\n y, x = stack.tile_shape\n\n expected = np.full(\n (stack.shape[Indices.ROUND], stack.shape[Indices.CH], zrange.stop - zrange.start, y, x),\n fill_value=0.5,\n dtype=np.float32\n )\n index = {Indices.Z: zrange}\n\n stack.set_slice(index, expected)\n\n assert np.array_equal(stack.get_slice(index)[0], expected)\n\n\ndef test_from_numpy_array_raises_error_when_incorrect_dims_passed():\n array = np.ones((2, 2), dtype=np.float32)\n # verify this method works with the correct shape\n image = ImageStack.from_numpy_array(array.reshape((1, 1, 1, 2, 2)))\n assert isinstance(image, ImageStack)\n\n with pytest.raises(ValueError):\n ImageStack.from_numpy_array(array.reshape((1, 1, 2, 2)))\n ImageStack.from_numpy_array(array.reshape((1, 2, 2)))\n ImageStack.from_numpy_array(array)\n ImageStack.from_numpy_array(array.reshape((1, 1, 1, 1, 2, 2)))\n\n\ndef test_from_numpy_array_automatically_handles_float_conversions():\n x = np.zeros((1, 1, 1, 20, 20), dtype=np.uint16)\n stack = ImageStack.from_numpy_array(x)\n assert stack.numpy_array.dtype == np.float32\n\n\ndef test_max_projection_preserves_dtype():\n original_dtype = np.float32\n array = np.ones((2, 2, 2), dtype=original_dtype)\n image = ImageStack.from_numpy_array(array.reshape((1, 1, 2, 2, 2)))\n\n max_projection = image.max_proj(Indices.CH, Indices.ROUND, Indices.Z)\n assert max_projection.dtype == original_dtype\n\n\ndef test_synthetic_spot_creation_raises_error_with_coords_too_small(synthetic_intensity_table):\n num_z = 0\n height = 40\n width = 50\n with pytest.raises(ValueError):\n ImageStack.synthetic_spots(synthetic_intensity_table, num_z, height, width)\n\n\ndef test_synthetic_spot_creation_produces_an_imagestack(synthetic_intensity_table):\n num_z = 12\n height = 50\n width = 40\n image = ImageStack.synthetic_spots(synthetic_intensity_table, num_z, height, width)\n assert isinstance(image, ImageStack)\n\n\ndef test_synthetic_spot_creation_produces_an_imagestack_with_correct_spot_location(\n synthetic_spot_pass_through_stack):\n\n codebook, true_intensities, image = synthetic_spot_pass_through_stack\n\n g, c, r = np.where(true_intensities.values)\n\n x = np.empty_like(g)\n y = np.empty_like(g)\n z = np.empty_like(g)\n breaks = np.concatenate([\n np.array([0]),\n np.where(np.diff(g))[0] + 1,\n np.array([g.shape[0]])\n ])\n for i in np.arange(len(breaks) - 1):\n x[breaks[i]: breaks[i + 1]] = true_intensities.coords[Indices.X.value][i]\n y[breaks[i]: breaks[i + 1]] = true_intensities.coords[Indices.Y.value][i]\n z[breaks[i]: breaks[i + 1]] = true_intensities.coords[Indices.Z.value][i]\n\n # only 8 values should be set, since there are only 8 locations across the tensor\n assert np.sum(image.numpy_array != 0) == 8\n\n assert np.allclose(\n image.numpy_array[r, c, z, y, x],\n true_intensities.values[np.where(true_intensities)])\n\n\n# TODO ambrosejcarr: improve the tests here.\ndef test_imagestack_to_intensity_table():\n codebook, intensity_table, image = codebook_intensities_image_for_single_synthetic_spot()\n pixel_intensities = IntensityTable.from_image_stack(image)\n pixel_intensities = codebook.metric_decode(\n pixel_intensities, max_distance=0, min_intensity=1000, norm_order=2)\n assert isinstance(pixel_intensities, IntensityTable)\n\n\ndef test_imagestack_to_intensity_table_no_noise(synthetic_spot_pass_through_stack):\n codebook, intensity_table, image = synthetic_spot_pass_through_stack\n pixel_intensities = IntensityTable.from_image_stack(image)\n pixel_intensities = codebook.metric_decode(\n pixel_intensities, max_distance=0, min_intensity=1000, norm_order=2)\n assert isinstance(pixel_intensities, IntensityTable)\n" ]
[ [ "numpy.full", "numpy.array", "numpy.empty", "numpy.zeros", "numpy.sum", "numpy.ones", "numpy.diff", "numpy.where", "numpy.empty_like" ] ]
Phimos/PKU-Pattern-Recognition-2021-Fall
[ "be2c59710ec956437d237c306a5fe74b15f6618d" ]
[ "plot.py" ]
[ "# %%\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.arange(-1, 5, 0.01)\nfx = 1 * np.abs(x - 0) - 1 * np.abs(x-3) + 1 * np.abs(x - 4)\nplt.plot(x, fx)\nplt.title(\"$f(x)$\")\n\nplt.savefig(\"plot.png\", dpi=300)\n\n# %%\n\nx = np.arange(-1, 5, 0.01)\nb1x = -1/24 * np.abs(x - 0) + 1/6 * np.abs(x-3) + 1 / 8 * np.abs(x - 4)\nb2x = 1/6 * np.abs(x-0) - 2/3 * np.abs(x-3) + 1 / 2 * np.abs(x - 4)\nb3x = 1/8 * np.abs(x-0) + 1/2 * np.abs(x-3) - 3 / 8 * np.abs(x - 4)\nplt.plot(x, b1x)\nplt.plot(x, b2x)\nplt.plot(x, b3x)\nplt.title(\"$f(x)$\")\n\n# %%\nplt.plot(x, 1*b1x+4*b2x+3*b3x)\n# %%\nplt.plot(x, 1*b1x, label=\"$y_1 b_1(x)$\")\nplt.plot(x, 4*b2x, label=\"$y_2 b_2(x)$\")\nplt.plot(x, 3*b3x, label=\"$y_3 b_3(x)$\")\nplt.legend()\nplt.title(\"$y_i b_i(x)$\")\nplt.savefig(\"plot.png\", dpi=300)\n# %%\n" ]
[ [ "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "matplotlib.pyplot.title", "numpy.arange", "numpy.abs" ] ]
vinhtruongtrong/aspect-based-sentiment-analysis-for-vietnamese-text-using-bert
[ "f4908e6a47dd176671b38d58cb49f189b6f9bc45" ]
[ "run_classifier_TABSA.py" ]
[ "# coding=utf-8\n\n\"\"\"BERT finetuning runner.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport argparse\nimport collections\nimport logging\nimport os\nimport random\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom torch.utils.data.distributed import DistributedSampler\nfrom torch.utils.data.sampler import RandomSampler, SequentialSampler\nfrom tqdm import tqdm, trange\n\nimport tokenization\nfrom modeling import BertConfig, BertForSequenceClassification\nfrom optimization import BERTAdam\nfrom processor import (VLSP_2018_single_Processor, VLSP_2018_QA_M_Processor, VLSP_2018_QA_B_Processor, VLSP_2018_NLI_M_Processor, VLSP_2018_NLI_B_Processor)\n\nlogging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s', \n datefmt = '%m/%d/%Y %H:%M:%S',\n level = logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self, input_ids, input_mask, segment_ids, label_id):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.label_id = label_id\n\n\ndef convert_examples_to_features(examples, label_list, max_seq_length, tokenizer):\n \"\"\"Loads a data file into a list of `InputBatch`s.\"\"\"\n\n label_map = {}\n for (i, label) in enumerate(label_list):\n label_map[label] = i\n\n features = []\n for (ex_index, example) in enumerate(tqdm(examples)):\n tokens_a = tokenizer.tokenize(example.text_a)\n\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n\n if tokens_b:\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[0:(max_seq_length - 2)]\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambigiously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = []\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in tokens_a:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n if tokens_b:\n for token in tokens_b:\n tokens.append(token)\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n label_id = label_map[example.label]\n\n features.append(\n InputFeatures(\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id))\n return features\n\n\ndef _truncate_seq_pair(tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n ## Required parameters\n parser.add_argument(\"--task_name\",\n default=None,\n type=str,\n required=True,\n choices=[\"vlsp_2018_single\", \\\n \"vlsp_2018_NLI_M\", \"vlsp_2018_QA_M\", \"vlsp_2018_NLI_B\", \"vlsp_2018_QA_B\"],\n help=\"The name of the task to train.\")\n parser.add_argument(\"--data_dir\",\n default=None,\n type=str,\n required=True,\n help=\"The input data dir. Should contain the .tsv files (or other data files) for the task.\")\n parser.add_argument(\"--vocab_file\",\n default=None,\n type=str,\n required=True,\n help=\"The vocabulary file that the BERT model was trained on.\")\n parser.add_argument(\"--bert_config_file\",\n default=None,\n type=str,\n required=True,\n help=\"The config json file corresponding to the pre-trained BERT model. \\n\"\n \"This specifies the model architecture.\")\n parser.add_argument(\"--output_dir\",\n default=None,\n type=str,\n required=True,\n help=\"The output directory where the model checkpoints will be written.\")\n parser.add_argument(\"--init_checkpoint\",\n default=None,\n type=str,\n required=True,\n help=\"Initial checkpoint (usually from a pre-trained BERT model).\")\n \n ## Other parameters\n parser.add_argument(\"--do_save_model\",\n default=False,\n action='store_true',\n help=\"Whether to save checkpoint.\")\n parser.add_argument(\"--eval_test\",\n default=False,\n action='store_true',\n help=\"Whether to run eval on the test set.\") \n parser.add_argument(\"--do_lower_case\",\n default=False,\n action='store_true',\n help=\"Whether to lower case the input text. True for uncased models, False for cased models.\")\n parser.add_argument(\"--max_seq_length\",\n default=128,\n type=int,\n help=\"The maximum total input sequence length after WordPiece tokenization. \\n\"\n \"Sequences longer than this will be truncated, and sequences shorter \\n\"\n \"than this will be padded.\")\n parser.add_argument(\"--train_batch_size\",\n default=32,\n type=int,\n help=\"Total batch size for training.\")\n parser.add_argument(\"--eval_batch_size\",\n default=8,\n type=int,\n help=\"Total batch size for eval.\")\n parser.add_argument(\"--learning_rate\",\n default=5e-5,\n type=float,\n help=\"The initial learning rate for Adam.\")\n parser.add_argument(\"--num_train_epochs\",\n default=3.0,\n type=float,\n help=\"Total number of training epochs to perform.\")\n parser.add_argument(\"--warmup_proportion\",\n default=0.1,\n type=float,\n help=\"Proportion of training to perform linear learning rate warmup for. \"\n \"E.g., 0.1 = 10%% of training.\")\n parser.add_argument(\"--no_cuda\",\n default=False,\n action='store_true',\n help=\"Whether not to use CUDA when available\")\n parser.add_argument(\"--accumulate_gradients\",\n type=int,\n default=1,\n help=\"Number of steps to accumulate gradient on (divide the batch_size and accumulate)\")\n parser.add_argument(\"--local_rank\",\n type=int,\n default=-1,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument('--seed', \n type=int, \n default=42,\n help=\"random seed for initialization\")\n parser.add_argument('--gradient_accumulation_steps',\n type=int,\n default=1,\n help=\"Number of updates steps to accumualte before performing a backward/update pass.\") \n args = parser.parse_args()\n\n\n if args.local_rank == -1 or args.no_cuda:\n device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\")\n n_gpu = torch.cuda.device_count()\n else:\n device = torch.device(\"cuda\", args.local_rank)\n n_gpu = 1\n # Initializes the distributed backend which will take care of sychronizing nodes/GPUs\n torch.distributed.init_process_group(backend='nccl')\n logger.info(\"device %s n_gpu %d distributed training %r\", device, n_gpu, bool(args.local_rank != -1))\n\n if args.accumulate_gradients < 1:\n raise ValueError(\"Invalid accumulate_gradients parameter: {}, should be >= 1\".format(\n args.accumulate_gradients))\n\n args.train_batch_size = int(args.train_batch_size / args.accumulate_gradients)\n\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n bert_config = BertConfig.from_json_file(args.bert_config_file)\n\n if args.max_seq_length > bert_config.max_position_embeddings:\n raise ValueError(\n \"Cannot use sequence length {} because the BERT model was only trained up to sequence length {}\".format(\n args.max_seq_length, bert_config.max_position_embeddings))\n\n if os.path.exists(args.output_dir) and os.listdir(args.output_dir):\n raise ValueError(\"Output directory ({}) already exists and is not empty.\".format(args.output_dir))\n os.makedirs(args.output_dir, exist_ok=True)\n\n\n # prepare dataloaders\n processors = {\n \"vlsp_2018_single\":VLSP_2018_single_Processor,\n \"vlsp_2018_NLI_M\":VLSP_2018_NLI_M_Processor,\n \"vlsp_2018_QA_M\":VLSP_2018_QA_M_Processor,\n \"vlsp_2018_NLI_B\":VLSP_2018_NLI_B_Processor,\n \"vlsp_2018_QA_B\":VLSP_2018_QA_B_Processor,\n }\n\n processor = processors[args.task_name]()\n label_list = processor.get_labels()\n\n tokenizer = tokenization.FullTokenizer(\n vocab_file=args.vocab_file, do_lower_case=args.do_lower_case)\n\n # training set\n train_examples = None\n num_train_steps = None\n train_examples = processor.get_train_examples(args.data_dir)\n num_train_steps = int(\n len(train_examples) / args.train_batch_size * args.num_train_epochs)\n\n train_features = convert_examples_to_features(\n train_examples, label_list, args.max_seq_length, tokenizer)\n logger.info(\"***** Running training *****\")\n logger.info(\" Num examples = %d\", len(train_examples))\n logger.info(\" Batch size = %d\", args.train_batch_size)\n logger.info(\" Num steps = %d\", num_train_steps)\n\n all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)\n all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long)\n all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long)\n all_label_ids = torch.tensor([f.label_id for f in train_features], dtype=torch.long)\n\n train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)\n if args.local_rank == -1:\n train_sampler = RandomSampler(train_data)\n else:\n train_sampler = DistributedSampler(train_data)\n train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size)\n\n\n #dev set\n dev_examples = processor.get_dev_examples(args.data_dir)\n dev_features = convert_examples_to_features(\n dev_examples, label_list, args.max_seq_length, tokenizer)\n \n all_dev_input_ids = torch.tensor([f.input_ids for f in dev_features], dtype=torch.long)\n all_dev_input_mask = torch.tensor([f.input_mask for f in dev_features], dtype=torch.long)\n all_dev_segment_ids = torch.tensor([f.segment_ids for f in dev_features], dtype=torch.long)\n all_dev_label_ids = torch.tensor([f.label_id for f in dev_features], dtype=torch.long)\n\n dev_data = TensorDataset(all_dev_input_ids, all_dev_input_mask, all_dev_segment_ids, all_dev_label_ids)\n dev_dataloader = DataLoader(dev_data, batch_size=args.eval_batch_size, shuffle=False)\n\n # test set\n if args.eval_test:\n test_examples = processor.get_test_examples(args.data_dir)\n test_features = convert_examples_to_features(\n test_examples, label_list, args.max_seq_length, tokenizer)\n\n all_input_ids = torch.tensor([f.input_ids for f in test_features], dtype=torch.long)\n all_input_mask = torch.tensor([f.input_mask for f in test_features], dtype=torch.long)\n all_segment_ids = torch.tensor([f.segment_ids for f in test_features], dtype=torch.long)\n all_label_ids = torch.tensor([f.label_id for f in test_features], dtype=torch.long)\n\n test_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)\n test_dataloader = DataLoader(test_data, batch_size=args.eval_batch_size, shuffle=False)\n\n\n # model and optimizer\n model = BertForSequenceClassification(bert_config, len(label_list))\n if args.init_checkpoint is not None:\n model.bert.load_state_dict(torch.load(args.init_checkpoint, map_location='cpu'))\n model.to(device)\n\n if args.local_rank != -1:\n model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],\n output_device=args.local_rank)\n elif n_gpu > 1:\n model = torch.nn.DataParallel(model)\n\n no_decay = ['bias', 'gamma', 'beta']\n optimizer_parameters = [\n {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay_rate': 0.01},\n {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay_rate': 0.0}\n ]\n\t\t\n optimizer = BERTAdam(optimizer_parameters,\n lr=args.learning_rate,\n warmup=args.warmup_proportion,\n t_total=num_train_steps)\n\n\n # train\n output_log_file = os.path.join(args.output_dir, \"log.txt\")\n print(\"output_log_file=\",output_log_file)\n with open(output_log_file, \"w\") as writer:\n if args.eval_test:\n writer.write(\"epoch\\tglobal_step\\tloss\\tdev_loss\\tdev_accuracy\\ttest_loss\\ttest_accuracy\\n\")\n else:\n writer.write(\"epoch\\tglobal_step\\tloss\\n\")\n \n global_step = 0\n epoch=0\n for _ in trange(int(args.num_train_epochs), desc=\"Epoch\"):\n epoch+=1\n model.train()\n tr_loss = 0\n nb_tr_examples, nb_tr_steps = 0, 0\n for step, batch in enumerate(tqdm(train_dataloader, desc=\"Iteration\")):\n batch = tuple(t.to(device) for t in batch)\n input_ids, input_mask, segment_ids, label_ids = batch\n loss, _ = model(input_ids, segment_ids, input_mask, label_ids)\n if n_gpu > 1:\n loss = loss.mean() # mean() to average on multi-gpu.\n if args.gradient_accumulation_steps > 1:\n loss = loss / args.gradient_accumulation_steps\n loss.backward()\n tr_loss += loss.item()\n nb_tr_examples += input_ids.size(0)\n nb_tr_steps += 1\n if (step + 1) % args.gradient_accumulation_steps == 0:\n optimizer.step() # We have accumulated enought gradients\n model.zero_grad()\n global_step += 1\n \n if(args.do_save_model):\n if(n_gpu > 1):\n torch.save(model.module.state_dict(), os.path.join(args.output_dir, 'model_ep' + str(epoch) + '.bin'))\n else:\n torch.save(model.state_dict(), os.path.join(args.output_dir, 'model_ep' + str(epoch) + '.bin'))\n\n #dev eval\n model.eval()\n dev_loss, dev_accuracy = 0, 0\n nb_dev_steps, nb_dev_examples = 0, 0\n with open(os.path.join(args.output_dir, \"dev_ep_\"+str(epoch)+\".txt\"),\"w\") as f_dev:\n for input_ids, input_mask, segment_ids, label_ids in dev_dataloader:\n input_ids = input_ids.to(device)\n input_mask = input_mask.to(device)\n segment_ids = segment_ids.to(device)\n label_ids = label_ids.to(device)\n\n with torch.no_grad():\n tmp_dev_test_loss, logits = model(input_ids, segment_ids, input_mask, label_ids)\n\n logits = F.softmax(logits, dim=-1)\n logits = logits.detach().cpu().numpy()\n label_ids = label_ids.to('cpu').numpy()\n outputs = np.argmax(logits, axis=1)\n for output_i in range(len(outputs)):\n f_dev.write(str(outputs[output_i]))\n for ou in logits[output_i]:\n f_dev.write(\" \"+str(ou))\n f_dev.write(\"\\n\")\n tmp_dev_accuracy=np.sum(outputs == label_ids)\n\n dev_loss += tmp_dev_test_loss.mean().item()\n dev_accuracy += tmp_dev_accuracy\n\n nb_dev_examples += input_ids.size(0)\n nb_dev_steps += 1\n\n dev_loss = dev_loss / nb_dev_steps\n dev_accuracy = dev_accuracy / nb_dev_examples\n\n # eval_test\n if args.eval_test:\n model.eval()\n test_loss, test_accuracy = 0, 0\n nb_test_steps, nb_test_examples = 0, 0\n with open(os.path.join(args.output_dir, \"test_ep_\"+str(epoch)+\".txt\"),\"w\") as f_test:\n for input_ids, input_mask, segment_ids, label_ids in test_dataloader:\n input_ids = input_ids.to(device)\n input_mask = input_mask.to(device)\n segment_ids = segment_ids.to(device)\n label_ids = label_ids.to(device)\n\n with torch.no_grad():\n tmp_test_loss, logits = model(input_ids, segment_ids, input_mask, label_ids)\n\n logits = F.softmax(logits, dim=-1)\n logits = logits.detach().cpu().numpy()\n label_ids = label_ids.to('cpu').numpy()\n outputs = np.argmax(logits, axis=1)\n for output_i in range(len(outputs)):\n f_test.write(str(outputs[output_i]))\n for ou in logits[output_i]:\n f_test.write(\" \"+str(ou))\n f_test.write(\"\\n\")\n tmp_test_accuracy=np.sum(outputs == label_ids)\n\n test_loss += tmp_test_loss.mean().item()\n test_accuracy += tmp_test_accuracy\n\n nb_test_examples += input_ids.size(0)\n nb_test_steps += 1\n\n test_loss = test_loss / nb_test_steps\n test_accuracy = test_accuracy / nb_test_examples\n\n\n result = collections.OrderedDict()\n if args.eval_test:\n result = {'epoch': epoch,\n 'global_step': global_step,\n 'loss': tr_loss/nb_tr_steps,\n 'dev_loss': dev_loss,\n 'dev_accuracy': dev_accuracy,\n 'test_loss': test_loss,\n 'test_accuracy': test_accuracy}\n else:\n result = {'epoch': epoch,\n 'global_step': global_step,\n 'loss': tr_loss/nb_tr_steps}\n\n logger.info(\"***** Eval results *****\")\n with open(output_log_file, \"a+\") as writer:\n for key in result.keys():\n logger.info(\" %s = %s\\n\", key, str(result[key]))\n writer.write(\"%s\\t\" % (str(result[key])))\n writer.write(\"\\n\")\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "torch.cuda.is_available", "torch.load", "torch.nn.DataParallel", "torch.utils.data.sampler.RandomSampler", "torch.distributed.init_process_group", "torch.manual_seed", "torch.tensor", "torch.utils.data.DataLoader", "numpy.argmax", "torch.device", "torch.cuda.manual_seed_all", "torch.nn.parallel.DistributedDataParallel", "torch.cuda.device_count", "torch.nn.functional.softmax", "torch.utils.data.TensorDataset", "numpy.random.seed", "numpy.sum", "torch.no_grad", "torch.utils.data.distributed.DistributedSampler" ] ]
francotheengineer/autokeras
[ "eac91bad8a90f78a68933992cc1ff4b7df4ee30f" ]
[ "autokeras/pretrained/voice_generator/voice_generator.py" ]
[ "import os\n\nimport numpy as np\nimport torch\nimport lws\nfrom scipy import signal\n\nfrom autokeras.pretrained.base import Pretrained\nfrom autokeras.constant import Constant\nfrom autokeras.utils import temp_path_generator, ensure_dir, get_device\nimport librosa\n\nfrom autokeras.pretrained.voice_generator.deepvoice3_pytorch import frontend, builder\n\nfrom autokeras.pretrained.voice_generator.google_drive_download import GoogleDriveDownloader as gdd\n\n\n# NOTE: If you want full control for model architecture. please take a look\n# at the code and change whatever you want. Some hyper parameters are hardcoded.\n\n# Default hyperparameters:\n\nclass Hparams:\n name = \"deepvoice3\"\n\n # Text:\n # [en jp]\n frontend = 'en'\n\n # Replace words to its pronunciation with fixed probability.\n # e.g. 'hello' to 'HH AH0 L OW1'\n # [en jp]\n # en: Word -> pronunciation using CMUDict\n # jp: Word -> pronounciation usnig MeCab\n # [0 ~ 1.0]: 0 means no replacement happens.\n replace_pronunciation_prob = 0.5\n\n # Convenient model builder\n # Definitions can be found at deepvoice3_pytorch/builder.py\n # deepvoice3: DeepVoice3 https://arxiv.org/abs/1710.07654\n builder = \"deepvoice3\"\n\n # Must be configured depends on the dataset and model you use\n n_speakers = 1\n speaker_embed_dim = 16\n\n # Audio:\n num_mels = 80\n fmin = 125\n fmax = 7600\n fft_size = 1024\n hop_size = 256\n sample_rate = 22050\n preemphasis = 0.97\n min_level_db = -100\n ref_level_db = 20\n # whether to rescale waveform or not.\n # Let x is an input waveform rescaled waveform y is given by:\n # y = x / np.abs(x).max() * rescaling_max\n rescaling = False\n rescaling_max = 0.999\n # mel-spectrogram is normalized to [0 1] for each utterance and clipping may\n # happen depends on min_level_db and ref_level_db causing clipping noise.\n # If False assertion is added to ensure no clipping happens.\n allow_clipping_in_normalization = True\n\n # Model:\n downsample_step = 4 # must be 4 when builder=\"nyanko\"\n outputs_per_step = 1 # must be 1 when builder=\"nyanko\"\n embedding_weight_std = 0.1\n speaker_embedding_weight_std = 0.01\n padding_idx = 0\n # Maximum number of input text length\n # try setting larger value if you want to give very long text input\n max_positions = 512\n dropout = 1 - 0.95\n kernel_size = 3\n text_embed_dim = 128\n encoder_channels = 256\n decoder_channels = 256\n # Note: large converter channels requires significant computational cost\n converter_channels = 256\n query_position_rate = 1.0\n # can be computed by `compute_timestamp_ratio.py`.\n key_position_rate = 1.385 # 2.37 for jsut\n key_projection = False\n value_projection = False\n use_memory_mask = True\n trainable_positional_encodings = False\n freeze_embedding = False\n # If True use decoder's internal representation for postnet inputs\n # otherwise use mel-spectrogram.\n use_decoder_state_for_postnet_input = True\n\n # Data loader\n pin_memory = True\n num_workers = 2 # Set it to 1 when in Windows (MemoryError THAllocator.c 0x5)\n\n # Loss\n masked_loss_weight = 0.5 # (1-w)*loss + w * masked_loss\n priority_freq = 3000 # heuristic: priotrize [0 ~ priotiry_freq] for linear loss\n priority_freq_weight = 0.0 # (1-w)*linear_loss + w*priority_linear_loss\n # https://arxiv.org/pdf/1710.08969.pdf\n # Adding the divergence to the loss stabilizes training expecially for\n # very deep (> 10 layers) networks.\n # Binary div loss seems has approx 10x scale compared to L1 loss so I choose 0.1.\n binary_divergence_weight = 0.1 # set 0 to disable\n use_guided_attention = True\n guided_attention_sigma = 0.2\n\n # Training:\n batch_size = 16\n adam_beta1 = 0.5\n adam_beta2 = 0.9\n adam_eps = 1e-6\n amsgrad = False\n initial_learning_rate = 5e-4 # 0.001\n lr_schedule = \"noam_learning_rate_decay\"\n lr_schedule_kwargs = {}\n nepochs = 2000\n weight_decay = 0.0\n clip_thresh = 0.1\n\n # Save\n checkpoint_interval = 10000\n eval_interval = 10000\n save_optimizer_state = True\n\n # Eval:\n # this can be list for multple layers of attention\n # e.g. [True False False False True]\n force_monotonic_attention = True\n # Attention constraint for incremental decoding\n window_ahead = 3\n # 0 tends to prevent word repretetion but sometime causes skip words\n window_backward = 1\n power = 1.4 # Power to raise magnitudes to prior to phase retrieval\n\n # GC:\n # Forced garbage collection probability\n # Use only when MemoryError continues in Windows (Disabled by default)\n # gc_probability = 0.001\n\n # json_meta mode only\n # 0: \"use all\"\n # 1: \"ignore only unmatched_alignment\"\n # 2: \"fully ignore recognition\"\n ignore_recognition_level = 2\n # when dealing with non-dedicated speech dataset(e.g. movie excerpts) setting min_text above 15 is desirable.\n # Can be adjusted by dataset.\n min_text = 20\n # if true data without phoneme alignment file(.lab) will be ignored\n process_only_htk_aligned = False\n\n\nfs = Hparams.sample_rate\nglobal_step = 0\nglobal_epoch = 0\n\n\ndef build_model():\n model = getattr(builder, Hparams.builder)(\n n_speakers=Hparams.n_speakers,\n speaker_embed_dim=Hparams.speaker_embed_dim,\n n_vocab=frontend.n_vocab,\n embed_dim=Hparams.text_embed_dim,\n mel_dim=Hparams.num_mels,\n linear_dim=Hparams.fft_size // 2 + 1,\n r=Hparams.outputs_per_step,\n padding_idx=Hparams.padding_idx,\n dropout=Hparams.dropout,\n kernel_size=Hparams.kernel_size,\n encoder_channels=Hparams.encoder_channels,\n decoder_channels=Hparams.decoder_channels,\n converter_channels=Hparams.converter_channels,\n use_memory_mask=Hparams.use_memory_mask,\n trainable_positional_encodings=Hparams.trainable_positional_encodings,\n force_monotonic_attention=Hparams.force_monotonic_attention,\n use_decoder_state_for_postnet_input=Hparams.use_decoder_state_for_postnet_input,\n max_positions=Hparams.max_positions,\n freeze_embedding=Hparams.freeze_embedding,\n window_ahead=Hparams.window_ahead,\n window_backward=Hparams.window_backward\n )\n return model\n\n\ndef load_checkpoint(path, model, device):\n global global_step\n global global_epoch\n\n print(\"Load checkpoint from: {}\".format(path))\n if device.startswith(\"cuda\"):\n checkpoint = torch.load(path)\n else:\n checkpoint = torch.load(path, map_location=lambda storage, loc: storage)\n model.load_state_dict(checkpoint[\"state_dict\"])\n global_step = checkpoint[\"global_step\"]\n global_epoch = checkpoint[\"global_epoch\"]\n\n return model\n\n\ndef inv_preemphasis(x, coef=Hparams.preemphasis):\n \"\"\"Inverse operation of pre-emphasis\n\n Args:\n x (1d-array): Input signal.\n coef (float): Pre-emphasis coefficient.\n\n Returns:\n array: Output filtered signal.\n\n See also:\n :func:`preemphasis`\n \"\"\"\n b = np.array([1.], x.dtype)\n a = np.array([1., -coef], x.dtype)\n return signal.lfilter(b, a, x)\n\n\ndef inv_spectrogram(spectrogram):\n \"\"\"Converts spectrogram to waveform using librosa\"\"\"\n S = _db_to_amp(_denormalize(spectrogram) + Hparams.ref_level_db) # Convert back to linear\n processor = _lws_processor()\n D = processor.run_lws(S.astype(np.float64).T ** Hparams.power)\n y = processor.istft(D).astype(np.float32)\n return inv_preemphasis(y)\n\n\ndef _lws_processor():\n return lws.lws(Hparams.fft_size, Hparams.hop_size, mode=\"speech\")\n\n\n_mel_basis = None\n\n\ndef _db_to_amp(x):\n return np.power(10.0, x * 0.05)\n\n\ndef _denormalize(S):\n return (np.clip(S, 0, 1) * -Hparams.min_level_db) + Hparams.min_level_db\n\n\nclass VoiceGenerator(Pretrained):\n def __init__(self, model_path=None, overwrite=False):\n super(VoiceGenerator, self).__init__()\n self.model_path = model_path if model_path is not None else temp_path_generator()\n ensure_dir(self.model_path)\n self.checkpoint_path = os.path.join(self.model_path, Constant.PRE_TRAIN_VOICE_GENERATOR_MODEL_NAME)\n self.sample_rate = 0\n self.hop_length = 0\n self.overwrite = overwrite\n self.device = get_device()\n self.load()\n\n def load(self):\n self._maybe_download()\n self.sample_rate = Hparams.sample_rate\n self.hop_length = Hparams.hop_size\n model = build_model()\n\n self.model = load_checkpoint(self.checkpoint_path, model, self.device)\n self.model.to(self.device)\n\n def _maybe_download(self):\n # For files in dropbox or google drive, cannot directly use request to download\n # This can be changed directly use download_file method when the file is stored in server\n if not os.path.exists(self.checkpoint_path) or self.overwrite:\n checkpoint_google_id = Constant.PRE_TRAIN_VOICE_GENERATOR_MODEL_GOOGLE_DRIVE_ID\n gdd.download_file_from_google_drive(file_id=checkpoint_google_id, dest_path=self.checkpoint_path,\n overwrite=self.overwrite)\n\n def generate(self, text, path=None):\n waveform, alignment, spectrogram, mel = self.tts(text)\n if path is None:\n path = Constant.PRE_TRAIN_VOICE_GENERATOR_SAVE_FILE_DEFAULT_NAME\n librosa.output.write_wav(path, waveform, self.sample_rate)\n\n def predict(self, x_predict):\n pass\n\n def tts(self, text, p=0, speaker_id=None, fast=True):\n \"\"\"Convert text to speech waveform given a deepvoice3 model.\n\n Args:\n text (str) : Input text to be synthesized\n p (float) : Replace word to pronounciation if p > 0. Default is 0.\n \"\"\"\n self.model.eval()\n if fast:\n self.model.make_generation_fast_()\n\n sequence = np.array(frontend.text_to_sequence(text, p=p))\n sequence = torch.from_numpy(sequence).unsqueeze(0).long().to(self.device)\n text_positions = torch.arange(1, sequence.size(-1) + 1).unsqueeze(0).long().to(self.device)\n speaker_ids = None if speaker_id is None else torch.LongTensor([speaker_id]).to(self.device)\n\n # Greedy decoding\n with torch.no_grad():\n mel_outputs, linear_outputs, alignments, done = self.model(\n sequence, text_positions=text_positions, speaker_ids=speaker_ids)\n\n linear_output = linear_outputs[0].cpu().data.numpy()\n spectrogram = _denormalize(linear_output)\n alignment = alignments[0].cpu().data.numpy()\n mel = mel_outputs[0].cpu().data.numpy()\n mel = _denormalize(mel)\n\n # Predicted audio signal\n waveform = inv_spectrogram(linear_output.T)\n\n return waveform, alignment, spectrogram, mel\n" ]
[ [ "numpy.array", "torch.no_grad", "torch.from_numpy", "scipy.signal.lfilter", "numpy.power", "torch.load", "numpy.clip", "torch.LongTensor" ] ]
konsan1101/py-etc
[ "687061ce09889ec91c1c3c11df62f4cfcb3d9613" ]
[ "flask6_all/_v5_proc_camera.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# COPYRIGHT (C) 2014-2020 Mitsuo KONDOU.\n# This software is released under the MIT License.\n# https://github.com/konsan1101\n# Thank you for keeping the rules.\n\n\n\nimport sys\nimport os\nimport time\nimport datetime\nimport codecs\nimport glob\n\nimport queue\nimport threading\nimport subprocess\n\nimport numpy as np\nimport cv2\n\n\n\n# 共通ルーチン\nimport _v5__qRiKi\nqRiKi = _v5__qRiKi.qRiKi_class()\nimport _v5__qFunc\nqFunc = _v5__qFunc.qFunc_class()\nimport _v5__qLog\nqLog = _v5__qLog.qLog_class()\n\nqPLATFORM = qRiKi.getValue('qPLATFORM' )\nqRUNATTR = qRiKi.getValue('qRUNATTR' )\nqHOSTNAME = qRiKi.getValue('qHOSTNAME' )\nqUSERNAME = qRiKi.getValue('qUSERNAME' )\nqPath_pictures = qRiKi.getValue('qPath_pictures' )\nqPath_videos = qRiKi.getValue('qPath_videos' )\nqPath_cache = qRiKi.getValue('qPath_cache' )\nqPath_sounds = qRiKi.getValue('qPath_sounds' )\nqPath_icons = qRiKi.getValue('qPath_icons' )\nqPath_fonts = qRiKi.getValue('qPath_fonts' )\nqPath_log = qRiKi.getValue('qPath_log' )\nqPath_work = qRiKi.getValue('qPath_work' )\nqPath_rec = qRiKi.getValue('qPath_rec' )\n\nqPath_s_ctrl = qRiKi.getValue('qPath_s_ctrl' )\nqPath_s_inp = qRiKi.getValue('qPath_s_inp' )\nqPath_s_wav = qRiKi.getValue('qPath_s_wav' )\nqPath_s_jul = qRiKi.getValue('qPath_s_jul' )\nqPath_s_STT = qRiKi.getValue('qPath_s_STT' )\nqPath_s_TTS = qRiKi.getValue('qPath_s_TTS' )\nqPath_s_TRA = qRiKi.getValue('qPath_s_TRA' )\nqPath_s_play = qRiKi.getValue('qPath_s_play' )\nqPath_v_ctrl = qRiKi.getValue('qPath_v_ctrl' )\nqPath_v_inp = qRiKi.getValue('qPath_v_inp' )\nqPath_v_jpg = qRiKi.getValue('qPath_v_jpg' )\nqPath_v_detect = qRiKi.getValue('qPath_v_detect' )\nqPath_v_cv = qRiKi.getValue('qPath_v_cv' )\nqPath_v_photo = qRiKi.getValue('qPath_v_photo' )\nqPath_v_msg = qRiKi.getValue('qPath_v_msg' )\nqPath_d_ctrl = qRiKi.getValue('qPath_d_ctrl' )\nqPath_d_play = qRiKi.getValue('qPath_d_play' )\nqPath_d_prtscn = qRiKi.getValue('qPath_d_prtscn' )\nqPath_d_movie = qRiKi.getValue('qPath_d_movie' )\nqPath_d_upload = qRiKi.getValue('qPath_d_upload' )\n\nqBusy_dev_cpu = qRiKi.getValue('qBusy_dev_cpu' )\nqBusy_dev_com = qRiKi.getValue('qBusy_dev_com' )\nqBusy_dev_mic = qRiKi.getValue('qBusy_dev_mic' )\nqBusy_dev_spk = qRiKi.getValue('qBusy_dev_spk' )\nqBusy_dev_cam = qRiKi.getValue('qBusy_dev_cam' )\nqBusy_dev_dsp = qRiKi.getValue('qBusy_dev_dsp' )\nqBusy_dev_scn = qRiKi.getValue('qBusy_dev_scn' )\nqBusy_s_ctrl = qRiKi.getValue('qBusy_s_ctrl' )\nqBusy_s_inp = qRiKi.getValue('qBusy_s_inp' )\nqBusy_s_wav = qRiKi.getValue('qBusy_s_wav' )\nqBusy_s_STT = qRiKi.getValue('qBusy_s_STT' )\nqBusy_s_TTS = qRiKi.getValue('qBusy_s_TTS' )\nqBusy_s_TRA = qRiKi.getValue('qBusy_s_TRA' )\nqBusy_s_play = qRiKi.getValue('qBusy_s_play' )\nqBusy_v_ctrl = qRiKi.getValue('qBusy_v_ctrl' )\nqBusy_v_inp = qRiKi.getValue('qBusy_v_inp' )\nqBusy_v_QR = qRiKi.getValue('qBusy_v_QR' )\nqBusy_v_jpg = qRiKi.getValue('qBusy_v_jpg' )\nqBusy_v_CV = qRiKi.getValue('qBusy_v_CV' )\nqBusy_d_ctrl = qRiKi.getValue('qBusy_d_ctrl' )\nqBusy_d_inp = qRiKi.getValue('qBusy_d_inp' )\nqBusy_d_QR = qRiKi.getValue('qBusy_d_QR' )\nqBusy_d_rec = qRiKi.getValue('qBusy_d_rec' )\nqBusy_d_telework = qRiKi.getValue('qBusy_d_telework' )\nqBusy_d_play = qRiKi.getValue('qBusy_d_play' )\nqBusy_d_browser = qRiKi.getValue('qBusy_d_browser' )\nqBusy_d_upload = qRiKi.getValue('qBusy_d_upload' )\nqRdy__s_force = qRiKi.getValue('qRdy__s_force' )\nqRdy__s_fproc = qRiKi.getValue('qRdy__s_fproc' )\nqRdy__s_sendkey = qRiKi.getValue('qRdy__s_sendkey' )\nqRdy__v_mirror = qRiKi.getValue('qRdy__v_mirror' )\nqRdy__v_reader = qRiKi.getValue('qRdy__v_reader' )\nqRdy__v_sendkey = qRiKi.getValue('qRdy__v_sendkey' )\nqRdy__d_reader = qRiKi.getValue('qRdy__d_reader' )\nqRdy__d_sendkey = qRiKi.getValue('qRdy__d_sendkey' )\n\n\n\nclass proc_camera:\n\n def __init__(self, name='thread', id='0', runMode='debug', \n camDev='0', camMode='harf', camStretch='0', camRotate='0', camZoom='1.0', camFps='5', ):\n self.runMode = runMode\n self.camDev = camDev\n self.camMode = camMode\n self.camStretch = camStretch\n self.camRotate = camRotate\n self.camZoom = camZoom\n self.camSquare = '0.05' #面積1/20以上\n self.camFps = '5'\n if (camFps.isdigit()):\n self.camFps = str(camFps)\n\n self.camWidth = 0\n self.camHeight = 0\n if (camMode != 'default') and (camMode != 'auto'):\n camWidth, camHeight = qFunc.getResolution(camMode)\n self.camWidth = camWidth\n self.camHeight = camHeight\n\n self.breakFlag = threading.Event()\n self.breakFlag.clear()\n self.name = name\n self.id = id\n self.proc_id = '{0:10s}'.format(name).replace(' ', '_')\n self.proc_id = self.proc_id[:-2] + '_' + str(id)\n if (runMode == 'debug'):\n self.logDisp = True\n else:\n self.logDisp = False\n qLog.log('info', self.proc_id, 'init', display=self.logDisp, )\n\n self.proc_s = None\n self.proc_r = None\n self.proc_main = None\n self.proc_beat = None\n self.proc_last = None\n self.proc_step = '0'\n self.proc_seq = 0\n\n # 変数設定\n self.blue_img = np.zeros((240,320,3), np.uint8)\n cv2.rectangle(self.blue_img,(0,0),(320,240),(255,0,0),-1)\n cv2.putText(self.blue_img, 'No Image !', (40,80), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,255))\n\n def __del__(self, ):\n qLog.log('info', self.proc_id, 'bye!', display=self.logDisp, )\n\n def begin(self, ):\n #qLog.log('info', self.proc_id, 'start')\n\n self.fileRun = qPath_work + self.proc_id + '.run'\n self.fileRdy = qPath_work + self.proc_id + '.rdy'\n self.fileBsy = qPath_work + self.proc_id + '.bsy'\n qFunc.statusSet(self.fileRun, False)\n qFunc.statusSet(self.fileRdy, False)\n qFunc.statusSet(self.fileBsy, False)\n\n self.proc_s = queue.Queue()\n self.proc_r = queue.Queue()\n self.proc_main = threading.Thread(target=self.main_proc, args=(self.proc_s, self.proc_r, ))\n self.proc_beat = time.time()\n self.proc_last = time.time()\n self.proc_step = '0'\n self.proc_seq = 0\n\n self.proc_main.setDaemon(True)\n self.proc_main.start()\n\n def abort(self, waitMax=5, ):\n qLog.log('info', self.proc_id, 'stop', display=self.logDisp, )\n\n self.breakFlag.set()\n chktime = time.time()\n while (not self.proc_beat is None) and ((time.time() - chktime) < waitMax):\n time.sleep(0.25)\n chktime = time.time()\n while (os.path.exists(self.fileRun)) and ((time.time() - chktime) < waitMax):\n time.sleep(0.25)\n\n def put(self, data, ):\n self.proc_s.put(data)\n return True\n\n def checkGet(self, waitMax=5, ):\n chktime = time.time()\n while (self.proc_r.qsize() == 0) and ((time.time() - chktime) < waitMax):\n time.sleep(0.10)\n data = self.get()\n return data\n\n def get(self, ):\n if (self.proc_r.qsize() == 0):\n return ['', '']\n data = self.proc_r.get()\n self.proc_r.task_done()\n return data\n\n def main_proc(self, cn_r, cn_s, ):\n # ログ\n qLog.log('info', self.proc_id, 'start', display=self.logDisp, )\n qFunc.statusSet(self.fileRun, True)\n self.proc_beat = time.time()\n\n # 初期設定\n self.proc_step = '1'\n\n # デバイス設定\n capture = None\n if (not self.camDev.isdigit()):\n capture = cv2.VideoCapture(self.camDev)\n\n # FPS計測\n qFPS_class = _v5__qFunc.qFPS_class()\n qFPS_last = time.time()\n\n # 待機ループ\n self.proc_step = '5'\n\n while (self.proc_step == '5'):\n self.proc_beat = time.time()\n\n # 停止要求確認\n if (self.breakFlag.is_set()):\n self.breakFlag.clear()\n self.proc_step = '9'\n break\n\n # キュー取得\n if (cn_r.qsize() > 0):\n cn_r_get = cn_r.get()\n inp_name = cn_r_get[0]\n inp_value = cn_r_get[1]\n cn_r.task_done()\n else:\n inp_name = ''\n inp_value = ''\n\n if (cn_r.qsize() > 1) or (cn_s.qsize() > 20):\n qLog.log('warning', self.proc_id, 'queue overflow warning!, ' + str(cn_r.qsize()) + ', ' + str(cn_s.qsize()))\n\n # デバイス設定\n if (self.camDev.isdigit()):\n if (capture is None):\n if ((qFunc.statusCheck(qBusy_dev_cam) == False) \\\n or (qFunc.statusCheck(qRdy__v_sendkey) == True)):\n\n dev = self.camDev\n if (qFunc.statusCheck(qRdy__v_mirror) == True):\n dev = '0'\n if (qHOSTNAME == 'kondou-s10'):\n dev = '1'\n\n if (os.name != 'nt'):\n capture = cv2.VideoCapture(int(dev))\n else:\n capture = cv2.VideoCapture(int(dev), cv2.CAP_DSHOW)\n try:\n try:\n capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('H', '2', '6', '4'))\n except Exception as e:\n pass\n if (int(self.camWidth ) != 0):\n capture.set(cv2.CAP_PROP_FRAME_WIDTH, int(self.camWidth ))\n if (int(self.camHeight) != 0):\n capture.set(cv2.CAP_PROP_FRAME_HEIGHT, int(self.camHeight))\n if (int(self.camFps) != 0):\n capture.set(cv2.CAP_PROP_FPS, int(self.camFps ))\n except Exception as e:\n pass\n\n # ビジー設定 (ready)\n if (qFunc.statusCheck(self.fileBsy) == False):\n qFunc.statusSet(self.fileBsy, True)\n if (str(self.id) == '0'):\n qFunc.statusSet(qBusy_v_inp, True)\n\n if (not capture is None):\n if ((qFunc.statusCheck(qBusy_dev_cam) == True) \\\n and (qFunc.statusCheck(qRdy__v_sendkey) == False)):\n capture.release()\n capture = None\n\n # ビジー解除 (!ready)\n qFunc.statusSet(self.fileBsy, False)\n if (str(self.id) == '0'):\n qFunc.statusSet(qBusy_v_inp, False)\n\n # レディ設定\n if (not capture is None) and (not os.path.exists(self.fileRdy)):\n qFunc.statusSet(self.fileRdy, True)\n if (capture is None) and (os.path.exists(self.fileRdy)):\n qFunc.statusSet(self.fileRdy, False)\n\n # ステータス応答\n if (inp_name.lower() == '_status_'):\n out_name = inp_name\n if (not capture is None):\n out_value = '_ready_'\n else:\n out_value = '!ready'\n cn_s.put([out_name, out_value])\n\n # 連携情報\n if (inp_name.lower() == '_camstretch_'):\n self.camStretch = inp_value\n qFPS_last = time.time() - 60\n if (inp_name.lower() == '_camrotate_'):\n self.camRotate = inp_value\n qFPS_last = time.time() - 60\n if (inp_name.lower() == '_camzoom_'):\n self.camZoom = inp_value\n qFPS_last = time.time() - 60\n\n\n\n # 画像処理\n if (cn_s.qsize() == 0):\n #if (True):\n\n # 画像取得\n if (not capture is None):\n ret, frame = capture.read()\n else:\n ret = True\n frame = self.blue_img.copy()\n\n if (ret == False):\n qLog.log('info', self.proc_id, 'capture error!', display=self.logDisp,)\n time.sleep(5.00)\n self.proc_step = '9'\n break\n\n else:\n\n # 実行カウンタ\n self.proc_last = time.time()\n self.proc_seq += 1\n if (self.proc_seq > 9999):\n self.proc_seq = 1\n\n # frame_img\n frame_img = frame.copy()\n frame_height, frame_width = frame_img.shape[:2]\n input_img = frame.copy()\n input_height, input_width = input_img.shape[:2]\n\n # 台形補正\n if (int(self.camStretch) != 0):\n x = int((input_width/2) * abs(int(self.camStretch))/100)\n if (int(self.camStretch) > 0):\n perspective1 = np.float32([ [x, 0], [input_width-x, 0], [input_width, input_height], [0, input_height] ])\n else:\n perspective1 = np.float32([ [0, 0], [input_width, 0], [input_width-x, input_height], [x, input_height] ])\n perspective2 = np.float32([ [0, 0], [input_width, 0], [input_width, input_height], [0, input_height] ])\n transform_matrix = cv2.getPerspectiveTransform(perspective1, perspective2)\n input_img = cv2.warpPerspective(input_img, transform_matrix, (input_width, input_height))\n\n # ミラー有効\n if (qFunc.statusCheck(qRdy__v_mirror) == True):\n input_img = cv2.flip(input_img, 1) # 180 Rotation X\n\n # 画像回転\n if (int(self.camRotate) == -180):\n input_img = cv2.flip(input_img, 0) # 180 Rotation Y\n elif (int(self.camRotate) == -360):\n input_img = cv2.flip(input_img, 1) # 180 Rotation X\n elif (abs(int(self.camRotate)) != 0):\n width2 = int((input_width - input_height)/2)\n rect_img = cv2.resize(input_img[0:input_height, width2:width2+input_height], (960,960))\n rect_mat = cv2.getRotationMatrix2D((480, 480), -int(self.camRotate), 1.0)\n rect_r = cv2.warpAffine(rect_img, rect_mat, (960, 960), flags=cv2.INTER_LINEAR)\n input_img = cv2.resize(rect_r, (input_height, input_height))\n input_height, input_width = input_img.shape[:2]\n\n # ズーム\n if (float(self.camZoom) != 1):\n zm = float(self.camZoom)\n x1 = int((input_width-(input_width/zm))/2)\n x2 = input_width - x1\n y1 = int((input_height-(input_height/zm))/2)\n y2 = input_height - y1\n zm_img = input_img[y1:y2, x1:x2]\n input_img = zm_img.copy()\n input_height, input_width = input_img.shape[:2]\n\n # 4角形補足\n if (float(self.camSquare) != 0):\n if (self.runMode == 'debug') \\\n or (self.runMode == 'camera'):\n if (qFunc.statusCheck(qBusy_d_rec) == False):\n\n square_contours = []\n gray = cv2.cvtColor(input_img, cv2.COLOR_BGR2GRAY)\n\n # 0:黒字に白、1:白地に黒\n for bw in range(2):\n\n # 画像補正\n if (bw == 0):\n _, thresh = cv2.threshold(gray, 192, 255, cv2.THRESH_BINARY_INV)\n else:\n gray2 = cv2.bitwise_not(gray)\n _, thresh = cv2.threshold(gray2, 192, 255, cv2.THRESH_BINARY_INV)\n thresh_not = cv2.bitwise_not(thresh)\n\n # 輪郭抽出・幾何図形取得(黒字に白)\n contours, hierarchy = cv2.findContours(thresh_not, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n for i, cnt in enumerate(contours):\n\n # 面積で選別\n area = cv2.contourArea(cnt)\n if (area > ((input_height * input_width) * float(self.camSquare))):\n\n # 輪郭長さで輪郭を近似化する。\n arclen = cv2.arcLength(cnt, True)\n epsilon_len = arclen * 0.05\n approx_cnt = cv2.approxPolyDP(cnt, epsilon=epsilon_len, closed=True)\n\n # 画数で選別\n if (len(approx_cnt) == 4):\n\n # 座標ずらす\n x = np.array([])\n y = np.array([])\n for i in range(4):\n x = np.append(x, approx_cnt[i][0][0])\n y = np.append(y, approx_cnt[i][0][1])\n ave_x = np.mean(x)\n ave_y = np.mean(y)\n\n hit1 = False\n hit2 = False\n hit3 = False\n hit4 = False\n for i in range(4):\n if (x[i] <= ave_x) and (y[i] <= ave_y):\n hit1 = True\n approx_cnt[0][0][0]=x[i]\n approx_cnt[0][0][1]=y[i]\n if (x[i] <= ave_x) and (y[i] > ave_y):\n hit2 = True\n approx_cnt[1][0][0]=x[i]\n approx_cnt[1][0][1]=y[i]\n if (x[i] > ave_x) and (y[i] > ave_y):\n hit3 = True\n approx_cnt[2][0][0]=x[i]\n approx_cnt[2][0][1]=y[i]\n if (x[i] > ave_x) and (y[i] <= ave_y):\n hit4 = True\n approx_cnt[3][0][0]=x[i]\n approx_cnt[3][0][1]=y[i]\n\n if (hit1 == True) and (hit2 == True) \\\n and (hit3 == True) and (hit4 == True):\n square_contours.append(approx_cnt)\n\n # 4角形透過変換\n for i, cnt in enumerate(square_contours):\n\n # 輪郭に外接する長方形を取得する。\n x, y, width, height = cv2.boundingRect(cnt)\n\n # 透過変換\n dst = []\n pts1 = np.float32(cnt)\n pts2 = np.float32([[0,0],[0,height],[width,height],[width,0]])\n\n M = cv2.getPerspectiveTransform(pts1,pts2)\n dst = cv2.warpPerspective(input_img,M,(width,height))\n\n #input_img = dst.copy()\n\n # オーバーレイ\n over_x = x\n over_y = y\n over_img = dst.copy()\n over_height, over_width = over_img.shape[:2]\n\n if (over_x >=0) and (over_y >=0) \\\n and ((over_x + over_width) < input_width) \\\n and ((over_y + over_height) < input_height):\n input_img[over_y:over_y+over_height, over_x:over_x+over_width] = over_img\n cv2.rectangle(input_img,(over_x,over_y),(over_x+over_width,over_y+over_height),(0,0,0),1)\n\n\n\n # FPS計測\n fps = qFPS_class.get()\n if ((time.time() - qFPS_last) > 5):\n qFPS_last = time.time()\n\n # 結果出力(fps)\n out_name = '_fps_'\n out_value = '{:.1f}'.format(fps)\n cn_s.put([out_name, out_value])\n\n # 結果出力(reso)\n out_name = '_reso_'\n out_value = str(input_width) + 'x' + str(input_height)\n if (float(self.camZoom) != 1):\n out_value += ' (Zoom=' + self.camZoom + ')'\n cn_s.put([out_name, out_value])\n\n # 結果出力\n if (cn_s.qsize() == 0):\n out_name = '[img]'\n out_value = input_img.copy()\n cn_s.put([out_name, out_value])\n\n\n\n # アイドリング\n slow = False\n if (qFunc.statusCheck(qBusy_dev_cpu) == True):\n slow = True\n if (qFunc.statusCheck(qBusy_dev_cam ) == True):\n slow = True\n if (qFunc.statusCheck(qBusy_d_play ) == True) \\\n or (qFunc.statusCheck(qBusy_d_browser) == True):\n slow = True\n\n if (slow == True):\n time.sleep(1.00)\n else:\n time.sleep((1/int(self.camFps))/2)\n\n # 終了処理\n if (True):\n\n # レディ解除\n qFunc.statusSet(self.fileRdy, False)\n\n # デバイス開放\n if (not capture is None): \n capture.release()\n capture = None\n\n # ビジー解除 (!ready)\n qFunc.statusSet(self.fileBsy, False)\n if (str(self.id) == '0'):\n qFunc.statusSet(qBusy_v_inp, False)\n\n # キュー削除\n while (cn_r.qsize() > 0):\n cn_r_get = cn_r.get()\n cn_r.task_done()\n while (cn_s.qsize() > 0):\n cn_s_get = cn_s.get()\n cn_s.task_done()\n\n # ログ\n qLog.log('info', self.proc_id, 'end', display=self.logDisp, )\n qFunc.statusSet(self.fileRun, False)\n self.proc_beat = None\n\n\n\nif __name__ == '__main__':\n\n # 共通クラス\n qRiKi.init()\n qFunc.init()\n\n # ログ\n nowTime = datetime.datetime.now()\n filename = qPath_log + nowTime.strftime('%Y%m%d.%H%M%S') + '.' + os.path.basename(__file__) + '.log'\n qLog.init(mode='logger', filename=filename, )\n\n # ビジー解除 (!ready)\n qFunc.statusSet(qBusy_dev_cam, False)\n\n # 設定\n cv2.namedWindow('Display', 1)\n cv2.moveWindow( 'Display', 0, 0)\n\n #camDev='http://192.168.200.251/nphMotionJpeg?Resolution=640x480'\n camDev='0'\n camera_thread = proc_camera(name='camera', id='0', runMode='debug', \n camDev=camDev, camMode='vga', camStretch='0', camRotate='0', camZoom='1.0', camFps='5',)\n camera_thread.begin()\n\n\n\n # ループ\n chktime = time.time()\n limit_sec = 15\n if (camDev != '0'):\n limit_sec = 3600\n while ((time.time() - chktime) < limit_sec):\n\n res_data = camera_thread.get()\n res_name = res_data[0]\n res_value = res_data[1]\n if (res_name != ''):\n if (res_name == '[img]'):\n cv2.imshow('Display', res_value.copy() )\n cv2.waitKey(1)\n else:\n print(res_name, res_value, )\n\n #if (camera_thread.proc_s.qsize() == 0):\n # camera_thread.put(['_status_', ''])\n\n time.sleep(0.02)\n\n time.sleep(1.00)\n camera_thread.abort()\n del camera_thread\n\n\n\n cv2.destroyAllWindows()\n\n\n\n" ]
[ [ "numpy.array", "numpy.zeros", "numpy.mean", "numpy.float32", "numpy.append" ] ]
vishalbelsare/FinMind
[ "bf57f8e68adc0583495b29135a91e47515cf4cf1" ]
[ "FinMind/strategies/short_sale_margin_purchase_ratio.py" ]
[ "import numpy as np\nimport pandas as pd\n\nfrom FinMind.data import DataLoader\nfrom FinMind.schema.data import Dataset\nfrom FinMind.strategies.base import Strategy, Trader\n\n\nclass ShortSaleMarginPurchaseRatio(Strategy):\n \"\"\"\n url: \"https://blog.above.tw/2018/08/15/%E7%B1%8C%E7%A2%BC%E9%9D%A2%E7%9A%84%E9%97%9C%E9%8D%B5%E6%8C%87%E6%A8%99%E6%9C%89%E5%93%AA%E4%BA%9B%EF%BC%9F/\"\n summary:\n 策略概念: 券資比越高代表散戶看空,法人買超股票會上漲,這時候賣可以跟大部分散戶進行相反的操作,反之亦然\n 策略規則: 券資比>=30% 且法人買超股票, 賣\n 券資比<30% 且法人賣超股票 買\n \"\"\"\n\n ShortSaleMarginPurchaseTodayRatioThreshold = 0.3\n\n def __init__(\n self,\n trader: Trader,\n stock_id: str,\n start_date: str,\n end_date: str,\n data_loader: DataLoader,\n ):\n super().__init__(trader, stock_id, start_date, end_date, data_loader)\n self.TaiwanStockMarginPurchaseShortSale = None\n self.InstitutionalInvestorsBuySell = None\n\n def load_strategy_data(self):\n self.TaiwanStockMarginPurchaseShortSale = self.data_loader.get_data(\n dataset=Dataset.TaiwanStockMarginPurchaseShortSale,\n data_id=self.stock_id,\n start_date=self.start_date,\n end_date=self.end_date,\n )\n self.InstitutionalInvestorsBuySell = self.data_loader.get_data(\n dataset=Dataset.TaiwanStockInstitutionalInvestorsBuySell,\n data_id=self.stock_id,\n start_date=self.start_date,\n end_date=self.end_date,\n )\n\n def load_taiwan_stock_margin_purchase_short_sale(self):\n self.TaiwanStockMarginPurchaseShortSale[\n [\"ShortSaleTodayBalance\", \"MarginPurchaseTodayBalance\"]\n ] = self.TaiwanStockMarginPurchaseShortSale[\n [\"ShortSaleTodayBalance\", \"MarginPurchaseTodayBalance\"]\n ].astype(\n int\n )\n self.TaiwanStockMarginPurchaseShortSale[\n \"ShortSaleMarginPurchaseTodayRatio\"\n ] = (\n self.TaiwanStockMarginPurchaseShortSale[\"ShortSaleTodayBalance\"]\n / self.TaiwanStockMarginPurchaseShortSale[\n \"MarginPurchaseTodayBalance\"\n ]\n )\n\n def load_institutional_investors_buy_sell(self):\n self.InstitutionalInvestorsBuySell[[\"sell\", \"buy\"]] = (\n self.InstitutionalInvestorsBuySell[[\"sell\", \"buy\"]]\n .fillna(0)\n .astype(int)\n )\n self.InstitutionalInvestorsBuySell = (\n self.InstitutionalInvestorsBuySell.groupby(\n [\"date\", \"stock_id\"], as_index=False\n ).agg({\"buy\": np.sum, \"sell\": np.sum})\n )\n self.InstitutionalInvestorsBuySell[\"diff\"] = (\n self.InstitutionalInvestorsBuySell[\"buy\"]\n - self.InstitutionalInvestorsBuySell[\"sell\"]\n )\n\n def create_trade_sign(self, stock_price: pd.DataFrame) -> pd.DataFrame:\n stock_price = stock_price.sort_values(\"date\")\n self.load_taiwan_stock_margin_purchase_short_sale()\n self.load_institutional_investors_buy_sell()\n stock_price = pd.merge(\n stock_price,\n self.InstitutionalInvestorsBuySell[[\"stock_id\", \"date\", \"diff\"]],\n on=[\"stock_id\", \"date\"],\n how=\"left\",\n ).fillna(0)\n stock_price = pd.merge(\n stock_price,\n self.TaiwanStockMarginPurchaseShortSale[\n [\"stock_id\", \"date\", \"ShortSaleMarginPurchaseTodayRatio\"]\n ],\n on=[\"stock_id\", \"date\"],\n how=\"left\",\n ).fillna(0)\n stock_price.index = range(len(stock_price))\n stock_price[\"signal\"] = 0\n sell_mask = (\n stock_price[\"ShortSaleMarginPurchaseTodayRatio\"]\n >= self.ShortSaleMarginPurchaseTodayRatioThreshold\n ) & (stock_price[\"diff\"] > 0)\n stock_price.loc[sell_mask, \"signal\"] = -1\n buy_mask = (\n stock_price[\"ShortSaleMarginPurchaseTodayRatio\"]\n < self.ShortSaleMarginPurchaseTodayRatioThreshold\n ) & (stock_price[\"diff\"] < 0)\n stock_price.loc[buy_mask, \"signal\"] = 1\n return stock_price\n" ]
[ [ "pandas.merge" ] ]
nicolas-harraudeau-sonarsource/tensorflow
[ "f42f57b814b82a217943f621967036a08bb95e88" ]
[ "tensorflow/python/compiler/tensorrt/trt_convert.py" ]
[ "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\"\"\"Exposes the Python wrapper conversion to trt_graph.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nfrom functools import partial # pylint: disable=g-importing-member\nimport os\nimport platform\nimport tempfile\n\nimport six as _six\n\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.core.protobuf import meta_graph_pb2\nfrom tensorflow.core.protobuf import rewriter_config_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import wrap_function\nfrom tensorflow.python.framework import convert_to_constants\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import graph_util\nfrom tensorflow.python.framework import importer\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.grappler import tf_optimizer\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_resource_variable_ops\nfrom tensorflow.python.platform import tf_logging\nfrom tensorflow.python.saved_model import builder\nfrom tensorflow.python.saved_model import load\nfrom tensorflow.python.saved_model import loader\nfrom tensorflow.python.saved_model import save\nfrom tensorflow.python.saved_model import signature_constants\nfrom tensorflow.python.saved_model import tag_constants\nfrom tensorflow.python.training import saver\nfrom tensorflow.python.training.tracking import tracking\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util.lazy_loader import LazyLoader\nfrom tensorflow.python.util.tf_export import tf_export\n\nif platform.system() == \"Windows\":\n raise RuntimeError(\"Windows platform is not supported\")\n\n# Lazily load the op, since it's not available in cpu-only builds. Importing\n# this at top will cause tests that imports TF-TRT fail when they're built\n# and run without CUDA/GPU.\ngen_trt_ops = LazyLoader(\n \"gen_trt_ops\", globals(),\n \"tensorflow.compiler.tf2tensorrt.ops.gen_trt_ops\")\n\n_pywrap_py_utils = LazyLoader(\n \"_pywrap_py_utils\", globals(),\n \"tensorflow.compiler.tf2tensorrt._pywrap_py_utils\")\n\n# Register TRT ops in python, so that when users import this module they can\n# execute a TRT-converted graph without calling any of the methods in this\n# module.\n#\n# This will call register_op_list() in\n# tensorflow/python/framework/op_def_registry.py, but it doesn't register\n# the op or the op kernel in C++ runtime.\ntry:\n gen_trt_ops.trt_engine_op # pylint: disable=pointless-statement\nexcept AttributeError:\n pass\n\n\ndef _to_bytes(s):\n \"\"\"Encode s if it is a sequence of chars.\"\"\"\n if isinstance(s, _six.text_type):\n return s.encode(\"utf-8\", errors=\"surrogateescape\")\n return s\n\n\ndef _to_string(s):\n \"\"\"Decode s if it is a sequence of bytes.\"\"\"\n if isinstance(s, _six.binary_type):\n return s.decode(\"utf-8\")\n return s\n\n\nclass TrtPrecisionMode(object):\n FP32 = \"FP32\"\n FP16 = \"FP16\"\n INT8 = \"INT8\"\n\n @staticmethod\n def supported_precision_modes():\n precisions = [\n TrtPrecisionMode.FP32, TrtPrecisionMode.FP16, TrtPrecisionMode.INT8\n ]\n return precisions + [p.lower() for p in precisions]\n\n\n# Use a large enough number as the default max_workspace_size for TRT engines,\n# so it can produce reasonable performance results with the default.\nDEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES = 1 << 30\n\n\n@tf_export(\"experimental.tensorrt.ConversionParams\", v1=[])\nclass TrtConversionParams(\n collections.namedtuple(\"TrtConversionParams\", [\n \"rewriter_config_template\", \"max_workspace_size_bytes\",\n \"precision_mode\", \"minimum_segment_size\", \"is_dynamic_op\",\n \"maximum_cached_engines\", \"use_calibration\", \"max_batch_size\",\n \"allow_build_at_runtime\", \"allow_mixed_precision_on_unconverted_ops\"\n ])):\n \"\"\"Parameters that are used for TF-TRT conversion.\n\n Fields:\n rewriter_config_template: a template RewriterConfig proto used to create a\n TRT-enabled RewriterConfig. If None, it will use a default one.\n max_workspace_size_bytes: the maximum GPU temporary memory which the TRT\n engine can use at execution time. This corresponds to the\n 'workspaceSize' parameter of nvinfer1::IBuilder::setMaxWorkspaceSize().\n precision_mode: one the strings in\n TrtPrecisionMode.supported_precision_modes().\n minimum_segment_size: the minimum number of nodes required for a subgraph\n to be replaced by TRTEngineOp.\n is_dynamic_op: whether to generate dynamic TRT ops which will build the\n TRT network and engine at run time. i.e. Since TensorRT version < 6.0\n does not support dynamic dimensions other than the batch dimension, when\n the TensorFlow graph has a non-batch dimension of dynamic size, we would\n need to enable this option. This option should be set to True in TF 2.0.\n maximum_cached_engines: max number of cached TRT engines for dynamic TRT\n ops. Created TRT engines for a dynamic dimension are cached. This is the\n maximum number of engines that can be cached. If the number of cached\n engines is already at max but none of them supports the input shapes,\n the TRTEngineOp will fall back to run the original TF subgraph that\n corresponds to the TRTEngineOp.\n use_calibration: this argument is ignored if precision_mode is not INT8.\n If set to True, a calibration graph will be created to calibrate the\n missing ranges. The calibration graph must be converted to an inference\n graph by running calibration with calibrate(). If set to False,\n quantization nodes will be expected for every tensor in the graph\n (excluding those which will be fused). If a range is missing, an error\n will occur. Please note that accuracy may be negatively affected if\n there is a mismatch between which tensors TRT quantizes and which\n tensors were trained with fake quantization.\n max_batch_size: max size for the input batch. This parameter is only\n effective when use_implicit_batch is true.\n allow_build_at_runtime: whether to build TensorRT engines during runtime.\n If no TensorRT engine can be found in cache that can handle the given\n inputs during runtime, then a new TensorRT engine is built at runtime if\n allow_build_at_runtime=True, and otherwise native TF is used. This\n argument is only effective if is_dynamic_op=True.\n allow_mixed_precision_on_unconverted_ops: whether to allow TensorFlow to\n use mixed precision on the operations which are not converted to inside\n a TensorRT engine. This argument has a default value of True, and is\n only effective if the requested `precision_mode` is lower than FP32.\n \"\"\"\n\n def __new__(cls,\n rewriter_config_template=None,\n max_workspace_size_bytes=DEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES,\n precision_mode=TrtPrecisionMode.FP32,\n minimum_segment_size=3,\n is_dynamic_op=True,\n maximum_cached_engines=1,\n use_calibration=True,\n max_batch_size=1,\n allow_build_at_runtime=True,\n allow_mixed_precision_on_unconverted_ops=True):\n return super(TrtConversionParams, cls).__new__(\n cls, rewriter_config_template, max_workspace_size_bytes, precision_mode,\n minimum_segment_size, is_dynamic_op, maximum_cached_engines,\n use_calibration, max_batch_size, allow_build_at_runtime,\n allow_mixed_precision_on_unconverted_ops)\n\n\nDEFAULT_TRT_CONVERSION_PARAMS = TrtConversionParams()\n\n_TRT_ENGINE_OP_NAME = \"TRTEngineOp\"\n\n\ndef _check_conversion_params(conversion_params, is_v2=False):\n \"\"\"Validate the provided TrtConversionParams.\n\n Args:\n conversion_params: a TrtConversionParams instance.\n is_v2: whether we're getting a RewriterConfig for TF 2.0.\n\n Raises:\n TypeError: if any of the parameters are of unexpected type.\n ValueError: if any of the parameters are of unexpected value.\n \"\"\"\n supported_precision_modes = TrtPrecisionMode.supported_precision_modes()\n if conversion_params.precision_mode not in supported_precision_modes:\n raise ValueError(\n (\"precision mode '{}' is not supported.\"\n \"It should be one of {}\").format(conversion_params.precision_mode,\n supported_precision_modes))\n if is_v2:\n # Static mode (building TRT engine without executing the op) is deprecated\n # in TF 2.0. See TrtGraphConverterV2 for more details.\n if not conversion_params.is_dynamic_op:\n raise ValueError(\"Option is_dynamic_op=False is not supported in TF 2.0, \"\n \"please set it to True instead.\")\n\n if conversion_params.rewriter_config_template:\n rewriter_cfg = conversion_params.rewriter_config_template\n trt_optimizer = None\n for optimizer in rewriter_cfg.custom_optimizers:\n if optimizer.name == \"TensorRTOptimizer\":\n if trt_optimizer:\n raise ValueError(\n \"Found more than one TensorRTOptimizer in \"\n \"rewriter_config_template while only one is allowed.\")\n trt_optimizer = optimizer\n # If rewriter_config_template is set, it should include TensorRTOptimizer.\n # It is possible to remove this requirement if needed.\n if not trt_optimizer:\n raise ValueError(\n \"Found no TensorRTOptimizer in rewriter_config_template.\")\n if not trt_optimizer.parameter_map:\n raise ValueError(\"Found no parameter_map in TensorRTOptimizer.\")\n if (\"precision_mode\" in trt_optimizer.parameter_map.keys() and\n trt_optimizer.parameter_map[\"precision_mode\"].s not in map(\n _to_bytes, supported_precision_modes)):\n raise ValueError((\"precision_mode '{}' is not supported. \"\n \"It should be one of {}\").format(\n trt_optimizer.parameter_map[\"precision_mode\"],\n supported_precision_modes))\n if is_v2:\n # Static mode (building TRT engine without executing the op) is not\n # supported in TF 2.0. See TrtGraphConverterV2 for more details.\n if (\"is_dynamic_op\" in trt_optimizer.parameter_map.keys() and\n not trt_optimizer.parameter_map[\"is_dynamic_op\"]):\n raise ValueError(\"Option is_dynamic_op=False is not supported \"\n \"in TF 2.0, please set it to True instead.\")\n if (conversion_params.allow_build_at_runtime and\n not conversion_params.is_dynamic_op):\n tf_logging.warn(\n (\"Building TensorRT engines at runtime is not supported \"\n \"if is_dynamic_op=False, therefore assuming \"\n \"allow_build_at_runtime=False. If building TensorRT engines \"\n \"at runtime is desired, set is_dynamic_op=True.\"))\n\n if not conversion_params.allow_mixed_precision_on_unconverted_ops:\n tf_logging.warn(\"Mixed precision on OPs not converted by TF-TRT has been \"\n \"deactivated. We recommend setting: \"\n \"`allow_mixed_precision_on_unconverted_ops=True` for \"\n \"performance reasons.\")\n\n\ndef _check_trt_version_compatibility():\n \"\"\"Check compatibility of TensorRT version.\n\n Raises:\n RuntimeError: if the TensorRT library version is incompatible.\n \"\"\"\n linked_version = _pywrap_py_utils.get_linked_tensorrt_version()\n loaded_version = _pywrap_py_utils.get_loaded_tensorrt_version()\n assert isinstance(linked_version, tuple)\n assert isinstance(loaded_version, tuple)\n assert len(linked_version) == 3\n assert len(loaded_version) == 3\n tf_logging.info(\"Linked TensorRT version: %s\" % str(linked_version))\n tf_logging.info(\"Loaded TensorRT version: %s\" % str(loaded_version))\n if loaded_version < linked_version:\n tf_logging.error(\n \"Loaded TensorRT %s but linked TensorFlow against TensorRT %s. \" %\n (\".\".join(str(x) for x in loaded_version), \".\".join(\n str(x) for x in linked_version)) +\n \"TensorRT does not support forward compatibility. \" +\n \"It is also required to use the same major version of TensorRT \" +\n \"during compilation and runtime.\")\n raise RuntimeError(\"Incompatible TensorRT versions\")\n if loaded_version[0] > linked_version[0]:\n tf_logging.error(\n \"Loaded TensorRT %s but linked TensorFlow against TensorRT %s. \" %\n (\".\".join(str(x) for x in loaded_version), \".\".join(\n str(x) for x in linked_version)) +\n \"It is required to use the same major version \" +\n \"of TensorRT during compilation and runtime.\")\n raise RuntimeError(\"Incompatible TensorRT major version\")\n if loaded_version != linked_version:\n tf_logging.info(\n \"Loaded TensorRT %s and linked TensorFlow against TensorRT %s. \" %\n (\".\".join(str(x) for x in loaded_version), \".\".join(\n str(x) for x in linked_version)) +\n \"This is supported because TensorRT \" +\n \" minor/patch upgrades are backward compatible\")\n\n\ndef get_tensorrt_rewriter_config(conversion_params,\n is_v2=False,\n disable_non_trt_optimizers=False):\n \"\"\"Returns a RewriterConfig proto for TRT transformation.\n\n Args:\n conversion_params: a TrtConversionParams instance.\n is_v2: whether we're getting a RewriterConfig for TF 2.0.\n disable_non_trt_optimizers: Turn off all default Grappler optimizers.\n\n Returns:\n A RewriterConfig proto which sets a TensorRTOptimizer to run Grappler.\n\n Raises:\n TypeError: if any of the parameters are of unexpected type.\n ValueError: if any of the parameters are of unexpected value.\n \"\"\"\n if conversion_params.rewriter_config_template is not None and not isinstance(\n conversion_params.rewriter_config_template,\n rewriter_config_pb2.RewriterConfig):\n raise TypeError(\n \"rewriter_config_template should be a RewriterConfig proto.\")\n _check_conversion_params(conversion_params, is_v2=is_v2)\n\n rewriter_config_with_trt = rewriter_config_pb2.RewriterConfig()\n\n if conversion_params.rewriter_config_template is None:\n if not disable_non_trt_optimizers:\n # Layout optimizer may add Const nodes followed by Reshape nodes, thus we\n # need to run constant folding again.\n rewriter_config_with_trt.optimizers.extend(\n [\"constfold\", \"layout\", \"constfold\"])\n rewriter_config_with_trt.meta_optimizer_iterations = (\n rewriter_config_pb2.RewriterConfig.ONE)\n optimizer = rewriter_config_with_trt.custom_optimizers.add()\n # Add a constfold optimizer to cleanup the unused Const nodes.\n rewriter_config_with_trt.custom_optimizers.add().name = \"constfold\"\n\n optimizer.name = \"TensorRTOptimizer\"\n optimizer.parameter_map[\n \"minimum_segment_size\"].i = conversion_params.minimum_segment_size\n optimizer.parameter_map[\"max_workspace_size_bytes\"].i = (\n conversion_params.max_workspace_size_bytes)\n optimizer.parameter_map[\"precision_mode\"].s = _to_bytes(\n conversion_params.precision_mode)\n optimizer.parameter_map[\n \"maximum_cached_engines\"].i = conversion_params.maximum_cached_engines\n optimizer.parameter_map[\n \"use_calibration\"].b = conversion_params.use_calibration\n optimizer.parameter_map[\"is_dynamic_op\"].b = conversion_params.is_dynamic_op\n optimizer.parameter_map[\n \"allow_build_at_runtime\"].b = conversion_params.allow_build_at_runtime\n optimizer.parameter_map[\n \"max_batch_size\"].i = conversion_params.max_batch_size\n else:\n rewriter_config_with_trt.CopyFrom(\n conversion_params.rewriter_config_template)\n\n if (conversion_params.allow_mixed_precision_on_unconverted_ops and\n conversion_params.precision_mode != TrtPrecisionMode.FP32):\n rewriter_config_with_trt.auto_mixed_precision = \\\n rewriter_config_pb2.RewriterConfig.ON\n else:\n rewriter_config_with_trt.auto_mixed_precision = \\\n rewriter_config_pb2.RewriterConfig.OFF\n\n # Disabling optimizers should happen after CopyFrom the template\n # otherwise the template can overwrite the disablement.\n if disable_non_trt_optimizers:\n off = rewriter_config_pb2.RewriterConfig.OFF\n rewriter_config_with_trt.layout_optimizer = off\n rewriter_config_with_trt.constant_folding = off\n rewriter_config_with_trt.shape_optimization = off\n rewriter_config_with_trt.remapping = off\n rewriter_config_with_trt.arithmetic_optimization = off\n rewriter_config_with_trt.dependency_optimization = off\n rewriter_config_with_trt.loop_optimization = off\n rewriter_config_with_trt.function_optimization = off\n rewriter_config_with_trt.debug_stripper = off\n rewriter_config_with_trt.disable_model_pruning = True\n rewriter_config_with_trt.scoped_allocator_optimization = off\n rewriter_config_with_trt.memory_optimization = (\n rewriter_config_pb2.RewriterConfig.NO_MEM_OPT)\n rewriter_config_with_trt.pin_to_host_optimization = off\n rewriter_config_with_trt.auto_parallel.enable = False\n rewriter_config_with_trt.auto_mixed_precision = off\n\n return rewriter_config_with_trt\n\n\n# Remove all scope prefixes in the node name. In TF 2.0, the same concrete\n# function can be initialized multiple times with different prefixes, and\n# this will result in the same TRTEngineOp being initialized multiple times\n# with different cache and duplicate TRT engines.\n# TODO(laigd): this may be caused by the fact that TRTEngineOp is not\n# stateful, need to investigate.\n# TODO(laigd): we rely on the fact that all functions are fully inlined\n# before TF-TRT optimizer is called, as otherwise it may generate the same\n# name when optimizing a different function graph. Fix this.\ndef _get_canonical_engine_name(name):\n return name.split(\"/\")[-1]\n\n\ndef is_explicit_batch_mode_enabled(rewriter_config):\n \"\"\"Checks whether explicit batch is enabled by the rewriter config.\"\"\"\n if rewriter_config is None:\n return False\n for optimizer in rewriter_config.custom_optimizers:\n if optimizer.name == \"TensorRTOptimizer\":\n if \"use_implicit_batch\" in optimizer.parameter_map:\n return not optimizer.parameter_map[\"use_implicit_batch\"].b\n return False\n\n\nclass TrtGraphConverter(object):\n \"\"\"A converter for TF-TRT transformation for TF 1.x GraphDef/SavedModels.\n\n To run the conversion without quantization calibration (e.g. for FP32/FP16\n precision modes):\n\n ```python\n converter = TrtGraphConverter(\n input_saved_model_dir=\"my_dir\",\n precision_mode=TrtPrecisionMode.FP16)\n converted_graph_def = converter.convert()\n converter.save(output_saved_model_dir)\n ```\n\n To run the conversion with quantization calibration:\n\n ```python\n converter = TrtGraphConverter(\n input_saved_model_dir=\"my_dir\",\n precision_mode=TrtPrecisionMode.INT8)\n converter.convert()\n\n # Run calibration 10 times.\n converted_graph_def = converter.calibrate(\n fetch_names=['output:0'],\n num_runs=10,\n feed_dict_fn=lambda: {'input:0': my_next_data()})\n\n converter.save(output_saved_model_dir)\n ```\n \"\"\"\n\n def __init__(self,\n input_saved_model_dir=None,\n input_saved_model_tags=None,\n input_saved_model_signature_key=None,\n input_graph_def=None,\n nodes_denylist=None,\n session_config=None,\n max_batch_size=1,\n max_workspace_size_bytes=DEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES,\n precision_mode=TrtPrecisionMode.FP32,\n minimum_segment_size=3,\n is_dynamic_op=False,\n maximum_cached_engines=1,\n use_calibration=True,\n allow_mixed_precision_on_unconverted_ops=True):\n \"\"\"Initialize the converter.\n\n Args:\n input_saved_model_dir: the directory to load the SavedModel which contains\n the input graph to transforms. Used only when input_graph_def is None.\n input_saved_model_tags: list of tags to load the SavedModel.\n input_saved_model_signature_key: the key of the signature to optimize the\n graph for.\n input_graph_def: a GraphDef object containing a model to be transformed.\n If set to None, the graph will be read from the SavedModel loaded from\n input_saved_model_dir.\n nodes_denylist: list of node names to prevent the converter from\n touching.\n session_config: the ConfigProto used to create a Session. It's also used\n as a template to create a TRT-enabled ConfigProto for conversion. If not\n specified, a default ConfigProto will be used.\n max_batch_size: max size for the input batch.\n max_workspace_size_bytes: the maximum GPU temporary memory which the TRT\n engine can use at execution time. This corresponds to the\n 'workspaceSize' parameter of nvinfer1::IBuilder::setMaxWorkspaceSize().\n precision_mode: one of TrtPrecisionMode.supported_precision_modes().\n minimum_segment_size: the minimum number of nodes required for a subgraph\n to be replaced by TRTEngineOp.\n is_dynamic_op: whether to generate dynamic TRT ops which will build the\n TRT network and engine at run time.\n maximum_cached_engines: max number of cached TRT engines in dynamic TRT\n ops. If the number of cached engines is already at max but none of them\n can serve the input, the TRTEngineOp will fall back to run the TF\n function based on which the TRTEngineOp is created.\n use_calibration: this argument is ignored if precision_mode is not INT8.\n If set to True, a calibration graph will be created to calibrate the\n missing ranges. The calibration graph must be converted to an inference\n graph by running calibration with calibrate(). If set to False,\n quantization nodes will be expected for every tensor in the graph\n (excluding those which will be fused). If a range is missing, an error\n will occur. Please note that accuracy may be negatively affected if\n there is a mismatch between which tensors TRT quantizes and which\n tensors were trained with fake quantization.\n allow_mixed_precision_on_unconverted_ops: whether to allow TensorFlow to\n use mixed precision on the operations which are not converted to inside\n a TensorRT engine. This argument has a default value of True, and is\n only effective if the requested `precision_mode` is lower than FP32.\n\n Raises:\n ValueError: if the combination of the parameters is invalid.\n RuntimeError: if this class is used in TF 2.0.\n \"\"\"\n if context.executing_eagerly():\n raise RuntimeError(\n \"Please use tf.experimental.tensorrt.Converter in TF 2.0.\")\n\n if input_graph_def and input_saved_model_dir:\n raise ValueError(\n \"Can only specify one of input_graph_def and input_saved_model_dir\")\n if not input_graph_def and not input_saved_model_dir:\n raise ValueError(\"Must specify one of input_graph_def and \"\n \"input_saved_model_dir\")\n _check_trt_version_compatibility()\n\n self._input_graph_def = input_graph_def\n self._nodes_denylist = nodes_denylist\n\n self._input_saved_model_dir = input_saved_model_dir\n self._converted = False\n self._grappler_meta_graph_def = None\n\n self._input_saved_model_tags = (\n input_saved_model_tags or [tag_constants.SERVING])\n self._input_saved_model_signature_key = (\n input_saved_model_signature_key or\n signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY)\n self._session_config = session_config or config_pb2.ConfigProto()\n\n # For calibration usage.\n self._calibration_graph = None\n self._calibration_data_collected = False\n self._need_calibration = (\n precision_mode == TrtPrecisionMode.INT8 and use_calibration)\n if self._need_calibration and not is_dynamic_op:\n tf_logging.warn(\n \"INT8 precision mode with calibration is supported with \"\n \"dynamic TRT ops only. Disregarding is_dynamic_op parameter.\")\n is_dynamic_op = True\n\n # TODO(laigd):\n # - Verify in int8 mode that maximum_cached_engines is set properly.\n # - If it fails to build the int8 engine it should return error.\n rewriter_config_template = None\n if (session_config and session_config.HasField(\"graph_options\") and\n session_config.graph_options.HasField(\"rewrite_options\")):\n rewriter_config_template = session_config.graph_options.rewrite_options\n\n self._conversion_params = TrtConversionParams(\n rewriter_config_template=rewriter_config_template,\n max_workspace_size_bytes=max_workspace_size_bytes,\n precision_mode=precision_mode,\n minimum_segment_size=minimum_segment_size,\n is_dynamic_op=is_dynamic_op,\n maximum_cached_engines=maximum_cached_engines,\n use_calibration=use_calibration,\n max_batch_size=max_batch_size,\n allow_build_at_runtime=True,\n allow_mixed_precision_on_unconverted_ops=\n allow_mixed_precision_on_unconverted_ops\n )\n _check_conversion_params(self._conversion_params)\n\n def _run_conversion(self):\n \"\"\"Run Grappler's OptimizeGraph() tool to convert the graph.\"\"\"\n # Create custom ConfigProto for Grappler.\n grappler_session_config = config_pb2.ConfigProto()\n grappler_session_config.CopyFrom(self._session_config)\n custom_rewriter_config = get_tensorrt_rewriter_config(\n conversion_params=self._conversion_params)\n grappler_session_config.graph_options.rewrite_options.CopyFrom(\n custom_rewriter_config)\n\n # Run Grappler.\n self._converted_graph_def = tf_optimizer.OptimizeGraph(\n grappler_session_config,\n self._grappler_meta_graph_def,\n graph_id=b\"tf_graph\")\n self._converted = True\n\n def _add_nodes_denylist(self):\n if self._nodes_denylist:\n collection_def = self._grappler_meta_graph_def.collection_def[\"train_op\"]\n denylist = collection_def.node_list.value\n for i in self._nodes_denylist:\n if isinstance(i, ops.Tensor):\n denylist.append(_to_bytes(i.name))\n else:\n denylist.append(_to_bytes(i))\n\n def _convert_graph_def(self):\n \"\"\"Convert the input GraphDef.\"\"\"\n graph = ops.Graph()\n with graph.as_default():\n importer.import_graph_def(self._input_graph_def, name=\"\")\n self._grappler_meta_graph_def = saver.export_meta_graph(\n graph_def=graph.as_graph_def(add_shapes=True), graph=graph)\n self._add_nodes_denylist()\n\n self._run_conversion()\n\n def _collections_to_keep(self, collection_keys):\n # TODO(laigd): currently we use the collection key to filter out\n # collections that depend on variable ops, but this may miss some\n # other user-defined collections. A better way would be to use\n # CollectionDef::NodeList for the filtering.\n collections_to_remove = (\n ops.GraphKeys._VARIABLE_COLLECTIONS + [\n ops.GraphKeys.TRAIN_OP, ops.GraphKeys.WHILE_CONTEXT,\n ops.GraphKeys.COND_CONTEXT\n ])\n return [key for key in collection_keys if key not in collections_to_remove]\n\n def _convert_saved_model(self):\n \"\"\"Convert the input SavedModel.\"\"\"\n graph = ops.Graph()\n with session.Session(graph=graph, config=self._session_config) as sess:\n input_meta_graph_def = loader.load(sess, self._input_saved_model_tags,\n self._input_saved_model_dir)\n input_signature_def = input_meta_graph_def.signature_def[\n self._input_saved_model_signature_key]\n\n def _gather_names(tensor_info):\n \"\"\"Get the node names from a TensorInfo.\"\"\"\n return {tensor_info[key].name.split(\":\")[0] for key in tensor_info}\n\n # Get input and outputs from all SignatureDef.\n output_node_names = _gather_names(input_signature_def.inputs).union(\n _gather_names(input_signature_def.outputs))\n\n # Preserve nodes in collection\n for collection_key in self._collections_to_keep(\n input_meta_graph_def.collection_def):\n for op in sess.graph.get_collection(collection_key):\n if isinstance(op, ops.Operation):\n output_node_names.add(op.name.split(\":\")[0])\n\n # Freeze the variables in the SavedModel graph and copy the frozen\n # graph over.\n frozen_graph_def = graph_util.convert_variables_to_constants(\n sess, sess.graph.as_graph_def(add_shapes=True),\n list(output_node_names))\n self._grappler_meta_graph_def = meta_graph_pb2.MetaGraphDef()\n self._grappler_meta_graph_def.graph_def.CopyFrom(frozen_graph_def)\n\n # Copy the collections that are not variables.\n for collection_key in self._collections_to_keep(\n input_meta_graph_def.collection_def):\n self._grappler_meta_graph_def.collection_def[collection_key].CopyFrom(\n input_meta_graph_def.collection_def[collection_key])\n\n self._add_nodes_denylist()\n\n # Copy other information.\n self._grappler_meta_graph_def.meta_info_def.CopyFrom(\n input_meta_graph_def.meta_info_def)\n self._grappler_meta_graph_def.signature_def[\n self._input_saved_model_signature_key].CopyFrom(input_signature_def)\n # TODO(laigd): maybe add back AssetFileDef.\n\n self._run_conversion()\n\n def convert(self):\n \"\"\"Run the TF-TRT conversion.\n\n Returns:\n The converted GraphDef for TF 1.x.\n \"\"\"\n assert not self._converted\n if self._input_graph_def:\n self._convert_graph_def()\n else:\n self._convert_saved_model()\n return self._converted_graph_def\n\n def calibrate(self,\n fetch_names,\n num_runs,\n feed_dict_fn=None,\n input_map_fn=None):\n \"\"\"Run the calibration and return the calibrated GraphDef.\n\n Args:\n fetch_names: a list of output tensor name to fetch during calibration.\n num_runs: number of runs of the graph during calibration.\n feed_dict_fn: a function that returns a dictionary mapping input names (as\n strings) in the GraphDef to be calibrated to values (e.g. Python list,\n numpy arrays, etc). One and only one of `feed_dict_fn` and\n `input_map_fn` should be specified.\n input_map_fn: a function that returns a dictionary mapping input names (as\n strings) in the GraphDef to be calibrated to Tensor objects. The values\n of the named input tensors in the GraphDef to be calibrated will be\n re-mapped to the respective `Tensor` values during calibration. One and\n only one of `feed_dict_fn` and `input_map_fn` should be specified.\n\n Raises:\n ValueError: if the input combination is invalid.\n RuntimeError: if this method is called in eager mode.\n\n Returns:\n The GraphDef after the calibration.\n \"\"\"\n assert self._converted\n assert self._need_calibration\n assert not self._calibration_data_collected\n\n if (feed_dict_fn and input_map_fn) or (not feed_dict_fn and\n not input_map_fn):\n raise ValueError(\n \"Should specify one and only one of feed_dict_fn and input_map_fn.\")\n\n if input_map_fn:\n for k, v in input_map_fn().items():\n if not isinstance(k, str):\n raise ValueError(\"Keys of input_map_fn must be of type str\")\n if not isinstance(v, ops.Tensor):\n raise ValueError(\"Values of input_map_fn must be of type tf.Tensor\")\n\n self._calibration_graph = ops.Graph()\n with self._calibration_graph.as_default():\n fetches = importer.import_graph_def(\n self._converted_graph_def,\n input_map=input_map_fn() if input_map_fn else None,\n return_elements=fetch_names,\n name=\"\")\n\n with session.Session(\n graph=self._calibration_graph,\n config=self._session_config) as calibration_sess:\n for _ in range(num_runs):\n calibration_sess.run(\n fetches, feed_dict=feed_dict_fn() if feed_dict_fn else None)\n\n # Maps device name to the corresponding get_calibration_data.\n #\n # TODO(laigd): a better way would be to use calibration_sess to list\n # all the devices, add one get_calibration_data for each device, and\n # fetch each such op for every resource until its found. This can work\n # even when the device of the TRTEngineOp is empty or not fully specified.\n device_to_get_resource_op_map = {}\n\n with self._calibration_graph.as_default():\n resource_name_input = array_ops.placeholder(dtypes.string)\n\n for node in self._converted_graph_def.node:\n if node.op == _TRT_ENGINE_OP_NAME:\n # Adds the get_calibration_data op for the device if not done\n # before. We only add one such op for each device.\n # TODO(laigd): What if the device is empty?????\n if node.device not in device_to_get_resource_op_map:\n with self._calibration_graph.device(node.device):\n serialized_resources_output = (\n gen_trt_ops.get_calibration_data_op(resource_name_input))\n device_to_get_resource_op_map[node.device] = (\n serialized_resources_output)\n\n # Get the calibration resource.\n calibration_result = calibration_sess.run(\n device_to_get_resource_op_map[node.device],\n feed_dict={\n resource_name_input: _get_canonical_engine_name(node.name)\n })\n node.attr[\"calibration_data\"].s = calibration_result\n\n self._calibration_data_collected = True\n\n return self._converted_graph_def\n\n def save(self, output_saved_model_dir):\n \"\"\"Save the converted graph as a SavedModel.\n\n Args:\n output_saved_model_dir: construct a SavedModel using the converted\n GraphDef and save it to the specified directory. This option only works\n when the input graph is loaded from a SavedModel, i.e. when\n input_saved_model_dir is specified and input_graph_def is None in\n __init__().\n\n Raises:\n ValueError: if the input to the converter is a GraphDef instead of a\n SavedModel.\n \"\"\"\n assert self._converted\n if self._need_calibration:\n assert self._calibration_data_collected\n if self._input_graph_def:\n raise ValueError(\n \"Not able to save to a SavedModel since input is a GraphDef\")\n\n def _restore_collections(dest_graph, src_meta_graph_def, collection_keys):\n \"\"\"Restores collections that we need to keep.\"\"\"\n scope = \"\"\n for key in collection_keys:\n collection_def = src_meta_graph_def.collection_def[key]\n kind = collection_def.WhichOneof(\"kind\")\n if kind is None:\n tf_logging.error(\n \"Cannot identify data type for collection %s. Skipping.\", key)\n continue\n from_proto = ops.get_from_proto_function(key)\n if from_proto and kind == \"bytes_list\":\n proto_type = ops.get_collection_proto_type(key)\n # It is assumed that there are no Variables Keys in collections\n for value in collection_def.bytes_list.value:\n proto = proto_type()\n proto.ParseFromString(value)\n try:\n new_value = from_proto(proto, import_scope=scope)\n except:\n continue\n dest_graph.add_to_collection(key, new_value)\n else:\n field = getattr(collection_def, kind)\n if kind == \"node_list\":\n for value in field.value:\n name = ops.prepend_name_scope(value, scope)\n # Since the graph has been optimized, the node may no longer\n # exists\n try:\n col_op = dest_graph.as_graph_element(name)\n except (TypeError, ValueError, KeyError):\n continue\n dest_graph.add_to_collection(key, col_op)\n elif kind == \"int64_list\":\n # NOTE(opensource): This force conversion is to work around the\n # fact that Python2 distinguishes between int and long, while\n # Python3 has only int.\n for value in field.value:\n dest_graph.add_to_collection(key, int(value))\n else:\n for value in field.value:\n dest_graph.add_to_collection(key,\n ops.prepend_name_scope(value, scope))\n\n # Write the transformed graphdef as SavedModel.\n saved_model_builder = builder.SavedModelBuilder(output_saved_model_dir)\n with ops.Graph().as_default():\n importer.import_graph_def(self._converted_graph_def, name=\"\")\n _restore_collections(\n ops.get_default_graph(), self._grappler_meta_graph_def,\n self._collections_to_keep(\n self._grappler_meta_graph_def.collection_def))\n # We don't use any specific converter here.\n with session.Session(config=self._session_config) as sess:\n saved_model_builder.add_meta_graph_and_variables(\n sess,\n self._input_saved_model_tags,\n signature_def_map=self._grappler_meta_graph_def.signature_def)\n # Ignore other meta graphs from the input SavedModel.\n saved_model_builder.save()\n\n\ndef _get_resource_handle(name, device):\n with ops.device(device):\n return gen_trt_ops.create_trt_resource_handle(resource_name=name)\n\n\nclass _TRTEngineResourceDeleter(tracking.CapturableResourceDeleter):\n \"\"\"Resource deleter for destroying TRT engine cache resource.\"\"\"\n\n def __init__(self, resource_name, device):\n super(_TRTEngineResourceDeleter, self).__init__()\n self._resource_name = resource_name\n self._device = device\n\n def destroy_resource(self):\n handle = _get_resource_handle(self._resource_name, self._device)\n with ops.device(self._device):\n gen_resource_variable_ops.destroy_resource_op(\n handle, ignore_lookup_error=True)\n\n\nclass _TRTEngineResource(tracking.TrackableResource):\n \"\"\"Class to track the serialized engines resource.\"\"\"\n\n def __init__(self,\n resource_name,\n filename,\n maximum_cached_engines,\n device=\"GPU\"):\n super(_TRTEngineResource, self).__init__(\n device=device, deleter=_TRTEngineResourceDeleter(resource_name, device))\n self._resource_name = resource_name\n # Track the serialized engine file in the SavedModel.\n self._filename = self._track_trackable(\n tracking.Asset(filename), \"_serialized_trt_resource_filename\")\n self._maximum_cached_engines = maximum_cached_engines\n\n def _create_resource(self):\n return _get_resource_handle(self._resource_name, self._resource_device)\n\n def _initialize(self):\n gen_trt_ops.initialize_trt_resource(\n self.resource_handle,\n self._filename,\n max_cached_engines_count=self._maximum_cached_engines)\n\n\n@tf_export(\"experimental.tensorrt.Converter\", v1=[])\nclass TrtGraphConverterV2(object):\n \"\"\"An offline converter for TF-TRT transformation for TF 2.0 SavedModels.\n\n Currently this is not available on Windows platform.\n\n Note that in V2, is_dynamic_op=False is not supported, meaning TRT engines\n will be built only when the corresponding TRTEngineOp is executed. But we\n still provide a way to avoid the cost of building TRT engines during inference\n (see more below).\n\n There are several ways to run the conversion:\n\n 1. FP32/FP16 precision\n\n ```python\n params = tf.experimental.tensorrt.ConversionParams(\n precision_mode='FP16')\n converter = tf.experimental.tensorrt.Converter(\n input_saved_model_dir=\"my_dir\", conversion_params=params)\n converter.convert()\n converter.save(output_saved_model_dir)\n ```\n\n In this case, no TRT engines will be built or saved in the converted\n SavedModel. But if input data is available during conversion, we can still\n build and save the TRT engines to reduce the cost during inference (see\n option 2 below).\n\n 2. FP32/FP16 precision with pre-built engines\n\n ```python\n params = tf.experimental.tensorrt.ConversionParams(\n precision_mode='FP16',\n # Set this to a large enough number so it can cache all the engines.\n maximum_cached_engines=16)\n converter = tf.experimental.tensorrt.Converter(\n input_saved_model_dir=\"my_dir\", conversion_params=params)\n converter.convert()\n\n # Define a generator function that yields input data, and use it to execute\n # the graph to build TRT engines.\n # With TensorRT 5.1, different engines will be built (and saved later) for\n # different input shapes to the TRTEngineOp.\n def my_input_fn():\n for _ in range(num_runs):\n inp1, inp2 = ...\n yield inp1, inp2\n\n converter.build(input_fn=my_input_fn) # Generate corresponding TRT engines\n converter.save(output_saved_model_dir) # Generated engines will be saved.\n ```\n\n In this way, one engine will be built/saved for each unique input shapes of\n the TRTEngineOp. This is good for applications that cannot afford building\n engines during inference but have access to input data that is similar to\n the one used in production (for example, that has the same input shapes).\n Also, the generated TRT engines is platform dependent, so we need to run\n `build()` in an environment that is similar to production (e.g. with\n same type of GPU).\n\n 3. INT8 precision and calibration with pre-built engines\n\n ```python\n params = tf.experimental.tensorrt.ConversionParams(\n precision_mode='INT8',\n # Currently only one INT8 engine is supported in this mode.\n maximum_cached_engines=1,\n use_calibration=True)\n converter = tf.experimental.tensorrt.Converter(\n input_saved_model_dir=\"my_dir\", conversion_params=params)\n\n # Define a generator function that yields input data, and run INT8\n # calibration with the data. All input data should have the same shape.\n # At the end of convert(), the calibration stats (e.g. range information)\n # will be saved and can be used to generate more TRT engines with different\n # shapes. Also, one TRT engine will be generated (with the same shape as\n # the calibration data) for save later.\n def my_calibration_input_fn():\n for _ in range(num_runs):\n inp1, inp2 = ...\n yield inp1, inp2\n\n converter.convert(calibration_input_fn=my_calibration_input_fn)\n\n # (Optional) Generate more TRT engines offline (same as the previous\n # option), to avoid the cost of generating them during inference.\n def my_input_fn():\n for _ in range(num_runs):\n inp1, inp2 = ...\n yield inp1, inp2\n converter.build(input_fn=my_input_fn)\n\n # Save the TRT engine and the engines.\n converter.save(output_saved_model_dir)\n ```\n \"\"\"\n\n def __init__(self,\n input_saved_model_dir=None,\n input_saved_model_tags=None,\n input_saved_model_signature_key=None,\n conversion_params=None):\n \"\"\"Initialize the converter.\n\n Args:\n input_saved_model_dir: the directory to load the SavedModel which contains\n the input graph to transforms. Used only when input_graph_def is None.\n input_saved_model_tags: list of tags to load the SavedModel.\n input_saved_model_signature_key: the key of the signature to optimize the\n graph for.\n conversion_params: a TrtConversionParams instance.\n\n Raises:\n ValueError: if the combination of the parameters is invalid.\n \"\"\"\n assert context.executing_eagerly()\n if conversion_params is None:\n conversion_params = TrtConversionParams()\n _check_trt_version_compatibility()\n _check_conversion_params(conversion_params, is_v2=True)\n\n self._conversion_params = conversion_params\n self._input_saved_model_dir = input_saved_model_dir\n self._input_saved_model_tags = (\n input_saved_model_tags or [tag_constants.SERVING])\n self._input_saved_model_signature_key = (\n input_saved_model_signature_key or\n signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY)\n self._rewriter_config = get_tensorrt_rewriter_config(\n conversion_params=self._conversion_params, is_v2=True)\n\n self._need_calibration = (\n conversion_params.precision_mode == TrtPrecisionMode.INT8 and\n conversion_params.use_calibration)\n if (self._need_calibration and not conversion_params.is_dynamic_op):\n raise ValueError(\"INT8 precision mode with calibration is not supported \"\n \"with static TensorRT ops. Set is_dynamic_op to True.\")\n\n # rewriter_config is already validated\n self._need_trt_profiles = is_explicit_batch_mode_enabled(\n self._rewriter_config)\n self._converted = False\n self._build_called_once = False\n\n def _run_conversion(self, meta_graph_def):\n \"\"\"Run Grappler's OptimizeGraph() tool to convert the graph.\n\n Args:\n meta_graph_def: the MetaGraphDef instance to run the optimizations on.\n\n Returns:\n The optimized GraphDef.\n \"\"\"\n grappler_session_config = config_pb2.ConfigProto()\n grappler_session_config.graph_options.rewrite_options.CopyFrom(\n self._rewriter_config)\n return tf_optimizer.OptimizeGraph(\n grappler_session_config, meta_graph_def, graph_id=b\"tf_graph\")\n\n def _for_each_trt_node(self, graph_def, fn):\n \"\"\"Helper method to manipulate all TRTEngineOps in a GraphDef.\"\"\"\n for node in graph_def.node:\n if node.op == _TRT_ENGINE_OP_NAME:\n fn(node)\n for func in graph_def.library.function:\n for node in func.node_def:\n if node.op == _TRT_ENGINE_OP_NAME:\n fn(node)\n\n def _rebuild_func(self, func):\n \"\"\"Rebuild function from graph_def.\"\"\"\n rebuilt_func = wrap_function.function_from_graph_def(\n self._converted_graph_def, [tensor.name for tensor in func.inputs],\n [tensor.name for tensor in func.outputs])\n rebuilt_func.graph.structured_outputs = nest.pack_sequence_as(\n func.graph.structured_outputs, rebuilt_func.graph.structured_outputs)\n return rebuilt_func\n\n # TODO(laigd): provide a utility function to optimize a ConcreteFunction and\n # use it here (b/124792963).\n def convert(self, calibration_input_fn=None):\n \"\"\"Convert the input SavedModel in 2.0 format.\n\n Args:\n calibration_input_fn: a generator function that yields input data as a\n list or tuple, which will be used to execute the converted signature for\n calibration. All the returned input data should have the same shape.\n Example: `def input_fn(): yield input1, input2, input3`\n\n Raises:\n ValueError: if the input combination is invalid.\n\n Returns:\n The TF-TRT converted Function.\n \"\"\"\n assert not self._converted\n\n if (self._need_calibration and not calibration_input_fn):\n raise ValueError(\"Should specify calibration_input_fn because INT8 \"\n \"calibration is needed\")\n if (not self._need_calibration and calibration_input_fn):\n raise ValueError(\"Should not specify calibration_input_fn because INT8 \"\n \"calibration is not needed\")\n\n self._saved_model = load.load(self._input_saved_model_dir,\n self._input_saved_model_tags)\n func = self._saved_model.signatures[self._input_saved_model_signature_key]\n frozen_func = convert_to_constants.convert_variables_to_constants_v2(func)\n grappler_meta_graph_def = saver.export_meta_graph(\n graph_def=frozen_func.graph.as_graph_def(), graph=frozen_func.graph)\n\n # Add a collection 'train_op' so that Grappler knows the outputs.\n fetch_collection = meta_graph_pb2.CollectionDef()\n for array in frozen_func.inputs + frozen_func.outputs:\n fetch_collection.node_list.value.append(array.name)\n grappler_meta_graph_def.collection_def[\"train_op\"].CopyFrom(\n fetch_collection)\n\n # Run TRT optimizer in Grappler to convert the graph.\n self._converted_graph_def = self._run_conversion(grappler_meta_graph_def)\n self._converted_func = wrap_function.function_from_graph_def(\n self._converted_graph_def,\n [tensor.name for tensor in frozen_func.inputs],\n [tensor.name for tensor in frozen_func.outputs])\n # Reconstruct the output signatures using the ones from original model.\n self._converted_func.graph.structured_outputs = nest.pack_sequence_as(\n func.graph.structured_outputs,\n self._converted_func.graph.structured_outputs)\n\n if self._need_calibration:\n for inp in calibration_input_fn():\n self._converted_func(*map(ops.convert_to_tensor, inp))\n\n def _save_calibration_table(node):\n calibration_table = gen_trt_ops.get_calibration_data_op(\n _get_canonical_engine_name(node.name))\n node.attr[\"calibration_data\"].s = calibration_table.numpy()\n\n self._for_each_trt_node(self._converted_graph_def,\n _save_calibration_table)\n\n # Rebuild the function since calibration has changed the graph.\n self._converted_func = self._rebuild_func(self._converted_func)\n\n self._converted = True\n\n def build(self, input_fn):\n \"\"\"Run inference with converted graph in order to build TensorRT engines.\n\n Args:\n input_fn: a generator function that yields input data as a list or tuple,\n which will be used to execute the converted signature to generate TRT\n engines. Example:\n `def input_fn():\n # Let's assume a network with 2 input tensors. We generate 3 sets\n # of dummy input data:\n input_shapes = [[(1, 16), (2, 16)], # 1st input list\n [(2, 32), (4, 32)], # 2nd list of two tensors\n [(4, 32), (8, 32)]] # 3rd input list\n for shapes in input_shapes:\n # return a list of input tensors\n yield [np.zeros(x).astype(np.float32) for x in shapes]`\n Raises:\n NotImplementedError: build() is already called.\n RuntimeError: the input_fx is None.\n \"\"\"\n if self._build_called_once:\n raise NotImplementedError(\"build() is already called. It is not \"\n \"supported to call build() more than once.\")\n if not input_fn:\n raise RuntimeError(\"input_fn is None. Method build() needs input_fn \"\n \"to be specified in order to build TensorRT engines\")\n\n def _set_profile_generation_mode(value, node):\n node.attr[\"_profile_generation_mode\"].b = value\n\n if self._need_trt_profiles:\n # Enable profile generation.\n self._for_each_trt_node(self._converted_graph_def,\n partial(_set_profile_generation_mode, True))\n # Profile generation is enabled using the _profile_generation_mode\n # attribute of the TRTEngineOps. We need to rebuild the function to\n # change this attribute.\n func = self._rebuild_func(self._converted_func)\n else:\n func = self._converted_func\n\n first_input = None\n # Run inference:\n # Builds TRT engines if self._need_trt_profiles is False.\n # Builds TRT optimization profiles if self._need_trt_profiles is True.\n for inp in input_fn():\n if not first_input:\n first_input = inp\n func(*map(ops.convert_to_tensor, inp))\n\n if self._need_trt_profiles:\n # Disable profile generation.\n self._for_each_trt_node(self._converted_graph_def,\n partial(_set_profile_generation_mode, False))\n # Use the first input in explicit batch mode to build TensorRT engines\n # after generating all the profiles. The first input is used but any of\n # the inputs can be used because the shape of this input does not\n # determine the engine and instead the shapes collected in profiles\n # determine the engine.\n self._converted_func(*map(ops.convert_to_tensor, first_input))\n\n self._build_called_once = True\n\n def save(self, output_saved_model_dir):\n \"\"\"Save the converted SavedModel.\n\n Args:\n output_saved_model_dir: directory to saved the converted SavedModel.\n \"\"\"\n assert self._converted\n\n if self._need_trt_profiles and not self._build_called_once:\n raise NotImplementedError(\n \"build() is not called . Explicit batch mode \"\n \"(use_implicit_batch=False) requires generating TensorRT optimization\"\n \" profiles which is done by calling build().\")\n\n # Serialize the TRT engines in the cache if any, and create trackable\n # resource to track them.\n engine_asset_dir = tempfile.mkdtemp()\n resource_map = {}\n\n def _serialize_and_track_engine(node):\n \"\"\"Serialize TRT engines in the cache and track them.\"\"\"\n # Don't dump the same cache twice.\n canonical_engine_name = _get_canonical_engine_name(node.name)\n if canonical_engine_name in resource_map:\n return\n\n filename = os.path.join(engine_asset_dir,\n \"trt-serialized-engine.\" + canonical_engine_name)\n\n try:\n gen_trt_ops.serialize_trt_resource(\n resource_name=canonical_engine_name,\n filename=filename,\n delete_resource=True)\n except errors.NotFoundError:\n tf_logging.info(\"Could not find %s in TF-TRT cache. \"\n \"This can happen if build() is not called, \"\n \"which means TensorRT engines will be built \"\n \"and cached at runtime.\" % canonical_engine_name)\n return\n\n # TODO(laigd): add an option for the user to choose the device.\n resource_map[canonical_engine_name] = _TRTEngineResource(\n canonical_engine_name, filename,\n self._conversion_params.maximum_cached_engines)\n\n self._for_each_trt_node(self._converted_graph_def,\n _serialize_and_track_engine)\n self._saved_model.trt_engine_resources = resource_map\n\n # Rewrite the signature map using the optimized ConcreteFunction.\n signatures = {\n key: value for key, value in self._saved_model.signatures.items()\n }\n\n # Set allow_build_at_runtime=False if asked by user.\n #\n # This attribute is set here because build() needs it to be True in order to\n # build engines.\n if not self._conversion_params.allow_build_at_runtime:\n\n def _reset_allow_build_at_runtime(node):\n node.attr[\"allow_build_at_runtime\"].b = False\n\n self._for_each_trt_node(self._converted_graph_def,\n _reset_allow_build_at_runtime)\n # Rebuild the function since a node attribute changed above\n reset_converted_func = wrap_function.function_from_graph_def(\n self._converted_graph_def,\n [tensor.name for tensor in self._converted_func.inputs],\n [tensor.name for tensor in self._converted_func.outputs])\n reset_converted_func.graph.structured_outputs = nest.pack_sequence_as(\n self._converted_func.graph.structured_outputs,\n reset_converted_func.graph.structured_outputs)\n self._converted_func = reset_converted_func\n\n signatures[self._input_saved_model_signature_key] = self._converted_func\n save.save(self._saved_model, output_saved_model_dir, signatures)\n\n\n# TODO(laigd): use TrtConversionParams here.\ndef create_inference_graph(\n input_graph_def,\n outputs,\n max_batch_size=1,\n max_workspace_size_bytes=DEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES,\n precision_mode=TrtPrecisionMode.FP32,\n minimum_segment_size=3,\n is_dynamic_op=False,\n maximum_cached_engines=1,\n input_saved_model_dir=None,\n input_saved_model_tags=None,\n input_saved_model_signature_key=None,\n output_saved_model_dir=None,\n session_config=None):\n \"\"\"Python wrapper for the TRT transformation.\n\n Args:\n input_graph_def: a GraphDef object containing a model to be transformed. If\n set to None, the graph will be read from the SavedModel loaded from\n input_saved_model_dir.\n outputs: list of tensors or node names for the model outputs. Only used when\n input_graph_def is not None.\n max_batch_size: max size for the input batch.\n max_workspace_size_bytes: the maximum GPU temporary memory which the TRT\n engine can use at execution time. This corresponds to the 'workspaceSize'\n parameter of nvinfer1::IBuilder::setMaxWorkspaceSize().\n precision_mode: one of TrtPrecisionMode.supported_precision_modes().\n minimum_segment_size: the minimum number of nodes required for a subgraph to\n be replaced by TRTEngineOp.\n is_dynamic_op: whether to generate dynamic TRT ops which will build the TRT\n network and engine at run time.\n maximum_cached_engines: max number of cached TRT engines in dynamic TRT ops.\n If the number of cached engines is already at max but none of them can\n serve the input, the TRTEngineOp will fall back to run the TF function\n based on which the TRTEngineOp is created.\n input_saved_model_dir: the directory to load the SavedModel which contains\n the input graph to transforms. Used only when input_graph_def is None.\n input_saved_model_tags: list of tags to load the SavedModel.\n input_saved_model_signature_key: the key of the signature to optimize the\n graph for.\n output_saved_model_dir: if not None, construct a SavedModel using the\n returned GraphDef and save it to the specified directory. This option only\n works when the input graph is loaded from a SavedModel, i.e. when\n input_saved_model_dir is specified and input_graph_def is None.\n session_config: the ConfigProto used to create a Session. It's also used as\n a template to create a TRT-enabled ConfigProto for conversion. If not\n specified, a default ConfigProto will be used.\n\n Returns:\n A GraphDef transformed from input_graph_def (or the SavedModel graph def\n loaded from input_saved_model_dir, if input_graph_def is not present), where\n all TRT compatible subgraphs are replaced with TRTEngineOps, and a TF\n function is added for each of the subgraphs.\n\n If is_dynamic_op is True, each TRTEngineOp will contain a serialized\n subgraph GraphDef, which will be converted to a TRT engine at execution time\n and the TRT engine will be cached for future usage. A new TRT engine will be\n created each time when none of the cached engines match the input shapes. If\n it fails to execute the TRT engine or the number of cached engines reaches\n maximum_cached_engines, the op will fall back to call the corresponding TF\n function.\n\n If is_dynamic_op is False, each TRTEngineOp will contain a serialized TRT\n engine created from the corresponding subgraph. No more engines will be\n created on the fly, and the op will fall back to call the corresponding TF\n function when it fails to execute the engine.\n\n Raises:\n ValueError: if the combination of the parameters is invalid.\n \"\"\"\n trt_converter = TrtGraphConverter(\n input_saved_model_dir=input_saved_model_dir,\n input_saved_model_tags=input_saved_model_tags,\n input_saved_model_signature_key=input_saved_model_signature_key,\n input_graph_def=input_graph_def,\n nodes_denylist=outputs,\n session_config=session_config,\n max_batch_size=max_batch_size,\n max_workspace_size_bytes=max_workspace_size_bytes,\n precision_mode=precision_mode,\n minimum_segment_size=minimum_segment_size,\n is_dynamic_op=is_dynamic_op,\n maximum_cached_engines=maximum_cached_engines,\n use_calibration=False)\n converted_graph_def = trt_converter.convert()\n if output_saved_model_dir:\n trt_converter.save(output_saved_model_dir)\n return converted_graph_def\n" ]
[ [ "tensorflow.core.protobuf.config_pb2.ConfigProto", "tensorflow.python.ops.gen_resource_variable_ops.destroy_resource_op", "tensorflow.python.framework.ops.get_collection_proto_type", "tensorflow.python.framework.ops.get_from_proto_function", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.framework.ops.device", "tensorflow.python.platform.tf_logging.warn", "tensorflow.core.protobuf.meta_graph_pb2.CollectionDef", "tensorflow.python.saved_model.loader.load", "tensorflow.python.client.session.Session", "tensorflow.core.protobuf.meta_graph_pb2.MetaGraphDef", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.saved_model.builder.SavedModelBuilder", "tensorflow.python.platform.tf_logging.error", "tensorflow.python.eager.wrap_function.function_from_graph_def", "tensorflow.python.framework.importer.import_graph_def", "tensorflow.python.framework.ops.Graph", "tensorflow.python.platform.tf_logging.info", "tensorflow.python.framework.convert_to_constants.convert_variables_to_constants_v2", "tensorflow.python.saved_model.load.load", "tensorflow.python.util.nest.pack_sequence_as", "tensorflow.python.framework.ops.prepend_name_scope", "tensorflow.python.grappler.tf_optimizer.OptimizeGraph", "tensorflow.core.protobuf.rewriter_config_pb2.RewriterConfig", "tensorflow.python.saved_model.save.save", "tensorflow.python.training.tracking.tracking.Asset", "tensorflow.python.util.tf_export.tf_export" ] ]
amezqui3/vitaminC_morphology
[ "c2a59ce83248bbc6966dd63532cb466192ce0600" ]
[ "jupyter/mvee.py" ]
[ "from mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport sys\nimport numpy as np\n\nclass EllipsoidTool:\n \"\"\"Some stuff for playing with ellipsoids\n\n Taken from:\n https://github.com/minillinim/ellipsoid\n \"\"\"\n def __init__(self): pass\n\n def getMinVolEllipse(self, P=None, tolerance=0.01, verbose=False):\n \"\"\" Find the minimum volume ellipsoid which holds all the points\n\n Based on work by Nima Moshtagh\n http://www.mathworks.com/matlabcentral/fileexchange/9542\n and also by looking at:\n http://cctbx.sourceforge.net/current/python/scitbx.math.minimum_covering_ellipsoid.html\n Which is based on the first reference anyway!\n\n Here, P is a numpy array of N dimensional points like this:\n P = [[x,y,z,...], <-- one point per line\n [x,y,z,...],\n [x,y,z,...]]\n\n Returns:\n (center, radii, rotation)\n\n \"\"\"\n (N, d) = np.shape(P)\n d = float(d)\n\n # Q will be our working array\n Q = np.vstack([np.copy(P.T), np.ones(N)])\n QT = Q.T\n\n # initializations\n err = 1.0 + tolerance\n u = (1.0 / N) * np.ones(N)\n\n # Khachiyan Algorithm\n iters = 0\n while ((err > tolerance) and (iters < 500)):\n V = np.dot(Q, np.dot(np.diag(u), QT))\n M = np.diag(np.dot(QT , np.dot(np.linalg.inv(V), Q))) # M the diagonal vector of an NxN matrix\n j = np.argmax(M)\n maximum = M[j]\n step_size = (maximum - d - 1.0) / ((d + 1.0) * (maximum - 1.0))\n new_u = (1.0 - step_size) * u\n new_u[j] += step_size\n err = np.linalg.norm(new_u - u)\n u = new_u\n iters += 1\n\n if verbose:\n print('Needed ', iters, ' iterations for MVEE')\n\n # center of the ellipse\n center = np.dot(P.T, u)\n\n # the A matrix for the ellipse\n A = np.linalg.inv(\n np.dot(P.T, np.dot(np.diag(u), P)) -\n np.array([[a * b for b in center] for a in center])\n ) / d\n\n # Get the values we'd like to return\n U, s, rotation = np.linalg.svd(A)\n radii = 1.0/np.sqrt(s)\n\n return (center, radii, rotation)\n\n def getEllipsoidVolume(self, radii):\n \"\"\"Calculate the volume of the blob\"\"\"\n return 4./3.*np.pi*radii[0]*radii[1]*radii[2]\n\n def plotEllipsoid(self, center, radii, rotation, ax=None, plotAxes=False, cageColor='b', cageAlpha=0.2):\n \"\"\"Plot an ellipsoid\"\"\"\n make_ax = ax == None\n if make_ax:\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n\n u = np.linspace(0.0, 2.0 * np.pi, 100)\n v = np.linspace(0.0, np.pi, 100)\n\n # cartesian coordinates that correspond to the spherical angles:\n x = radii[0] * np.outer(np.cos(u), np.sin(v))\n y = radii[1] * np.outer(np.sin(u), np.sin(v))\n z = radii[2] * np.outer(np.ones_like(u), np.cos(v))\n # rotate accordingly\n for i in range(len(x)):\n for j in range(len(x)):\n [x[i,j],y[i,j],z[i,j]] = np.dot([x[i,j],y[i,j],z[i,j]], rotation) + center\n\n if plotAxes:\n # make some purdy axes\n axes = np.array([[radii[0],0.0,0.0],\n [0.0,radii[1],0.0],\n [0.0,0.0,radii[2]]])\n # rotate accordingly\n for i in range(len(axes)):\n axes[i] = np.dot(axes[i], rotation)\n\n\n # plot axes\n for p in axes:\n X3 = np.linspace(-p[0], p[0], 10) + center[0]\n Y3 = np.linspace(-p[1], p[1], 10) + center[1]\n Z3 = np.linspace(-p[2], p[2], 10) + center[2]\n ax.plot(X3, Y3, Z3, color=cageColor)\n\n # plot ellipsoid\n ax.plot_wireframe(x, y, z, rstride=4, cstride=4, color=cageColor, alpha=cageAlpha)\n" ]
[ [ "numpy.array", "numpy.dot", "numpy.linalg.norm", "numpy.sin", "numpy.ones_like", "numpy.copy", "numpy.ones", "numpy.linalg.inv", "numpy.shape", "matplotlib.pyplot.figure", "numpy.argmax", "numpy.linalg.svd", "numpy.sqrt", "numpy.cos", "numpy.linspace", "numpy.diag" ] ]
ionuttamas/Theano-PyMC
[ "b666bdbb35aec21ac83936bfc91c573ef5ccf741" ]
[ "theano/scan/basic.py" ]
[ "__docformat__ = \"restructedtext en\"\n__authors__ = \"Razvan Pascanu \" \"Frederic Bastien \" \"James Bergstra \" \"Pascal Lamblin \"\n__copyright__ = \"(c) 2010, Universite de Montreal\"\n__contact__ = \"Razvan Pascanu <r.pascanu@gmail>\"\n\n\nimport logging\nfrom collections import OrderedDict\n\nimport numpy as np\n\nimport theano.tensor as tt\nfrom theano import config, gof\nfrom theano.compile import SharedVariable, ops\nfrom theano.compile.function import function\nfrom theano.compile.mode import Mode\nfrom theano.gof.utils import TestValueError\nfrom theano.scan import utils\nfrom theano.scan.op import Scan\nfrom theano.scan.utils import safe_new, traverse\nfrom theano.tensor import opt\nfrom theano.updates import OrderedUpdates\n\n\n_logger = logging.getLogger(\"theano.scan.basic\")\n\n\ndef scan(\n fn,\n sequences=None,\n outputs_info=None,\n non_sequences=None,\n n_steps=None,\n truncate_gradient=-1,\n go_backwards=False,\n mode=None,\n name=None,\n profile=False,\n allow_gc=None,\n strict=False,\n return_list=False,\n):\n \"\"\"This function constructs and applies a Scan op to the provided\n arguments.\n\n Parameters\n ----------\n fn\n ``fn`` is a function that describes the operations involved in one\n step of ``scan``. ``fn`` should construct variables describing the\n output of one iteration step. It should expect as input theano\n variables representing all the slices of the input sequences\n and previous values of the outputs, as well as all other arguments\n given to scan as ``non_sequences``. The order in which scan passes\n these variables to ``fn`` is the following :\n\n * all time slices of the first sequence\n * all time slices of the second sequence\n * ...\n * all time slices of the last sequence\n * all past slices of the first output\n * all past slices of the second output\n * ...\n * all past slices of the last output\n * all other arguments (the list given as `non_sequences` to\n scan)\n\n The order of the sequences is the same as the one in the list\n `sequences` given to scan. The order of the outputs is the same\n as the order of ``outputs_info``. For any sequence or output the\n order of the time slices is the same as the one in which they have\n been given as taps. For example if one writes the following :\n\n .. code-block:: python\n\n scan(fn, sequences = [ dict(input= Sequence1, taps = [-3,2,-1])\n , Sequence2\n , dict(input = Sequence3, taps = 3) ]\n , outputs_info = [ dict(initial = Output1, taps = [-3,-5])\n , dict(initial = Output2, taps = None)\n , Output3 ]\n , non_sequences = [ Argument1, Argument2])\n\n ``fn`` should expect the following arguments in this given order:\n\n #. ``Sequence1[t-3]``\n #. ``Sequence1[t+2]``\n #. ``Sequence1[t-1]``\n #. ``Sequence2[t]``\n #. ``Sequence3[t+3]``\n #. ``Output1[t-3]``\n #. ``Output1[t-5]``\n #. ``Output3[t-1]``\n #. ``Argument1``\n #. ``Argument2``\n\n The list of ``non_sequences`` can also contain shared variables\n used in the function, though ``scan`` is able to figure those\n out on its own so they can be skipped. For the clarity of the\n code we recommend though to provide them to scan. To some extend\n ``scan`` can also figure out other ``non sequences`` (not shared)\n even if not passed to scan (but used by `fn`). A simple example of\n this would be :\n\n .. code-block:: python\n\n import theano.tensor as tt\n W = tt.matrix()\n W_2 = W**2\n def f(x):\n return tt.dot(x,W_2)\n\n The function is expected to return two things. One is a list of\n outputs ordered in the same order as ``outputs_info``, with the\n difference that there should be only one output variable per\n output initial state (even if no tap value is used). Secondly\n `fn` should return an update dictionary (that tells how to\n update any shared variable after each iteration step). The\n dictionary can optionally be given as a list of tuples. There is\n no constraint on the order of these two list, ``fn`` can return\n either ``(outputs_list, update_dictionary)`` or\n ``(update_dictionary, outputs_list)`` or just one of the two (in\n case the other is empty).\n\n To use ``scan`` as a while loop, the user needs to change the\n function ``fn`` such that also a stopping condition is returned.\n To do so, he/she needs to wrap the condition in an ``until`` class.\n The condition should be returned as a third element, for example:\n\n .. code-block:: python\n\n ...\n return [y1_t, y2_t], {x:x+1}, until(x < 50)\n\n Note that a number of steps (considered in here as the maximum\n number of steps ) is still required even though a condition is\n passed (and it is used to allocate memory if needed). = {}):\n\n sequences\n ``sequences`` is the list of Theano variables or dictionaries\n describing the sequences ``scan`` has to iterate over. If a\n sequence is given as wrapped in a dictionary, then a set of optional\n information can be provided about the sequence. The dictionary\n should have the following keys:\n\n * ``input`` (*mandatory*) -- Theano variable representing the\n sequence.\n\n * ``taps`` -- Temporal taps of the sequence required by ``fn``.\n They are provided as a list of integers, where a value ``k``\n impiles that at iteration step ``t`` scan will pass to ``fn``\n the slice ``t+k``. Default value is ``[0]``\n\n Any Theano variable in the list ``sequences`` is automatically\n wrapped into a dictionary where ``taps`` is set to ``[0]``\n\n outputs_info\n ``outputs_info`` is the list of Theano variables or dictionaries\n describing the initial state of the outputs computed\n recurrently. When this initial states are given as dictionary\n optional information can be provided about the output corresponding\n to these initial states. The dictionary should have the following\n keys:\n\n * ``initial`` -- Theano variable that represents the initial\n state of a given output. In case the output is not computed\n recursively (think of a map) and does not require an initial\n state this field can be skipped. Given that (only) the previous\n time step of the output is used by ``fn``, the initial state\n **should have the same shape** as the output and **should not\n involve a downcast** of the data type of the output. If multiple\n time taps are used, the initial state should have one extra\n dimension that should cover all the possible taps. For example\n if we use ``-5``, ``-2`` and ``-1`` as past taps, at step 0,\n ``fn`` will require (by an abuse of notation) ``output[-5]``,\n ``output[-2]`` and ``output[-1]``. This will be given by\n the initial state, which in this case should have the shape\n (5,)+output.shape. If this variable containing the initial\n state is called ``init_y`` then ``init_y[0]`` *corresponds to*\n ``output[-5]``. ``init_y[1]`` *correponds to* ``output[-4]``,\n ``init_y[2]`` corresponds to ``output[-3]``, ``init_y[3]``\n coresponds to ``output[-2]``, ``init_y[4]`` corresponds to\n ``output[-1]``. While this order might seem strange, it comes\n natural from splitting an array at a given point. Assume that\n we have a array ``x``, and we choose ``k`` to be time step\n ``0``. Then our initial state would be ``x[:k]``, while the\n output will be ``x[k:]``. Looking at this split, elements in\n ``x[:k]`` are ordered exactly like those in ``init_y``.\n * ``taps`` -- Temporal taps of the output that will be pass to\n ``fn``. They are provided as a list of *negative* integers,\n where a value ``k`` implies that at iteration step ``t`` scan\n will pass to ``fn`` the slice ``t+k``.\n\n ``scan`` will follow this logic if partial information is given:\n\n * If an output is not wrapped in a dictionary, ``scan`` will wrap\n it in one assuming that you use only the last step of the output\n (i.e. it makes your tap value list equal to [-1]).\n * If you wrap an output in a dictionary and you do not provide any\n taps but you provide an initial state it will assume that you are\n using only a tap value of -1.\n * If you wrap an output in a dictionary but you do not provide any\n initial state, it assumes that you are not using any form of\n taps.\n * If you provide a ``None`` instead of a variable or a empty\n dictionary ``scan`` assumes that you will not use any taps for\n this output (like for example in case of a map)\n\n If ``outputs_info`` is an empty list or None, ``scan`` assumes\n that no tap is used for any of the outputs. If information is\n provided just for a subset of the outputs an exception is\n raised (because there is no convention on how scan should map\n the provided information to the outputs of ``fn``)\n\n non_sequences\n ``non_sequences`` is the list of arguments that are passed to\n ``fn`` at each steps. One can opt to exclude variable\n used in ``fn`` from this list as long as they are part of the\n computational graph, though for clarity we encourage not to do so.\n\n n_steps\n ``n_steps`` is the number of steps to iterate given as an int\n or Theano scalar. If any of the input sequences do not have\n enough elements, scan will raise an error. If the *value is 0* the\n outputs will have *0 rows*. If n_steps is not provided, ``scan`` will\n figure out the amount of steps it should run given its input\n sequences. ``n_steps`` < 0 is not supported anymore.\n\n truncate_gradient\n ``truncate_gradient`` is the number of steps to use in truncated\n BPTT. If you compute gradients through a scan op, they are\n computed using backpropagation through time. By providing a\n different value then -1, you choose to use truncated BPTT instead\n of classical BPTT, where you go for only ``truncate_gradient``\n number of steps back in time.\n\n go_backwards\n ``go_backwards`` is a flag indicating if ``scan`` should go\n backwards through the sequences. If you think of each sequence\n as indexed by time, making this flag True would mean that\n ``scan`` goes back in time, namely that for any sequence it\n starts from the end and goes towards 0.\n\n name\n When profiling ``scan``, it is crucial to provide a name for any\n instance of ``scan``. The profiler will produce an overall\n profile of your code as well as profiles for the computation of\n one step of each instance of ``scan``. The ``name`` of the instance\n appears in those profiles and can greatly help to disambiguate\n information.\n\n mode\n It is recommended to leave this argument to None, especially\n when profiling ``scan`` (otherwise the results are not going to\n be accurate). If you prefer the computations of one step of\n ``scan`` to be done differently then the entire function, you\n can use this parameter to describe how the computations in this\n loop are done (see ``theano.function`` for details about\n possible values and their meaning).\n\n profile\n Flag or string. If true, or different from the empty string, a\n profile object will be created and attached to the inner graph of\n scan. In case ``profile`` is True, the profile object will have the\n name of the scan instance, otherwise it will have the passed string.\n Profile object collect (and print) information only when running the\n inner graph with the new cvm linker ( with default modes,\n other linkers this argument is useless)\n\n allow_gc\n Set the value of allow gc for the internal graph of scan. If\n set to None, this will use the value of config.scan__allow_gc.\n\n The full scan behavior related to allocation is determined by\n this value and the Theano flag allow_gc. If the flag allow_gc\n is True (default) and this scan parameter allow_gc is False\n (default), then we let scan allocate all intermediate memory\n on the first iteration, those are not garbage collected them\n during that first iteration (this is determined by the scan\n allow_gc). This speed up allocation of the following\n iteration. But we free all those temp allocation at the end of\n all iterations (this is what the Theano flag allow_gc mean).\n\n If you use preallocate and this scan is on GPU, the speed up\n from the scan allow_gc is small. If you are missing memory,\n disable the scan allow_gc could help you run graph that\n request much memory.\n\n strict\n If true, all the shared variables used in ``fn`` must be provided as a\n part of ``non_sequences`` or ``sequences``.\n\n return_list\n If True, will always return a list, even if there is only 1 output.\n\n Returns\n -------\n tuple\n Tuple of the form (outputs, updates); ``outputs`` is either a\n Theano variable or a list of Theano variables representing the\n outputs of ``scan`` (in the same order as in ``outputs_info``).\n ``updates`` is a subclass of dictionary specifying the update rules for\n all shared variables used in scan.\n This dictionary should be passed to ``theano.function`` when you compile\n your function. The change compared to a normal dictionary is that we\n validate that keys are SharedVariable and addition of those dictionary\n are validated to be consistent.\n\n \"\"\"\n # General observation : this code is executed only once, at creation\n # of the computational graph, so we don't yet need to be smart about\n # anything (to speed things up)\n\n ##\n # Step 1. Wrap all inputs in dictionaries and add default values\n ##\n\n # check if inputs are just single variables instead of lists\n def wrap_into_list(x):\n \"\"\"\n Wrap the input into a list if it is not already a list.\n\n \"\"\"\n if x is None:\n return []\n elif not isinstance(x, (list, tuple)):\n return [x]\n else:\n return list(x)\n\n seqs = wrap_into_list(sequences)\n outs_info = wrap_into_list(outputs_info)\n\n # Make sure we get rid of numpy arrays or ints or anything like that\n # passed as inputs to scan\n non_seqs = []\n for elem in wrap_into_list(non_sequences):\n if not isinstance(elem, gof.Variable):\n non_seqs.append(tt.as_tensor_variable(elem))\n else:\n non_seqs.append(elem)\n\n # If we provided a known number of steps ( before compilation)\n # and if that number is 1 or -1, then we can skip the Scan Op,\n # and just apply the inner function once\n # To do that we check here to see the nature of n_steps\n n_fixed_steps = None\n\n if isinstance(n_steps, (float, int)):\n n_fixed_steps = int(n_steps)\n else:\n try:\n n_fixed_steps = opt.get_scalar_constant_value(n_steps)\n except tt.NotScalarConstantError:\n n_fixed_steps = None\n\n # Check n_steps is an int\n if hasattr(n_steps, \"dtype\") and str(n_steps.dtype) not in tt.integer_dtypes:\n raise ValueError(f\" n_steps must be an int. dtype provided is {n_steps.dtype}\")\n\n # compute number of sequences and number of outputs\n n_seqs = len(seqs)\n n_outs = len(outs_info)\n\n return_steps = OrderedDict()\n # wrap sequences in a dictionary if they are not already dictionaries\n for i in range(n_seqs):\n if not isinstance(seqs[i], dict):\n seqs[i] = OrderedDict([(\"input\", seqs[i]), (\"taps\", [0])])\n elif seqs[i].get(\"taps\", None) is not None:\n seqs[i][\"taps\"] = wrap_into_list(seqs[i][\"taps\"])\n elif seqs[i].get(\"taps\", None) is None:\n # seqs dictionary does not have the ``taps`` key\n seqs[i][\"taps\"] = [0]\n\n # wrap outputs info in a dictionary if they are not already in one\n for i in range(n_outs):\n if outs_info[i] is not None:\n if isinstance(outs_info[i], dict):\n if outs_info[i].get(\"return_steps\", None) is not None:\n raise DeprecationWarning(\n \"Using `return_steps` has been deprecated. \"\n \"Simply select the entries you need using a \"\n \"subtensor. Scan will optimize memory \"\n \"consumption, so do not worry about that.\"\n )\n # END\n\n if not isinstance(outs_info[i], dict):\n # by default any output has a tap value of -1\n outs_info[i] = OrderedDict([(\"initial\", outs_info[i]), (\"taps\", [-1])])\n elif (\n outs_info[i].get(\"initial\", None) is None\n and outs_info[i].get(\"taps\", None) is not None\n ):\n # ^ no initial state but taps provided\n raise ValueError(\n \"If you are using slices of an output \"\n \"you need to provide a initial state \"\n f\"for it: {outs_info[i]}\"\n )\n elif (\n outs_info[i].get(\"initial\", None) is not None\n and outs_info[i].get(\"taps\", None) is None\n ):\n # ^ initial state but taps not provided\n if \"taps\" in outs_info[i]:\n # ^ explicitly provided a None for taps\n _logger.warning(\n f\"Output {getattr(outs_info[i]['initial'], 'name', 'None')} (index {i}) has a initial \"\n \"state but taps is explicitly set to None \",\n )\n outs_info[i][\"taps\"] = [-1]\n elif outs_info[i].get(\"taps\", None) is not None:\n # Check that taps are valid (< 0 and all dfferent)\n taps = outs_info[i][\"taps\"]\n if len(taps) > len(set(taps)):\n raise ValueError(\n (\"All the taps must be different in \" \" `outputs_info`\"),\n outs_info[i],\n )\n for t in taps:\n if t >= 0:\n raise ValueError(\n (\"All the tap values must be \" \"smaller than 0.\"),\n outs_info[i],\n )\n else:\n # if a None is provided as the output info we replace it\n # with an empty OrdereDict() to simplify handling\n outs_info[i] = OrderedDict()\n\n ##\n # Step 2. Generate inputs and outputs of the inner functions\n # for compiling a dummy function (Iteration #1)\n ##\n\n # create theano inputs for the recursive function\n # note : this is a first batch of possible inputs that will\n # be compiled in a dummy function; we used this dummy\n # function to detect shared variables and their updates\n # and to construct a new and complete list of inputs and\n # outputs\n\n n_seqs = 0\n scan_seqs = [] # Variables passed as inputs to the scan op\n inner_seqs = [] # Variables passed as inputs to the inner function\n inner_slices = [] # Actual slices if scan is removed from the picture\n # go through sequences picking up time slices as needed\n for i, seq in enumerate(seqs):\n # Note that you can have something like no taps for\n # a sequence, though is highly unlikely in practice\n if \"taps\" in seq:\n # go through the indicated slice\n mintap = np.min(seq[\"taps\"])\n maxtap = np.max(seq[\"taps\"])\n # We cut the sequence such that seq[i] to correspond to\n # seq[i-k]. For the purposes of cutting the sequences, we\n # need to pretend tap 0 is used to avoid cutting the sequences\n # too long if the taps are all lower or all higher than 0.\n maxtap_proxy = max(maxtap, 0)\n mintap_proxy = min(mintap, 0)\n for k in seq[\"taps\"]:\n # create one slice of the input\n # Later on, if we decide not to use scan because we are\n # going for just one step, it makes things easier if we\n # compute the correct outputs here. This way we can use\n # the output of the lambda expression directly to replace\n # the output of scan.\n\n # If not we need to use copies, that will be replaced at\n # each frame by the corresponding slice\n actual_slice = seq[\"input\"][k - mintap_proxy]\n _seq_val = tt.as_tensor_variable(seq[\"input\"])\n _seq_val_slice = _seq_val[k - mintap_proxy]\n nw_slice = _seq_val_slice.type()\n\n # Try to transfer test_value to the new variable\n if config.compute_test_value != \"off\":\n try:\n nw_slice.tag.test_value = gof.get_test_value(_seq_val_slice)\n except TestValueError:\n if config.compute_test_value != \"ignore\":\n # No need to print a warning or raise an error now,\n # it will be done when fn will be called.\n _logger.warning(\n (\n \"Cannot compute test value for \"\n \"the inner function of scan, input value \"\n \"missing {}\"\n ).format(_seq_val_slice)\n )\n\n # Add names to slices for debugging and pretty printing ..\n # that is if the input already has a name\n if getattr(seq[\"input\"], \"name\", None) is not None:\n if k > 0:\n nw_name = seq[\"input\"].name + f\"[t+{int(k)}]\"\n elif k == 0:\n nw_name = seq[\"input\"].name + \"[t]\"\n else:\n nw_name = seq[\"input\"].name + f\"[t{int(k)}]\"\n nw_slice.name = nw_name\n\n start = k - mintap_proxy\n nw_name = None\n if k == maxtap_proxy:\n nw_seq = seq[\"input\"][start:]\n if getattr(seq[\"input\"], \"name\", None) is not None:\n nw_name = seq[\"input\"].name + f\"[{int(start)}:]\"\n else:\n end = -(maxtap_proxy - k)\n nw_seq = seq[\"input\"][start:end]\n if getattr(seq[\"input\"], \"name\", None) is not None:\n nw_name = seq[\"input\"].name + f\"[{int(start)}:{int(end)}]\"\n\n if go_backwards:\n nw_seq = nw_seq[::-1]\n\n scan_seqs.append(nw_seq)\n inner_seqs.append(nw_slice)\n inner_slices.append(actual_slice)\n n_seqs += 1\n # Add names -- it helps a lot when debugging\n if nw_name is not None:\n nw_seq.name = nw_name\n\n # Since we've added all sequences now we need to level them up based on\n # n_steps or their different shapes\n lengths_vec = []\n for seq in scan_seqs:\n lengths_vec.append(seq.shape[0])\n\n if not utils.isNaN_or_Inf_or_None(n_steps):\n # ^ N_steps should also be considered\n lengths_vec.append(tt.as_tensor(n_steps))\n\n if len(lengths_vec) == 0:\n # ^ No information about the number of steps\n raise ValueError(\n \"No information about the number of steps \"\n \"provided. Either provide a value for \"\n \"n_steps argument of scan or provide an input \"\n \"sequence\"\n )\n\n # If the user has provided the number of steps, do that regardless ( and\n # raise an error if the sequences are not long enough )\n if utils.isNaN_or_Inf_or_None(n_steps):\n actual_n_steps = lengths_vec[0]\n for contestant in lengths_vec[1:]:\n actual_n_steps = tt.minimum(actual_n_steps, contestant)\n else:\n actual_n_steps = tt.as_tensor(n_steps)\n\n scan_seqs = [seq[:actual_n_steps] for seq in scan_seqs]\n # Conventions :\n # mit_mot = multiple input taps, multiple output taps ( only provided\n # by the gradient function )\n # mit_sot = multiple input taps, single output tap (t + 0)\n # sit_sot = single input tap, single output tap (t + 0)\n # nit_sot = no input tap, single output tap (t + 0)\n\n # MIT_MOT -- not provided by the user only by the grad function\n n_mit_mot = 0\n n_mit_mot_outs = 0\n mit_mot_scan_inputs = []\n mit_mot_inner_inputs = []\n mit_mot_inner_outputs = []\n mit_mot_out_slices = []\n\n # SIT_SOT -- provided by the user\n n_mit_sot = 0\n mit_sot_scan_inputs = []\n mit_sot_inner_inputs = []\n mit_sot_inner_slices = []\n mit_sot_inner_outputs = []\n mit_sot_return_steps = OrderedDict()\n mit_sot_tap_array = []\n mit_sot_rightOrder = []\n\n n_sit_sot = 0\n sit_sot_scan_inputs = []\n sit_sot_inner_inputs = []\n sit_sot_inner_slices = []\n sit_sot_inner_outputs = []\n sit_sot_return_steps = OrderedDict()\n sit_sot_rightOrder = []\n\n # go through outputs picking up time slices as needed\n for i, init_out in enumerate(outs_info):\n # Note that our convention dictates that if an output uses\n # just the previous time step, as a initial state we will only\n # provide a tensor of the same dimension as one time step; This\n # makes code much cleaner for those who do not use taps. Otherwise\n # they would always had to shape_padleft the initial state ..\n # which is ugly\n if init_out.get(\"taps\", None) == [-1]:\n\n actual_arg = init_out[\"initial\"]\n if not isinstance(actual_arg, tt.Variable):\n actual_arg = tt.as_tensor_variable(actual_arg)\n arg = safe_new(actual_arg)\n if isinstance(arg, tt.Constant):\n # safe new returns a clone of the constants, but that is not\n # what we need for initial states\n arg = arg.type()\n\n # Try to transfer test_value to the new variable\n if config.compute_test_value != \"off\":\n try:\n arg.tag.test_value = gof.get_test_value(actual_arg)\n except TestValueError:\n if config.compute_test_value != \"ignore\":\n _logger.warning(\n (\n \"Cannot compute test value for the \"\n \"inner function of scan, test value missing: {}\"\n ).format(actual_arg)\n )\n\n if getattr(init_out[\"initial\"], \"name\", None) is not None:\n arg.name = init_out[\"initial\"].name + \"[t-1]\"\n\n # We need now to allocate space for storing the output and copy\n # the initial state over. We do this using the expand function\n # defined in scan utils\n sit_sot_scan_inputs.append(\n utils.expand_empty(\n tt.unbroadcast(tt.shape_padleft(actual_arg), 0),\n actual_n_steps,\n )\n )\n\n sit_sot_inner_slices.append(actual_arg)\n if i in return_steps:\n sit_sot_return_steps[n_sit_sot] = return_steps[i]\n sit_sot_inner_inputs.append(arg)\n sit_sot_rightOrder.append(i)\n n_sit_sot += 1\n\n elif init_out.get(\"taps\", None):\n\n if np.any(np.array(init_out.get(\"taps\", [])) > 0):\n # Make sure we do not have requests for future values of a\n # sequence we can not provide such values\n raise ValueError(\"Can not use future taps of outputs\", init_out)\n # go through the taps\n mintap = abs(np.min(init_out[\"taps\"]))\n mit_sot_tap_array.append(init_out[\"taps\"])\n # Sequence\n mit_sot_scan_inputs.append(\n utils.expand_empty(init_out[\"initial\"][:mintap], actual_n_steps)\n )\n\n if i in return_steps:\n mit_sot_return_steps[n_mit_sot] = return_steps[i]\n mit_sot_rightOrder.append(i)\n n_mit_sot += 1\n for k in init_out[\"taps\"]:\n # create a new slice\n actual_nw_slice = init_out[\"initial\"][k + mintap]\n _init_out_var = tt.as_tensor_variable(init_out[\"initial\"])\n _init_out_var_slice = _init_out_var[k + mintap]\n nw_slice = _init_out_var_slice.type()\n\n # Try to transfer test_value to the new variable\n if config.compute_test_value != \"off\":\n try:\n nw_slice.tag.test_value = gof.get_test_value(\n _init_out_var_slice\n )\n except TestValueError:\n if config.compute_test_value != \"ignore\":\n _logger.warning(\n (\n \"Cannot compute test value for \"\n \"the inner function of scan, test value \"\n \"missing: {}\"\n ).format(_init_out_var_slice)\n )\n\n # give it a name or debugging and pretty printing\n if getattr(init_out[\"initial\"], \"name\", None) is not None:\n if k > 0:\n nw_slice.name = init_out[\"initial\"].name + f\"[t+{int(k)}]\"\n elif k == 0:\n nw_slice.name = init_out[\"initial\"].name + \"[t]\"\n else:\n nw_slice.name = init_out[\"initial\"].name + f\"[t{int(k)}]\"\n mit_sot_inner_inputs.append(nw_slice)\n mit_sot_inner_slices.append(actual_nw_slice)\n # NOTE: there is another case, in which we do not want to provide\n # any previous value of the output to the inner function (i.e.\n # a map); in that case we do not have to do anything ..\n\n # Re-order args\n max_mit_sot = np.max([-1] + mit_sot_rightOrder) + 1\n max_sit_sot = np.max([-1] + sit_sot_rightOrder) + 1\n n_elems = np.max([max_mit_sot, max_sit_sot])\n _ordered_args = [[] for x in range(n_elems)]\n offset = 0\n for idx in range(n_mit_sot):\n n_inputs = len(mit_sot_tap_array[idx])\n if n_fixed_steps in [1, -1]:\n _ordered_args[mit_sot_rightOrder[idx]] = mit_sot_inner_slices[\n offset : offset + n_inputs\n ]\n else:\n _ordered_args[mit_sot_rightOrder[idx]] = mit_sot_inner_inputs[\n offset : offset + n_inputs\n ]\n offset += n_inputs\n\n for idx in range(n_sit_sot):\n if n_fixed_steps in [1, -1]:\n _ordered_args[sit_sot_rightOrder[idx]] = [sit_sot_inner_slices[idx]]\n else:\n _ordered_args[sit_sot_rightOrder[idx]] = [sit_sot_inner_inputs[idx]]\n\n ordered_args = []\n for ls in _ordered_args:\n ordered_args += ls\n if n_fixed_steps in [1, -1]:\n args = inner_slices + ordered_args + non_seqs\n\n else:\n args = inner_seqs + ordered_args + non_seqs\n\n # add only the non-shared variables and non-constants to the arguments of\n # the dummy function [ a function should not get shared variables or\n # constants as input ]\n dummy_args = [\n arg\n for arg in args\n if (not isinstance(arg, SharedVariable) and not isinstance(arg, tt.Constant))\n ]\n # when we apply the lambda expression we get a mixture of update rules\n # and outputs that needs to be separated\n\n condition, outputs, updates = utils.get_updates_and_outputs(fn(*args))\n if condition is not None:\n as_while = True\n else:\n as_while = False\n ##\n # Step 3. Check if we actually need scan and remove it if we don't\n ##\n\n if n_fixed_steps in [1, -1]:\n # We do not need to use the scan op anymore, so we can just return\n # the outputs and updates we have\n if condition is not None:\n _logger.warning(\n (\n \"When the number of steps is fixed and equal \"\n \"to 1, the provided stopping condition, {} is ignored\",\n ).format(condition)\n )\n\n for pos, inner_out in enumerate(outputs):\n # we need to see if we need to pad our sequences with an\n # unbroadcastable dimension; case example : we return an\n # output for which we want all intermediate. If n_steps is 1\n # then, if we return the output as given by the innner function\n # this will represent only a slice and it will have one\n # dimension less.\n if (\n isinstance(inner_out.type, tt.TensorType)\n and return_steps.get(pos, 0) != 1\n ):\n outputs[pos] = tt.unbroadcast(tt.shape_padleft(inner_out), 0)\n\n if return_list is not True and len(outputs) == 1:\n outputs = outputs[0]\n\n return (outputs, updates)\n\n ##\n # Step 4. Compile the dummy function\n ##\n\n # We can now compile a dummy function just to see what shared variable\n # we have and what are their update rules (note that the user has\n # the option not to pass the shared variable to scan, so we need to\n # pick them manually and add them to scan)\n # make the compilation as fast as possible by not applying any\n # optimization or conversion to C [ note this region is not important\n # for performance so we can do stuff as unoptimal as we wish ]\n\n # extract still missing inputs (there still might be so) and add them\n # as non sequences at the end of our args\n if condition is not None:\n outputs.append(condition)\n fake_nonseqs = [x.type() for x in non_seqs]\n fake_outputs = utils.clone(\n outputs, replace=OrderedDict(zip(non_seqs, fake_nonseqs))\n )\n all_inputs = filter(\n lambda x: (\n isinstance(x, gof.Variable)\n and not isinstance(x, SharedVariable)\n and not isinstance(x, gof.Constant)\n ),\n gof.graph.inputs(fake_outputs),\n )\n extra_inputs = [x for x in all_inputs if x not in args + fake_nonseqs]\n non_seqs += extra_inputs\n # Note we do not use all_inputs directly since the order of variables\n # in args is quite important\n dummy_args += extra_inputs\n\n dummy_outs = outputs\n # Perform a try-except to provide a meaningful error message to the\n # user if inputs of the inner function are missing.\n try:\n dummy_f = function(\n dummy_args,\n dummy_outs,\n updates=updates,\n mode=Mode(linker=\"py\", optimizer=None),\n on_unused_input=\"ignore\",\n profile=False,\n )\n except gof.fg.MissingInputError as err:\n msg = (\n \"\\nPlease pass this variable to the scan's inner function. Do \"\n \"not forget to also pass it to the `non_sequences` attribute \"\n \"of scan.\"\n )\n raise gof.fg.MissingInputError(err.args[0] + msg)\n ##\n # Step 5. Re-arange inputs of scan into a more strict order\n ##\n\n # Step 5.0 Check the outputs of the dummy function to see if they\n # match with user provided data\n\n # if the number of outputs to the function does not match the number of\n # assumed outputs until now (provided by the user) there can be\n # only one explanation: No information is provided for any of the\n # outputs (i.e. we are dealing with a map)\n tmp_dummy_f_outs = len(dummy_f.maker.outputs)\n if as_while:\n tmp_dummy_f_outs -= 1\n if not (tmp_dummy_f_outs == n_outs or outs_info == []):\n raise ValueError(\n \"Please provide None as outputs_info for \"\n \"any output that does not feed back into \"\n \"scan (i.e. it behaves like a map) \"\n )\n\n if outs_info == []:\n n_outs = len(dummy_f.maker.outputs)\n if as_while:\n n_outs = n_outs - 1\n outs_info = [OrderedDict() for x in range(n_outs)]\n\n # Step 5.1 Outputs with taps different then -1\n\n for i, out in enumerate(outs_info):\n if \"taps\" in out and out[\"taps\"] != [-1]:\n mit_sot_inner_outputs.append(outputs[i])\n\n # Step 5.2 Outputs with tap equal to -1\n for i, out in enumerate(outs_info):\n if \"taps\" in out and out[\"taps\"] == [-1]:\n sit_sot_inner_outputs.append(outputs[i])\n\n # Step 5.3 Outputs that correspond to update rules of shared variables\n givens = OrderedDict()\n n_shared_outs = 0\n shared_scan_inputs = []\n shared_inner_inputs = []\n shared_inner_outputs = []\n sit_sot_shared = []\n for input in dummy_f.maker.expanded_inputs:\n if isinstance(input.variable, SharedVariable) and input.update:\n new_var = safe_new(input.variable)\n if getattr(input.variable, \"name\", None) is not None:\n new_var.name = input.variable.name + \"_copy\"\n if isinstance(new_var.type, ops.expandable_types):\n sit_sot_inner_inputs.append(new_var)\n sit_sot_scan_inputs.append(\n utils.expand_empty(\n tt.unbroadcast(tt.shape_padleft(input.variable), 0),\n actual_n_steps,\n )\n )\n tensor_update = tt.as_tensor_variable(input.update)\n sit_sot_inner_outputs.append(tensor_update)\n # Not that pos is not a negative index. The sign of pos is used\n # as a flag to indicate if this output should be part of the\n # update rules or part of the standard outputs of scan.\n # If `pos` is positive than it corresponds to the standard\n # outputs of scan and it refers to output of index `pos`. If `pos`\n # is negative that it corresponds to update rules of scan and it\n # refers to update rule of index -1 - `pos`.\n sit_sot_rightOrder.append(-1 - len(sit_sot_shared))\n sit_sot_shared.append(input.variable)\n givens[input.variable] = new_var\n\n else:\n shared_inner_inputs.append(new_var)\n shared_scan_inputs.append(input.variable)\n shared_inner_outputs.append(input.update)\n givens[input.variable] = new_var\n n_shared_outs += 1\n n_sit_sot = len(sit_sot_inner_inputs)\n # Step 5.4 Outputs with no taps used in the input\n n_nit_sot = 0\n nit_sot_inner_outputs = []\n nit_sot_return_steps = OrderedDict()\n nit_sot_rightOrder = []\n for i, out in enumerate(outs_info):\n if \"taps\" not in out:\n nit_sot_inner_outputs.append(outputs[i])\n if i in return_steps:\n nit_sot_return_steps[n_nit_sot] = return_steps[i]\n nit_sot_rightOrder.append(i)\n n_nit_sot += 1\n\n # Step 5.5 all other arguments including extra inputs\n other_scan_args = []\n other_inner_args = []\n\n other_scan_args += [\n arg\n for arg in non_seqs\n if (not isinstance(arg, SharedVariable) and not isinstance(arg, tt.Constant))\n ]\n\n # Step 5.6 all shared variables with no update rules\n other_inner_args += [\n safe_new(arg, \"_copy\")\n for arg in non_seqs\n if (not isinstance(arg, SharedVariable) and not isinstance(arg, tt.Constant))\n ]\n\n givens.update(OrderedDict(zip(other_scan_args, other_inner_args)))\n\n if strict:\n non_seqs_set = set(non_sequences if non_sequences is not None else [])\n\n other_shared_scan_args = [\n arg.variable\n for arg in dummy_f.maker.expanded_inputs\n if (\n isinstance(arg.variable, SharedVariable)\n and not arg.update\n and arg.variable in non_seqs_set\n )\n ]\n other_shared_inner_args = [\n safe_new(arg.variable, \"_copy\")\n for arg in dummy_f.maker.expanded_inputs\n if (\n isinstance(arg.variable, SharedVariable)\n and not arg.update\n and arg.variable in non_seqs_set\n )\n ]\n else:\n other_shared_scan_args = [\n arg.variable\n for arg in dummy_f.maker.expanded_inputs\n if (isinstance(arg.variable, SharedVariable) and not arg.update)\n ]\n other_shared_inner_args = [\n safe_new(arg.variable, \"_copy\")\n for arg in dummy_f.maker.expanded_inputs\n if (isinstance(arg.variable, SharedVariable) and not arg.update)\n ]\n givens.update(OrderedDict(zip(other_shared_scan_args, other_shared_inner_args)))\n\n ##\n # Step 6. Re-order the outputs and clone them replacing things\n # using the givens\n ##\n inner_inputs = (\n inner_seqs\n + mit_mot_inner_inputs\n + mit_sot_inner_inputs\n + sit_sot_inner_inputs\n + shared_inner_inputs\n + other_shared_inner_args\n + other_inner_args\n )\n\n inner_outs = (\n mit_mot_inner_outputs\n + mit_sot_inner_outputs\n + sit_sot_inner_outputs\n + nit_sot_inner_outputs\n + shared_inner_outputs\n )\n if condition is not None:\n inner_outs.append(condition)\n # gpuarray is imported here, instead of being imported on top of\n # the file because that would force on the user some dependencies that we\n # might do not want to. Currently we are working on removing the\n # dependencies on sandbox code completeley.\n from theano import gpuarray\n\n if gpuarray.pygpu_activated:\n # very often we end up in this situation when we want to\n # replace w with w_copy, where w is a GPU variable\n # and w_copy is TensorType. This is caused because shared\n # variables are put on GPU right away >:| ,\n new_givens = OrderedDict()\n\n for w, w_copy in givens.items():\n if isinstance(w.type, gpuarray.GpuArrayType) and isinstance(\n w_copy.type, tt.TensorType\n ):\n for o in inner_outs:\n new_givens = traverse(o, w, w_copy, new_givens)\n else:\n new_givens[w] = w_copy\n else:\n new_givens = givens\n\n new_outs = utils.clone(inner_outs, replace=new_givens)\n\n ##\n # Step 7. Create the Scan Op\n ##\n\n tap_array = mit_sot_tap_array + [[-1] for x in range(n_sit_sot)]\n if allow_gc is None:\n allow_gc = config.scan__allow_gc\n info = OrderedDict()\n\n info[\"tap_array\"] = tap_array\n info[\"n_seqs\"] = n_seqs\n info[\"n_mit_mot\"] = n_mit_mot\n info[\"n_mit_mot_outs\"] = n_mit_mot_outs\n info[\"mit_mot_out_slices\"] = mit_mot_out_slices\n info[\"n_mit_sot\"] = n_mit_sot\n info[\"n_sit_sot\"] = n_sit_sot\n info[\"n_shared_outs\"] = n_shared_outs\n info[\"n_nit_sot\"] = n_nit_sot\n info[\"truncate_gradient\"] = truncate_gradient\n info[\"name\"] = name\n info[\"mode\"] = mode\n info[\"destroy_map\"] = OrderedDict()\n info[\"gpua\"] = False\n info[\"as_while\"] = as_while\n info[\"profile\"] = profile\n info[\"allow_gc\"] = allow_gc\n info[\"strict\"] = strict\n\n local_op = Scan(inner_inputs, new_outs, info)\n\n ##\n # Step 8. Compute the outputs using the scan op\n ##\n _scan_inputs = (\n scan_seqs\n + mit_mot_scan_inputs\n + mit_sot_scan_inputs\n + sit_sot_scan_inputs\n + shared_scan_inputs\n + [actual_n_steps for x in range(n_nit_sot)]\n + other_shared_scan_args\n + other_scan_args\n )\n\n scan_inputs = []\n for arg in [actual_n_steps] + _scan_inputs:\n try:\n arg = tt.as_tensor_variable(arg)\n except TypeError:\n # This happens for Random States for e.g. but it is a good way\n # to make sure all inputs are tensors.\n pass\n scan_inputs += [arg]\n scan_outs = local_op(*scan_inputs)\n if type(scan_outs) not in (list, tuple):\n scan_outs = [scan_outs]\n ##\n # Step 9. Figure out which outs are update rules for shared variables\n # and so on ...\n ##\n\n update_map = OrderedUpdates()\n\n def remove_dimensions(outs, steps_return, offsets=None):\n out_ls = []\n for idx, out in enumerate(outs):\n if idx in steps_return:\n if steps_return[idx] > 1:\n out_ls.append(out[-steps_return[idx] :])\n else:\n out_ls.append(out[-1])\n else:\n if offsets is None:\n out_ls.append(out)\n else:\n out_ls.append(out[offsets[idx] :])\n return out_ls\n\n offset = n_mit_mot\n offsets = [abs(np.min(x)) for x in mit_sot_tap_array]\n mit_sot_outs = remove_dimensions(\n scan_outs[offset : offset + n_mit_sot], mit_sot_return_steps, offsets\n )\n\n offset += n_mit_sot\n offsets = [1 for x in range(n_sit_sot)]\n sit_sot_outs = remove_dimensions(\n scan_outs[offset : offset + n_sit_sot], sit_sot_return_steps, offsets\n )\n\n offset += n_sit_sot\n nit_sot_outs = remove_dimensions(\n scan_outs[offset : offset + n_nit_sot], nit_sot_return_steps\n )\n\n offset += n_nit_sot\n for idx, update_rule in enumerate(scan_outs[offset : offset + n_shared_outs]):\n update_map[shared_scan_inputs[idx]] = update_rule\n\n _scan_out_list = mit_sot_outs + sit_sot_outs + nit_sot_outs\n # Step 10. I need to reorder the outputs to be in the order expected by\n # the user\n rightOrder = mit_sot_rightOrder + sit_sot_rightOrder + nit_sot_rightOrder\n scan_out_list = [None] * len(rightOrder)\n for idx, pos in enumerate(rightOrder):\n if pos >= 0:\n scan_out_list[pos] = _scan_out_list[idx]\n else:\n # Not that pos is not a negative index. The sign of pos is used\n # as a flag to indicate if this output should be part of the\n # update rules or part of the standard outputs of scan.\n # If `pos` is positive than it corresponds to the standard\n # outputs of scan and it refers to output of index `pos`. If `pos`\n # is negative that it corresponds to update rules of scan and it\n # refers to update rule of index -1 - `pos`.\n update_map[sit_sot_shared[abs(pos) - 1]] = _scan_out_list[idx][-1]\n scan_out_list = [x for x in scan_out_list if x is not None]\n if return_list is not True and len(scan_out_list) == 1:\n scan_out_list = scan_out_list[0]\n elif len(scan_out_list) == 0:\n scan_out_list = None\n\n return (scan_out_list, update_map)\n" ]
[ [ "numpy.max", "numpy.min" ] ]
Bstuart77/OBG-Clone
[ "94faafbe6c0e8b7c094b3d71dc4c7b58ab2582dc" ]
[ "examples/lsc/mag240m/preprocess_sgc.py" ]
[ "# NOTE: 128-256GB CPU memory required to run this script.\n\nimport os\nimport time\nimport argparse\nimport os.path as osp\nfrom tqdm import tqdm\n\nimport torch\nimport numpy as np\nfrom torch_sparse import SparseTensor\nfrom torch_geometric.nn.conv.gcn_conv import gcn_norm\nfrom ogb.lsc import MAG240MDataset\nfrom root import ROOT\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--num_layers', type=int, default=3),\n args = parser.parse_args()\n print(args)\n\n dataset = MAG240MDataset(ROOT)\n\n t = time.perf_counter()\n print('Reading adjacency matrix...', end=' ', flush=True)\n path = f'{dataset.dir}/paper_to_paper_symmetric_gcn.pt'\n if osp.exists(path):\n adj_t = torch.load(path)\n else:\n path_sym = f'{dataset.dir}/paper_to_paper_symmetric.pt'\n if osp.exists(path_sym):\n adj_t = torch.load(path_sym)\n else:\n edge_index = dataset.edge_index('paper', 'cites', 'paper')\n edge_index = torch.from_numpy(edge_index)\n adj_t = SparseTensor(\n row=edge_index[0], col=edge_index[1],\n sparse_sizes=(dataset.num_papers, dataset.num_papers),\n is_sorted=True)\n adj_t = adj_t.to_symmetric()\n torch.save(adj_t, path_sym)\n adj_t = gcn_norm(adj_t, add_self_loops=True)\n torch.save(adj_t, path)\n print(f'Done! [{time.perf_counter() - t:.2f}s]')\n\n train_idx = dataset.get_idx_split('train')\n valid_idx = dataset.get_idx_split('valid')\n test_idx = dataset.get_idx_split('test')\n num_features = dataset.num_paper_features\n\n pbar = tqdm(total=args.num_layers * (num_features // 128))\n pbar.set_description('Pre-processing node features')\n\n for j in range(0, num_features, 128): # Run spmm in column-wise chunks...\n x = dataset.paper_feat[:, j:min(j + 128, num_features)]\n x = torch.from_numpy(x.astype(np.float32))\n\n for i in range(1, args.num_layers + 1):\n x = adj_t @ x\n np.save(f'{dataset.dir}/x_train_{i}_{j}.npy', x[train_idx].numpy())\n np.save(f'{dataset.dir}/x_valid_{i}_{j}.npy', x[valid_idx].numpy())\n np.save(f'{dataset.dir}/x_test_{i}_{j}.npy', x[test_idx].numpy())\n pbar.update(1)\n pbar.close()\n\n t = time.perf_counter()\n print('Merging node features...', end=' ', flush=True)\n for i in range(1, args.num_layers + 1):\n x_train, x_valid, x_test = [], [], []\n for j in range(0, num_features, 128):\n x_train += [np.load(f'{dataset.dir}/x_train_{i}_{j}.npy')]\n x_valid += [np.load(f'{dataset.dir}/x_valid_{i}_{j}.npy')]\n x_test += [np.load(f'{dataset.dir}/x_test_{i}_{j}.npy')]\n x_train = np.concatenate(x_train, axis=-1)\n x_valid = np.concatenate(x_valid, axis=-1)\n x_test = np.concatenate(x_test, axis=-1)\n np.save(f'{dataset.dir}/x_train_{i}.npy', x_train)\n np.save(f'{dataset.dir}/x_valid_{i}.npy', x_valid)\n np.save(f'{dataset.dir}/x_test_{i}.npy', x_test)\n print(f'Done! [{time.perf_counter() - t:.2f}s]')\n\n t = time.perf_counter()\n print('Cleaning up...', end=' ', flush=True)\n for i in range(1, args.num_layers + 1):\n for j in range(0, num_features, 128):\n os.remove(f'{dataset.dir}/x_train_{i}_{j}.npy')\n os.remove(f'{dataset.dir}/x_valid_{i}_{j}.npy')\n os.remove(f'{dataset.dir}/x_test_{i}_{j}.npy')\n print(f'Done! [{time.perf_counter() - t:.2f}s]')\n" ]
[ [ "numpy.concatenate", "torch.save", "numpy.load", "numpy.save", "torch.from_numpy", "torch.load" ] ]
MeltingCake/acai
[ "9627e55ff63aa3086deea4205258f5a4335ecae0" ]
[ "create_datasets.py" ]
[ "# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n#!/usr/bin/env python\n\"\"\"Script to download all datasets and create .tfrecord files.\n\"\"\"\n\nimport collections\nimport gzip\nimport os\nimport tarfile\nimport tempfile\nimport urllib\nimport zipfile\n\nfrom google_drive_downloader import GoogleDriveDownloader as gdd\nimport numpy as np\nimport scipy.io\nimport tensorflow as tf\nfrom lib.data import DATA_DIR\nfrom tqdm import trange, tqdm\n\nURLS = {\n 'svhn': 'http://ufldl.stanford.edu/housenumbers/{}_32x32.mat',\n 'cifar10': 'https://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz',\n 'celeba': '0B7EVK8r0v71pZjFTYXZWM3FlRnM',\n 'mnist': 'https://storage.googleapis.com/cvdf-datasets/mnist/{}.gz',\n}\n\n\ndef _encode_png(images):\n raw = []\n with tf.Session() as sess, tf.device('cpu:0'):\n image_x = tf.placeholder(tf.uint8, [None, None, None], 'image_x')\n to_png = tf.image.encode_png(image_x)\n for x in trange(images.shape[0], desc='PNG Encoding', leave=False):\n raw.append(sess.run(to_png, feed_dict={image_x: images[x]}))\n return raw\n\n\ndef _load_svhn():\n splits = collections.OrderedDict()\n for split in ['train', 'test', 'extra']:\n with tempfile.NamedTemporaryFile() as f:\n urllib.request.urlretrieve(URLS['svhn'].format(split), f.name)\n data_dict = scipy.io.loadmat(f.name)\n dataset = {}\n dataset['images'] = np.transpose(data_dict['X'], [3, 0, 1, 2])\n dataset['images'] = _encode_png(dataset['images'])\n dataset['labels'] = data_dict['y'].reshape((-1))\n # SVHN raw data uses labels from 1 to 10; use 0 to 9 instead.\n dataset['labels'] -= 1\n splits[split] = dataset\n return splits\n\n\ndef _load_cifar10():\n def unflatten(images):\n return np.transpose(images.reshape((images.shape[0], 3, 32, 32)),\n [0, 2, 3, 1])\n\n with tempfile.NamedTemporaryFile() as f:\n urllib.request.urlretrieve(URLS['cifar10'], f.name)\n tar = tarfile.open(fileobj=f)\n train_data_batches, train_data_labels = [], []\n for batch in range(1, 6):\n data_dict = scipy.io.loadmat(tar.extractfile(\n 'cifar-10-batches-mat/data_batch_{}.mat'.format(batch)))\n train_data_batches.append(data_dict['data'])\n train_data_labels.append(data_dict['labels'].flatten())\n train_set = {'images': np.concatenate(train_data_batches, axis=0),\n 'labels': np.concatenate(train_data_labels, axis=0)}\n data_dict = scipy.io.loadmat(tar.extractfile(\n 'cifar-10-batches-mat/test_batch.mat'))\n test_set = {'images': data_dict['data'],\n 'labels': data_dict['labels'].flatten()}\n train_set['images'] = _encode_png(unflatten(train_set['images']))\n test_set['images'] = _encode_png(unflatten(test_set['images']))\n return dict(train=train_set, test=test_set)\n\n\ndef _load_celeba():\n with tempfile.NamedTemporaryFile() as f:\n gdd.download_file_from_google_drive(\n file_id=URLS['celeba'], dest_path=f.name, overwrite=True)\n zip_f = zipfile.ZipFile(f)\n images = []\n for image_file in tqdm(zip_f.namelist(), 'Decompressing', leave=False):\n if os.path.splitext(image_file)[1] == '.jpg':\n with zip_f.open(image_file) as image_f:\n images.append(image_f.read())\n train_set = {'images': images, 'labels': np.zeros(len(images), int)}\n return dict(train=train_set)\n\n\ndef _load_mnist():\n def _read32(data):\n dt = np.dtype(np.uint32).newbyteorder('>')\n return np.frombuffer(data.read(4), dtype=dt)[0]\n\n image_filename = '{}-images-idx3-ubyte'\n label_filename = '{}-labels-idx1-ubyte'\n split_files = collections.OrderedDict(\n [('train', 'train'), ('test', 't10k')])\n splits = collections.OrderedDict()\n for split, split_file in split_files.items():\n with tempfile.NamedTemporaryFile() as f:\n urllib.request.urlretrieve(\n URLS['mnist'].format(image_filename.format(split_file)),\n f.name)\n with gzip.GzipFile(fileobj=f, mode='r') as data:\n assert _read32(data) == 2051\n n_images = _read32(data)\n row = _read32(data)\n col = _read32(data)\n images = np.frombuffer(\n data.read(n_images * row * col), dtype=np.uint8)\n images = images.reshape((n_images, row, col, 1))\n with tempfile.NamedTemporaryFile() as f:\n urllib.request.urlretrieve(\n URLS['mnist'].format(label_filename.format(split_file)),\n f.name)\n with gzip.GzipFile(fileobj=f, mode='r') as data:\n assert _read32(data) == 2049\n n_labels = _read32(data)\n labels = np.frombuffer(data.read(n_labels), dtype=np.uint8)\n splits[split] = {'images': _encode_png(images), 'labels': labels}\n return splits\n\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\n\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef _save_as_tfrecord(data, filename):\n assert len(data['images']) == len(data['labels'])\n filename = os.path.join(DATA_DIR, filename + '.tfrecord')\n print('Saving dataset:', filename)\n with tf.python_io.TFRecordWriter(filename) as writer:\n for x in trange(len(data['images']), desc='Building records'):\n feat = dict(label=_int64_feature(data['labels'][x]),\n image=_bytes_feature(data['images'][x]))\n record = tf.train.Example(features=tf.train.Features(feature=feat))\n writer.write(record.SerializeToString())\n\n\nLOADERS = [\n ('mnist', _load_mnist),\n ('cifar10', _load_cifar10),\n ('svhn', _load_svhn),\n ('celeba', _load_celeba)\n]\n\nif __name__ == '__main__':\n try:\n os.makedirs(DATA_DIR)\n except OSError:\n pass\n for name, loader in LOADERS:\n print('Preparing', name)\n datas = loader()\n print(datas)\n # for sub_name, data in datas.items():\n # _save_as_tfrecord(data, '%s-%s' % (name, sub_name))\n" ]
[ [ "numpy.concatenate", "tensorflow.train.BytesList", "tensorflow.train.Int64List", "tensorflow.train.Features", "tensorflow.Session", "tensorflow.python_io.TFRecordWriter", "tensorflow.placeholder", "numpy.transpose", "tensorflow.device", "tensorflow.image.encode_png", "numpy.dtype" ] ]
neilfrndes/predictive-maintenance
[ "81026ad8658a595766ea5f8ba09153773431570b" ]
[ "src/run.py" ]
[ "# To add a new cell, type ''\n# To add a new markdown cell, type ' [markdown]'\n\nimport logging\nfrom timeit import default_timer as timer\n\nimport keras\nimport numpy as np\nimport pandas as pd\nfrom keras.layers import LSTM, Dense, Dropout\nfrom keras.models import Sequential\nfrom sklearn import preprocessing\nfrom sklearn.metrics import confusion_matrix, precision_score, recall_score\n\nfrom common import STATS, calculate_stats\n\n# Setup logging\nLOG_LEVEL = logging.INFO\nlogging.basicConfig(format='%(levelname)s:%(message)s', level=LOG_LEVEL)\nlogger = logging.getLogger(__name__)\nlogger.setLevel(LOG_LEVEL)\n\nlogger.info(\"Starting benchmark...\")\n\n# Setting random seed for reproducibility\nnp.random.seed(1234)\nPYTHONHASHSEED = 0\n\n# Parameters\nNUM_LOOPS = 10\nMIN_SEQUENCE_LENGTH = 50\nTRAINING_PARAMS = dict(\n epochs=10,\n batch_size=200,\n validation_split=0.05,\n verbose=1,\n)\nINFERENCING_PARAMS = dict(\n verbose=1,\n batch_size=200\n)\n\n# TRAINING DATA\n# Load dataset and label columns\ntrain_df = pd.read_csv('../data/train.csv', sep=\" \", header=None)\ntrain_df.drop(train_df.columns[[26, 27]], axis=1, inplace=True)\ntrain_df.columns = [\n 'id', 'cycle', 'setting1', 'setting2', 'setting3', 's1', 's2', 's3', 's4',\n 's5', 's6', 's7', 's8', 's9', 's10', 's11', 's12', 's13', 's14', 's15',\n 's16', 's17', 's18', 's19', 's20', 's21'\n]\n\n# Generate remaining useful life (RUL) feature\nrul = pd.DataFrame(train_df.groupby('id')['cycle'].max()).reset_index()\nrul.columns = ['id', 'max']\ntrain_df = train_df.merge(rul, on=['id'], how='left')\ntrain_df['RUL'] = train_df['max'] - train_df['cycle']\ntrain_df.drop('max', axis=1, inplace=True)\n\n# generate label columns for training data\nw1 = 30\nw0 = 15\ntrain_df['label1'] = np.where(train_df['RUL'] <= w1, 1, 0)\ntrain_df['label2'] = train_df['label1']\ntrain_df.loc[train_df['RUL'] <= w0, 'label2'] = 2\n\n# MinMax normalization\ntrain_df['cycle_norm'] = train_df['cycle']\ncols_normalize = train_df.columns.difference(\n ['id', 'cycle', 'RUL', 'label1', 'label2'])\nmin_max_scaler = preprocessing.MinMaxScaler()\nnorm_train_df = pd.DataFrame(min_max_scaler.fit_transform(\n train_df[cols_normalize]),\n columns=cols_normalize,\n index=train_df.index)\njoin_df = train_df[train_df.columns.difference(cols_normalize)].join(\n norm_train_df)\ntrain_df = join_df.reindex(columns=train_df.columns)\n\n\n# function to reshape features into (samples, time steps, features)\ndef gen_sequence(id_df, seq_length, seq_cols):\n \"\"\" Only sequences that meet the window-length are considered, no padding is used. This means for testing\n we need to drop those which are below the window-length. An alternative would be to pad sequences so that\n we can use shorter ones \"\"\"\n data_array = id_df[seq_cols].values\n num_elements = data_array.shape[0]\n for start, stop in zip(range(0, num_elements - seq_length),\n range(seq_length, num_elements)):\n yield data_array[start:stop, :]\n\n\n# pick the feature columns\nsensor_cols = ['s' + str(i) for i in range(1, 22)]\nsequence_cols = ['setting1', 'setting2', 'setting3', 'cycle_norm']\nsequence_cols.extend(sensor_cols)\n\n# generator for the sequences\nseq_gen = (list(\n gen_sequence(train_df[train_df['id'] == id], MIN_SEQUENCE_LENGTH,\n sequence_cols)) for id in train_df['id'].unique())\n\n# generate sequences and convert to numpy array\nseq_array = np.concatenate(list(seq_gen)).astype(np.float32)\n\n# function to generate labels\ndef gen_labels(id_df, seq_length, label):\n data_array = id_df[label].values\n num_elements = data_array.shape[0]\n return data_array[seq_length:num_elements, :]\n\n# generate labels\nlabel_gen = [\n gen_labels(train_df[train_df['id'] == id], MIN_SEQUENCE_LENGTH, ['label1'])\n for id in train_df['id'].unique()\n]\nlabel_array = np.concatenate(label_gen).astype(np.float32)\n\n\n# TEST DATA\n# read test data\ntest_df = pd.read_csv('../data/test.csv', sep=\" \", header=None)\ntest_df.drop(test_df.columns[[26, 27]], axis=1, inplace=True)\ntest_df.columns = [\n 'id', 'cycle', 'setting1', 'setting2', 'setting3', 's1', 's2', 's3', 's4',\n 's5', 's6', 's7', 's8', 's9', 's10', 's11', 's12', 's13', 's14', 's15',\n 's16', 's17', 's18', 's19', 's20', 's21'\n]\n\n# read ground truth data\ntruth_df = pd.read_csv('../data/truth.csv', sep=\" \", header=None)\ntruth_df.drop(truth_df.columns[[1]], axis=1, inplace=True)\n\n# min max normalization\ntest_df['cycle_norm'] = test_df['cycle']\nnorm_test_df = pd.DataFrame(min_max_scaler.transform(test_df[cols_normalize]),\n columns=cols_normalize,\n index=test_df.index)\ntest_join_df = test_df[test_df.columns.difference(cols_normalize)].join(\n norm_test_df)\ntest_df = test_join_df.reindex(columns=test_df.columns)\ntest_df = test_df.reset_index(drop=True)\n\n# generate RUL for test data\nrul = pd.DataFrame(test_df.groupby('id')['cycle'].max()).reset_index()\nrul.columns = ['id', 'max']\ntruth_df.columns = ['more']\ntruth_df['id'] = truth_df.index + 1\ntruth_df['max'] = rul['max'] + truth_df['more']\ntruth_df.drop('more', axis=1, inplace=True)\n\ntest_df = test_df.merge(truth_df, on=['id'], how='left')\ntest_df['RUL'] = test_df['max'] - test_df['cycle']\ntest_df.drop('max', axis=1, inplace=True)\n\n# generate label columns w0 and w1 for test data\ntest_df['label1'] = np.where(test_df['RUL'] <= w1, 1, 0)\ntest_df['label2'] = test_df['label1']\ntest_df.loc[test_df['RUL'] <= w0, 'label2'] = 2\n\n\n# Build LSTM network\nnb_features = seq_array.shape[2]\nnb_out = label_array.shape[1]\n\nmodel = Sequential()\n\nmodel.add(\n LSTM(input_shape=(MIN_SEQUENCE_LENGTH, nb_features),\n units=100,\n return_sequences=True))\nmodel.add(Dropout(0.2))\n\nmodel.add(LSTM(units=50, return_sequences=False))\nmodel.add(Dropout(0.4))\n\nmodel.add(Dense(units=nb_out, activation='sigmoid'))\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\nlogger.debug(model.summary())\n\n# Benchmark training\ntrain_times = []\nfor _ in range(NUM_LOOPS):\n start_time_train = timer()\n model.fit(seq_array,\n label_array,\n **TRAINING_PARAMS,\n callbacks=[\n keras.callbacks.EarlyStopping(monitor='val_loss',\n min_delta=0,\n patience=0,\n verbose=0,\n mode='auto')\n ])\n end_time_train = timer()\n train_times.append(end_time_train-start_time_train)\nlogger.info('Training Benchmark \\n%s\\n%s\\n\\n', STATS, calculate_stats(train_times))\n\n# Save model to inspect later\nmodel.save('model')\n\n# Training metrics\nscores = model.evaluate(seq_array, label_array, verbose=1, batch_size=200)\naccuracy = scores[1]\n\n# make predictions and compute confusion matrix\ny_pred = model.predict_classes(seq_array, **INFERENCING_PARAMS)\ny_true = label_array\ncm = confusion_matrix(y_true, y_pred)\n\n# compute precision and recall\nprecision = precision_score(y_true, y_pred)\nrecall = recall_score(y_true, y_pred)\nlogger.info(\n \"\\nTRAINING METRICS\\n\"\n \"Num Records: %d\\n\"\n \"Accuracy: %.2f\\n\"\n \"Precision: %.2f\\n\"\n \"Recall: %.2f\\n\"\n \"Confusion Matrix: \\n%s\\n\", len(label_array), accuracy, precision, recall, cm)\n\n\n# Test metrics\nseq_array_test_last = [\n test_df[test_df['id'] == id][sequence_cols].values[-MIN_SEQUENCE_LENGTH:]\n for id in test_df['id'].unique()\n if len(test_df[test_df['id'] == id]) >= MIN_SEQUENCE_LENGTH\n]\n\nseq_array_test_last = np.asarray(seq_array_test_last).astype(np.float32)\ny_mask = [\n len(test_df[test_df['id'] == id]) >= MIN_SEQUENCE_LENGTH\n for id in test_df['id'].unique()\n]\nlabel_array_test_last = test_df.groupby('id')['label1'].nth(-1)[y_mask].values\nlabel_array_test_last = label_array_test_last.reshape(\n label_array_test_last.shape[0], 1).astype(np.float32)\nlabel_array_test_last.shape\n\nscores_test = model.evaluate(seq_array_test_last,\n label_array_test_last,\n verbose=2)\naccuracy_test = scores_test[1]\n\n# make predictions and compute confusion matrix\n# Benchmark inferencing\ntest_times = []\nfor _ in range(NUM_LOOPS):\n start_time_test = timer()\n y_pred_test = model.predict_classes(seq_array_test_last)\n end_time_test = timer()\n test_times.append(end_time_test-start_time_test)\nlogger.info('Inferencing Benchmark \\n%s\\n%s\\n\\n', STATS, calculate_stats(test_times))\n\ny_true_test = label_array_test_last\ncm_test = confusion_matrix(y_true_test, y_pred_test)\n\nprecision_test = precision_score(y_true_test, y_pred_test)\nrecall_test = recall_score(y_true_test, y_pred_test)\nf1_test = 2 * (precision_test * recall_test) / (precision_test + recall_test)\n\nlogger.info(\n \"\\nINFERENCING METRICS\\n\"\n \"Num Records: %d\\n\"\n \"Accuracy: %.2f\\n\"\n \"Precision: %.2f\\n\"\n \"Recall: %.2f\\n\"\n \"F1 score: %.2f\\n\"\n \"Confusion Matrix: \\n%s\", len(label_array_test_last), accuracy_test, precision_test, recall_test, f1_test, cm_test)\n" ]
[ [ "numpy.concatenate", "sklearn.metrics.confusion_matrix", "numpy.asarray", "numpy.random.seed", "sklearn.metrics.precision_score", "numpy.where", "sklearn.preprocessing.MinMaxScaler", "pandas.read_csv", "sklearn.metrics.recall_score" ] ]
arahman010/MLlearningUd
[ "4c665ed5476733d921500a23962fd2020b604a95" ]
[ "svm/svm_author_id.py" ]
[ "#!/usr/bin/python\n\n\"\"\" \n This is the code to accompany the Lesson 2 (SVM) mini-project.\n\n Use a SVM to identify emails from the Enron corpus by their authors: \n Sara has label 0\n Chris has label 1\n\"\"\"\n \nimport sys\nfrom time import time\nsys.path.append(\"../tools/\")\nfrom email_preprocess import preprocess\nimport numpy as np\n\n### features_train and features_test are the features for the training\n### and testing datasets, respectively\n### labels_train and labels_test are the corresponding item labels\nfeatures_train, features_test, labels_train, labels_test = preprocess()\n\n\n\n\n#########################################################\n### your code goes here ###\nfrom sklearn.svm import SVC\nclf = SVC(kernel=\"rbf\",C = 10000.0)\n#features_train = features_train[:len(features_train)/100] \n#labels_train = labels_train[:len(labels_train)/100] \n\nclf.fit(features_train,labels_train)\npred = clf.predict(features_test)\n#########################################################\n\nprint(np.count_nonzero(pred == 1))\n\n#print(pred[10])\n#print(pred[26])\n#print(pred[50])\n\n#from sklearn.metrics import accuracy_score\n#acc = accuracy_score(pred, labels_test)\n\n#print(acc)\n#def submitAccuracy():\n# return acc\n" ]
[ [ "numpy.count_nonzero", "sklearn.svm.SVC" ] ]
mthrok/audio
[ "e7ea820eecb12aa9cdb7f72322a0ec9d99fd6974" ]
[ "examples/tutorials/audio_feature_augmentation_tutorial.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nAudio Feature Augmentation\n==========================\n\"\"\"\n\n# When running this tutorial in Google Colab, install the required packages\n# with the following.\n# !pip install torchaudio librosa\n\nimport torch\nimport torchaudio\nimport torchaudio.transforms as T\n\nprint(torch.__version__)\nprint(torchaudio.__version__)\n\n######################################################################\n# Preparing data and utility functions (skip this section)\n# --------------------------------------------------------\n#\n\n#@title Prepare data and utility functions. {display-mode: \"form\"}\n#@markdown\n#@markdown You do not need to look into this cell.\n#@markdown Just execute once and you are good to go.\n#@markdown\n#@markdown In this tutorial, we will use a speech data from [VOiCES dataset](https://iqtlabs.github.io/voices/), which is licensed under Creative Commos BY 4.0.\n\n#-------------------------------------------------------------------------------\n# Preparation of data and helper functions.\n#-------------------------------------------------------------------------------\n\nimport os\nimport requests\n\nimport librosa\nimport matplotlib.pyplot as plt\n\n\n_SAMPLE_DIR = \"_assets\"\n\nSAMPLE_WAV_SPEECH_URL = \"https://pytorch-tutorial-assets.s3.amazonaws.com/VOiCES_devkit/source-16k/train/sp0307/Lab41-SRI-VOiCES-src-sp0307-ch127535-sg0042.wav\"\nSAMPLE_WAV_SPEECH_PATH = os.path.join(_SAMPLE_DIR, \"speech.wav\")\n\nos.makedirs(_SAMPLE_DIR, exist_ok=True)\n\ndef _fetch_data():\n uri = [\n (SAMPLE_WAV_SPEECH_URL, SAMPLE_WAV_SPEECH_PATH),\n ]\n for url, path in uri:\n with open(path, 'wb') as file_:\n file_.write(requests.get(url).content)\n\n_fetch_data()\n\ndef _get_sample(path, resample=None):\n effects = [\n [\"remix\", \"1\"]\n ]\n if resample:\n effects.extend([\n [\"lowpass\", f\"{resample // 2}\"],\n [\"rate\", f'{resample}'],\n ])\n return torchaudio.sox_effects.apply_effects_file(path, effects=effects)\n\ndef get_speech_sample(*, resample=None):\n return _get_sample(SAMPLE_WAV_SPEECH_PATH, resample=resample)\n\ndef get_spectrogram(\n n_fft = 400,\n win_len = None,\n hop_len = None,\n power = 2.0,\n):\n waveform, _ = get_speech_sample()\n spectrogram = T.Spectrogram(\n n_fft=n_fft,\n win_length=win_len,\n hop_length=hop_len,\n center=True,\n pad_mode=\"reflect\",\n power=power,\n )\n return spectrogram(waveform)\n\ndef plot_spectrogram(spec, title=None, ylabel='freq_bin', aspect='auto', xmax=None):\n fig, axs = plt.subplots(1, 1)\n axs.set_title(title or 'Spectrogram (db)')\n axs.set_ylabel(ylabel)\n axs.set_xlabel('frame')\n im = axs.imshow(librosa.power_to_db(spec), origin='lower', aspect=aspect)\n if xmax:\n axs.set_xlim((0, xmax))\n fig.colorbar(im, ax=axs)\n plt.show(block=False)\n\n######################################################################\n# SpecAugment\n# -----------\n#\n# `SpecAugment <https://ai.googleblog.com/2019/04/specaugment-new-data-augmentation.html>`__\n# is a popular spectrogram augmentation technique.\n#\n# ``torchaudio`` implements ``TimeStretch``, ``TimeMasking`` and\n# ``FrequencyMasking``.\n#\n# TimeStretch\n# ~~~~~~~~~~~\n#\n\nspec = get_spectrogram(power=None)\nstretch = T.TimeStretch()\n\nrate = 1.2\nspec_ = stretch(spec, rate)\nplot_spectrogram(torch.abs(spec_[0]), title=f\"Stretched x{rate}\", aspect='equal', xmax=304)\n\nplot_spectrogram(torch.abs(spec[0]), title=\"Original\", aspect='equal', xmax=304)\n\nrate = 0.9\nspec_ = stretch(spec, rate)\nplot_spectrogram(torch.abs(spec_[0]), title=f\"Stretched x{rate}\", aspect='equal', xmax=304)\n\n######################################################################\n# TimeMasking\n# ~~~~~~~~~~~\n#\n\ntorch.random.manual_seed(4)\n\nspec = get_spectrogram()\nplot_spectrogram(spec[0], title=\"Original\")\n\nmasking = T.TimeMasking(time_mask_param=80)\nspec = masking(spec)\n\nplot_spectrogram(spec[0], title=\"Masked along time axis\")\n\n######################################################################\n# FrequencyMasking\n# ~~~~~~~~~~~~~~~~\n#\n\n\ntorch.random.manual_seed(4)\n\nspec = get_spectrogram()\nplot_spectrogram(spec[0], title=\"Original\")\n\nmasking = T.FrequencyMasking(freq_mask_param=80)\nspec = masking(spec)\n\nplot_spectrogram(spec[0], title=\"Masked along frequency axis\")\n" ]
[ [ "torch.random.manual_seed", "matplotlib.pyplot.show", "torch.abs", "matplotlib.pyplot.subplots" ] ]
Frank-Star-fn/transformers
[ "d1fcc90abf34cc498c8a65a717ad0d9354ceca97" ]
[ "tests/unispeech/test_modeling_unispeech.py" ]
[ "# coding=utf-8\n# Copyright 2021 The HuggingFace Inc. team. 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\"\"\" Testing suite for the PyTorch UniSpeech model. \"\"\"\n\nimport math\nimport unittest\n\nimport numpy as np\nimport pytest\nfrom datasets import load_dataset\n\nfrom transformers import UniSpeechConfig, is_torch_available\nfrom transformers.testing_utils import require_soundfile, require_torch, slow, torch_device\n\nfrom ..test_configuration_common import ConfigTester\nfrom ..test_modeling_common import (\n ModelTesterMixin,\n _config_zero_init,\n floats_tensor,\n ids_tensor,\n random_attention_mask,\n)\n\n\nif is_torch_available():\n import torch\n\n from transformers import (\n UniSpeechForCTC,\n UniSpeechForPreTraining,\n UniSpeechForSequenceClassification,\n UniSpeechModel,\n Wav2Vec2FeatureExtractor,\n Wav2Vec2Processor,\n )\n\n\nclass UniSpeechModelTester:\n def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=1024, # speech is longer\n is_training=False,\n hidden_size=16,\n feat_extract_norm=\"group\",\n feat_extract_dropout=0.0,\n feat_extract_activation=\"gelu\",\n conv_dim=(32, 32, 32),\n conv_stride=(4, 4, 4),\n conv_kernel=(8, 8, 8),\n conv_bias=False,\n num_conv_pos_embeddings=16,\n num_conv_pos_embedding_groups=2,\n num_hidden_layers=4,\n num_attention_heads=2,\n hidden_dropout_prob=0.1, # this is most likely not correctly set yet\n intermediate_size=20,\n layer_norm_eps=1e-5,\n hidden_act=\"gelu\",\n initializer_range=0.02,\n vocab_size=32,\n do_stable_layer_norm=False,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.hidden_size = hidden_size\n self.feat_extract_norm = feat_extract_norm\n self.feat_extract_dropout = feat_extract_dropout\n self.feat_extract_activation = feat_extract_activation\n self.conv_dim = conv_dim\n self.conv_stride = conv_stride\n self.conv_kernel = conv_kernel\n self.conv_bias = conv_bias\n self.num_conv_pos_embeddings = num_conv_pos_embeddings\n self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_dropout_prob = hidden_dropout_prob\n self.intermediate_size = intermediate_size\n self.layer_norm_eps = layer_norm_eps\n self.hidden_act = hidden_act\n self.initializer_range = initializer_range\n self.vocab_size = vocab_size\n self.do_stable_layer_norm = do_stable_layer_norm\n self.scope = scope\n\n output_seq_length = self.seq_length\n for kernel, stride in zip(self.conv_kernel, self.conv_stride):\n output_seq_length = (output_seq_length - (kernel - 1)) / stride\n self.output_seq_length = int(math.ceil(output_seq_length))\n self.encoder_seq_length = self.output_seq_length\n\n def prepare_config_and_inputs(self):\n input_values = floats_tensor([self.batch_size, self.seq_length], self.vocab_size)\n attention_mask = random_attention_mask([self.batch_size, self.seq_length])\n\n config = self.get_config()\n\n return config, input_values, attention_mask\n\n def get_config(self):\n return UniSpeechConfig(\n hidden_size=self.hidden_size,\n feat_extract_norm=self.feat_extract_norm,\n feat_extract_dropout=self.feat_extract_dropout,\n feat_extract_activation=self.feat_extract_activation,\n conv_dim=self.conv_dim,\n conv_stride=self.conv_stride,\n conv_kernel=self.conv_kernel,\n conv_bias=self.conv_bias,\n num_conv_pos_embeddings=self.num_conv_pos_embeddings,\n num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups,\n num_hidden_layers=self.num_hidden_layers,\n num_attention_heads=self.num_attention_heads,\n hidden_dropout_prob=self.hidden_dropout_prob,\n intermediate_size=self.intermediate_size,\n layer_norm_eps=self.layer_norm_eps,\n hidden_act=self.hidden_act,\n initializer_range=self.initializer_range,\n vocab_size=self.vocab_size,\n )\n\n def create_and_check_model(self, config, input_values, attention_mask):\n model = UniSpeechModel(config=config)\n model.to(torch_device)\n model.eval()\n result = model(input_values, attention_mask=attention_mask)\n self.parent.assertEqual(\n result.last_hidden_state.shape, (self.batch_size, self.output_seq_length, self.hidden_size)\n )\n\n def create_and_check_batch_inference(self, config, input_values, *args):\n # test does not pass for models making use of `group_norm`\n # check: https://github.com/pytorch/fairseq/issues/3227\n model = UniSpeechModel(config=config)\n model.to(torch_device)\n model.eval()\n\n input_values = input_values[:3]\n attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.bool)\n\n input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]]\n\n # pad input\n for i in range(len(input_lengths)):\n input_values[i, input_lengths[i] :] = 0.0\n attention_mask[i, input_lengths[i] :] = 0.0\n\n batch_outputs = model(input_values, attention_mask=attention_mask).last_hidden_state\n\n for i in range(input_values.shape[0]):\n input_slice = input_values[i : i + 1, : input_lengths[i]]\n output = model(input_slice).last_hidden_state\n\n batch_output = batch_outputs[i : i + 1, : output.shape[1]]\n self.parent.assertTrue(torch.allclose(output, batch_output, atol=1e-3))\n\n def check_ctc_loss(self, config, input_values, *args):\n model = UniSpeechForCTC(config=config)\n model.to(torch_device)\n\n # make sure that dropout is disabled\n model.eval()\n\n input_values = input_values[:3]\n attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long)\n\n input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]]\n max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths))\n labels = ids_tensor((input_values.shape[0], min(max_length_labels) - 1), model.config.vocab_size)\n\n # pad input\n for i in range(len(input_lengths)):\n input_values[i, input_lengths[i] :] = 0.0\n attention_mask[i, input_lengths[i] :] = 0\n\n model.config.ctc_loss_reduction = \"sum\"\n sum_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item()\n\n model.config.ctc_loss_reduction = \"mean\"\n mean_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item()\n\n self.parent.assertTrue(isinstance(sum_loss, float))\n self.parent.assertTrue(isinstance(mean_loss, float))\n\n def check_seq_classifier_loss(self, config, input_values, *args):\n model = UniSpeechForSequenceClassification(config=config)\n model.to(torch_device)\n\n # make sure that dropout is disabled\n model.eval()\n\n input_values = input_values[:3]\n attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long)\n\n input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]]\n labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label))\n\n # pad input\n for i in range(len(input_lengths)):\n input_values[i, input_lengths[i] :] = 0.0\n attention_mask[i, input_lengths[i] :] = 0\n\n masked_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item()\n unmasked_loss = model(input_values, labels=labels).loss.item()\n\n self.parent.assertTrue(isinstance(masked_loss, float))\n self.parent.assertTrue(isinstance(unmasked_loss, float))\n self.parent.assertTrue(masked_loss != unmasked_loss)\n\n def check_ctc_training(self, config, input_values, *args):\n config.ctc_zero_infinity = True\n model = UniSpeechForCTC(config=config)\n model.to(torch_device)\n model.train()\n\n # freeze feature encoder\n model.freeze_feature_encoder()\n\n input_values = input_values[:3]\n\n input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]]\n max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths))\n labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size)\n\n # pad input\n for i in range(len(input_lengths)):\n input_values[i, input_lengths[i] :] = 0.0\n\n if max_length_labels[i] < labels.shape[-1]:\n # it's important that we make sure that target lenghts are at least\n # one shorter than logit lenghts to prevent -inf\n labels[i, max_length_labels[i] - 1 :] = -100\n\n loss = model(input_values, labels=labels).loss\n self.parent.assertFalse(torch.isinf(loss).item())\n\n loss.backward()\n\n def check_seq_classifier_training(self, config, input_values, *args):\n config.ctc_zero_infinity = True\n model = UniSpeechForSequenceClassification(config=config)\n model.to(torch_device)\n model.train()\n\n # freeze everything but the classification head\n model.freeze_base_model()\n\n input_values = input_values[:3]\n\n input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]]\n labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label))\n\n # pad input\n for i in range(len(input_lengths)):\n input_values[i, input_lengths[i] :] = 0.0\n\n loss = model(input_values, labels=labels).loss\n self.parent.assertFalse(torch.isinf(loss).item())\n\n loss.backward()\n\n def check_labels_out_of_vocab(self, config, input_values, *args):\n model = UniSpeechForCTC(config)\n model.to(torch_device)\n model.train()\n\n input_values = input_values[:3]\n\n input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]]\n max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths))\n labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size + 100)\n\n with pytest.raises(ValueError):\n model(input_values, labels=labels)\n\n def prepare_config_and_inputs_for_common(self):\n config, input_values, attention_mask = self.prepare_config_and_inputs()\n inputs_dict = {\"input_values\": input_values, \"attention_mask\": attention_mask}\n return config, inputs_dict\n\n\n@require_torch\nclass UniSpeechRobustModelTest(ModelTesterMixin, unittest.TestCase):\n all_model_classes = (\n (UniSpeechForCTC, UniSpeechModel, UniSpeechForSequenceClassification, UniSpeechForPreTraining)\n if is_torch_available()\n else ()\n )\n test_pruning = False\n test_headmasking = False\n test_torchscript = False\n\n def setUp(self):\n self.model_tester = UniSpeechModelTester(\n self, conv_stride=(3, 3, 3), feat_extract_norm=\"layer\", do_stable_layer_norm=True\n )\n self.config_tester = ConfigTester(self, config_class=UniSpeechConfig, hidden_size=37)\n\n def test_config(self):\n self.config_tester.run_common_tests()\n\n def test_model(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_model(*config_and_inputs)\n\n def test_batched_inference(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_batch_inference(*config_and_inputs)\n\n def test_ctc_loss_inference(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.check_ctc_loss(*config_and_inputs)\n\n def test_seq_classifier_loss_inference(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.check_seq_classifier_loss(*config_and_inputs)\n\n def test_ctc_train(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.check_ctc_training(*config_and_inputs)\n\n def test_seq_classifier_train(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.check_seq_classifier_training(*config_and_inputs)\n\n def test_labels_out_of_vocab(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.check_labels_out_of_vocab(*config_and_inputs)\n\n # UniSpeech has no inputs_embeds\n def test_inputs_embeds(self):\n pass\n\n # `input_ids` is renamed to `input_values`\n def test_forward_signature(self):\n pass\n\n # UniSpeech cannot resize token embeddings\n # since it has no tokens embeddings\n def test_resize_tokens_embeddings(self):\n pass\n\n # UniSpeech has no inputs_embeds\n # and thus the `get_input_embeddings` fn\n # is not implemented\n def test_model_common_attributes(self):\n pass\n\n def test_retain_grad_hidden_states_attentions(self):\n config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()\n config.output_hidden_states = True\n config.output_attentions = True\n\n # no need to test all models as different heads yield the same functionality\n model_class = self.all_model_classes[0]\n model = model_class(config)\n model.to(torch_device)\n\n # set layer drop to 0\n model.config.layerdrop = 0.0\n\n input_values = inputs_dict[\"input_values\"]\n\n input_lengths = torch.tensor(\n [input_values.shape[1] for _ in range(input_values.shape[0])], dtype=torch.long, device=torch_device\n )\n output_lengths = model._get_feat_extract_output_lengths(input_lengths)\n\n labels = ids_tensor((input_values.shape[0], output_lengths[0] - 2), self.model_tester.vocab_size)\n inputs_dict[\"attention_mask\"] = torch.ones_like(inputs_dict[\"attention_mask\"])\n inputs_dict[\"labels\"] = labels\n\n outputs = model(**inputs_dict)\n\n output = outputs[0]\n\n # Encoder-/Decoder-only models\n hidden_states = outputs.hidden_states[0]\n attentions = outputs.attentions[0]\n\n hidden_states.retain_grad()\n attentions.retain_grad()\n\n output.flatten()[0].backward(retain_graph=True)\n\n self.assertIsNotNone(hidden_states.grad)\n self.assertIsNotNone(attentions.grad)\n\n def test_initialization(self):\n config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()\n\n configs_no_init = _config_zero_init(config)\n for model_class in self.all_model_classes:\n model = model_class(config=configs_no_init)\n for name, param in model.named_parameters():\n uniform_init_parms = [\n \"conv.weight\",\n \"masked_spec_embed\",\n \"codevectors\",\n \"quantizer.weight_proj.weight\",\n \"project_hid.weight\",\n \"project_hid.bias\",\n \"project_q.weight\",\n \"project_q.bias\",\n \"feature_projection.projection.weight\",\n \"feature_projection.projection.bias\",\n ]\n if param.requires_grad:\n if any([x in name for x in uniform_init_parms]):\n self.assertTrue(\n -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0,\n msg=f\"Parameter {name} of model {model_class} seems not properly initialized\",\n )\n else:\n self.assertIn(\n ((param.data.mean() * 1e9).round() / 1e9).item(),\n [0.0, 1.0],\n msg=f\"Parameter {name} of model {model_class} seems not properly initialized\",\n )\n\n # overwrite from test_modeling_common\n def _mock_init_weights(self, module):\n if hasattr(module, \"weight\") and module.weight is not None:\n module.weight.data.fill_(3)\n if hasattr(module, \"weight_g\") and module.weight_g is not None:\n module.weight_g.data.fill_(3)\n if hasattr(module, \"weight_v\") and module.weight_v is not None:\n module.weight_v.data.fill_(3)\n if hasattr(module, \"bias\") and module.bias is not None:\n module.bias.data.fill_(3)\n if hasattr(module, \"codevectors\") and module.codevectors is not None:\n module.codevectors.data.fill_(3)\n if hasattr(module, \"masked_spec_embed\") and module.masked_spec_embed is not None:\n module.masked_spec_embed.data.fill_(3)\n\n def test_mask_feature_prob_ctc(self):\n model = UniSpeechForCTC.from_pretrained(\n \"hf-internal-testing/tiny-random-unispeech\", mask_feature_prob=0.2, mask_feature_length=2\n )\n model.to(torch_device).train()\n processor = Wav2Vec2Processor.from_pretrained(\n \"hf-internal-testing/tiny-random-unispeech\", return_attention_mask=True\n )\n\n batch_duration_in_seconds = [1, 3, 2, 6]\n input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds]\n\n batch = processor(\n input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors=\"pt\"\n )\n\n logits = model(\n input_values=batch[\"input_values\"].to(torch_device),\n attention_mask=batch[\"attention_mask\"].to(torch_device),\n ).logits\n\n self.assertEqual(logits.shape, (4, 1498, 32))\n\n def test_mask_time_prob_ctc(self):\n model = UniSpeechForCTC.from_pretrained(\n \"hf-internal-testing/tiny-random-unispeech\", mask_time_prob=0.2, mask_time_length=2\n )\n model.to(torch_device).train()\n processor = Wav2Vec2Processor.from_pretrained(\n \"hf-internal-testing/tiny-random-unispeech\", return_attention_mask=True\n )\n\n batch_duration_in_seconds = [1, 3, 2, 6]\n input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds]\n\n batch = processor(\n input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors=\"pt\"\n )\n\n logits = model(\n input_values=batch[\"input_values\"].to(torch_device),\n attention_mask=batch[\"attention_mask\"].to(torch_device),\n ).logits\n\n self.assertEqual(logits.shape, (4, 1498, 32))\n\n def test_mask_time_feature_prob_ctc_single_batch(self):\n model = UniSpeechForCTC.from_pretrained(\n \"hf-internal-testing/tiny-random-unispeech\",\n mask_time_prob=0.2,\n mask_feature_prob=0.2,\n mask_time_length=2,\n mask_feature_length=2,\n )\n model.to(torch_device).train()\n processor = Wav2Vec2Processor.from_pretrained(\n \"hf-internal-testing/tiny-random-unispeech\", return_attention_mask=True\n )\n\n batch_duration_in_seconds = [6]\n input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds]\n\n batch = processor(\n input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors=\"pt\"\n )\n\n logits = model(\n input_values=batch[\"input_values\"].to(torch_device),\n attention_mask=batch[\"attention_mask\"].to(torch_device),\n ).logits\n\n self.assertEqual(logits.shape, (1, 1498, 32))\n\n @unittest.skip(reason=\"Feed forward chunking is not implemented\")\n def test_feed_forward_chunking(self):\n pass\n\n @slow\n def test_model_from_pretrained(self):\n model = UniSpeechModel.from_pretrained(\"microsoft/unispeech-large-1500h-cv\")\n self.assertIsNotNone(model)\n\n\n@require_torch\n@require_soundfile\n@slow\nclass UniSpeechModelIntegrationTest(unittest.TestCase):\n def _load_datasamples(self, num_samples):\n import soundfile as sf\n\n ids = [f\"1272-141231-000{i}\" for i in range(num_samples)]\n\n # map files to raw\n def map_to_array(batch):\n speech, _ = sf.read(batch[\"file\"])\n batch[\"speech\"] = speech\n return batch\n\n ds = load_dataset(\"patrickvonplaten/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n\n ds = ds.filter(lambda x: x[\"id\"] in ids).sort(\"id\").map(map_to_array)\n\n return ds[\"speech\"][:num_samples]\n\n def _load_superb(self, task, num_samples):\n\n ds = load_dataset(\"anton-l/superb_dummy\", task, split=\"test\")\n\n return ds[:num_samples]\n\n def test_inference_pretraining(self):\n model = UniSpeechForPreTraining.from_pretrained(\"microsoft/unispeech-large-1500h-cv\")\n model.to(torch_device)\n feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(\"facebook/wav2vec2-large-xlsr-53\")\n input_speech = self._load_datasamples(2)\n\n inputs_dict = feature_extractor(input_speech, return_tensors=\"pt\", padding=True)\n\n with torch.no_grad():\n torch.manual_seed(0)\n outputs = model(\n inputs_dict.input_values.to(torch_device),\n attention_mask=inputs_dict.attention_mask.to(torch_device),\n )\n\n # compute cosine similarity\n cosine_sim = torch.cosine_similarity(outputs.projected_states, outputs.projected_quantized_states, dim=-1)\n\n # pretrained model should have learned a high cosine similarity\n self.assertTrue(cosine_sim.mean() > 0.5)\n\n # fmt: off\n expected_cosine_sim_slice = torch.tensor(\n [[0.8290, 0.8335, 0.8815, 0.8580, 0.8249],\n [0.8892, 0.9221, 0.8711, 0.8601, 0.8482]],\n device=torch_device,\n )\n # fmt: on\n\n self.assertTrue(torch.allclose(cosine_sim[:, :5], expected_cosine_sim_slice, atol=1e-3))\n" ]
[ [ "torch.cosine_similarity", "torch.no_grad", "torch.ones", "torch.manual_seed", "torch.tensor", "torch.isinf", "torch.ones_like", "numpy.random.random", "torch.allclose" ] ]
Pankajd007/ML-Algortihm-for-Supervised-Learning
[ "d804e7eeace1e5187b156b2fa3e71125b2a3448a" ]
[ "Decision Tree Regressor/decision_tree_regression.py" ]
[ "# Decision Tree Regression\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('Position_Salaries.csv')\nX = dataset.iloc[:, 1:2].values\ny = dataset.iloc[:, 2].values\n\n# Splitting the dataset into the Training set and Test set\n\"\"\"from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\"\"\"\n\n# Feature Scaling\n\"\"\"from sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\nsc_y = StandardScaler()\ny_train = sc_y.fit_transform(y_train.reshape(-1,1))\"\"\"\n\n# Fitting Decision Tree Regression to the dataset\nfrom sklearn.tree import DecisionTreeRegressor\nregressor = DecisionTreeRegressor(random_state = 0)\nregressor.fit(X, y)\n\n# Predicting a new result\ny_pred = regressor.predict([[6.5]])\n\n# Visualising the Decision Tree Regression results (higher resolution)\nX_grid = np.arange(min(X), max(X), 0.01)\nX_grid = X_grid.reshape((len(X_grid), 1))\nplt.scatter(X, y, color = 'red')\nplt.plot(X_grid, regressor.predict(X_grid), color = 'blue')\nplt.title('Truth or Bluff (Decision Tree Regression)')\nplt.xlabel('Position level')\nplt.ylabel('Salary')\nplt.show()" ]
[ [ "matplotlib.pyplot.xlabel", "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "sklearn.tree.DecisionTreeRegressor", "matplotlib.pyplot.scatter", "pandas.read_csv" ] ]
Jabi7/QPD
[ "7afdb253963ff566705a239a3a4202282ac3b826" ]
[ "QGT.py" ]
[ "import numpy as np\nfrom math import *\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\nfrom tabulate import tabulate\n\n\n\nC = np.array([1,0])\nD = np.array([0,1])\n\nCC = np.kron(C,C)\nDD = np.kron(D,D)\n\n\n# To find conjugate transpose\ndef H(j):\n return j.conjugate().T \n\n# Entanglemet operator J(gamma)\ndef J(g):\n j = np.zeros((4,4), dtype = complex)\n for i in range(4):\n j[i][i] = cos(g/2)\n j[0][3] = -1j*sin(g/2)\n j[1][2] = 1j*sin(g/2)\n j[2][1] = 1j*sin(g/2)\n j[3][0] = -1j*sin(g/2)\n return j\n\n\n# two parameters staegy operator\ndef U1(theta, phi):\n u = np.array([[np.exp(1j*phi)*cos(theta/2), sin(theta/2)], \n [-sin(theta/2), np.exp(-1j*phi)*cos(theta/2)]])\n return u\n\n# Three parameters staegy operator\n\ndef U2(theta, a, b):\n u = np.array([[np.exp(1j*a)*cos(theta/2), 1j*np.exp(1j*b)*sin(theta/2)], \n [1j*np.exp(-1j*b)*sin(theta/2), np.exp(-1j*a)*cos(theta/2)]])\n return u\n\n# final state\n\ndef Psi(J, Ua, Ub):\n psi = np.matmul(np.matmul(H(J), np.kron(Ua,Ub)),np.matmul(J, CC))\n return psi\n\ndef expected_payoff(p, g, Ua, Ub):\n a, b= 0, 0\n psi = Psi(J(g), Ua, Ub)\n for i in range(len(p[0])):\n a += p[0][i]*(abs(psi[i]))**2\n b += p[1][i]*(abs(psi[i]))**2\n return a, b\n\n# For plotting\n\ndef payoff_plot(gamma, p, x, y):\n \n j = J(gamma)\n Ua = U(x*pi,0) if x >= 0 else U(0,-x*pi/2)\n Ub = U(y*pi,0) if y >= 0 else U(0,-y*pi/2)\n psi = Psi(j,Ua,Ub)\n a, b = expected_payoff(p, psi)\n return a\n\ndef HD_payoff_matrix(v, i, d):\n return np.array([[(v - i)/2, v, 0, v/2 -d],[(v - i)/2, 0, v, v/2 -d]])\n\ndef Psi_dense(J, Ua, Ub):\n rhoi = np.outer(CC,CC)\n rho1 = np.matmul(J, np.matmul(rhoi, H(J)))\n rho2 = np.matmul(np.kron(Ua, Ub), np.matmul(rho1, H(np.kron(Ua, Ub))))\n rhof = np.matmul(H(J), np.matmul(rho2, J))\n return rhof\n\n# The payoff operator \ndef payoff_op(p):\n C = np.array([1,0])\n D = np.array([0,1])\n basis = {\n 'b0' : np.kron(C,C),\n 'b1' : np.kron(C,D),\n 'b2' : np.kron(D,C),\n 'b3' : np.kron(D,D)\n }\n pa, pb = 0, 0\n for i in range(len(p[0])):\n pa += p[0][i]*np.outer(basis['b'+str(i)], basis['b'+str(i)])\n pb += p[1][i]*np.outer(basis['b'+str(i)], basis['b'+str(i)]) \n return pa, pb\n\n# expected payoff for mixed strategies with probability p and q \ndef mixed_payoff(j, ua1, ua2, ub1, ub2, p, q, payoff):\n rho = p*q*Psi_dense(j, ua1, ub1) + p*(1-q)*Psi_dense(j, ua1, ub2) + (1-p)*q*Psi_dense(j, ua2, ub1) + (1-p)*(1-q)*Psi_dense(j, ua2, ub2) \n P = payoff_op(payoff)\n a = np.trace(np.matmul(P[0],rho))\n b = np.trace(np.matmul(P[1],rho))\n return a.real, b.real\n\n\ndef payoff_tableg(U, po, g, sl, sa):\n t = [['', '']]\n t[0] += sl\n def mp(a1, a2, b1, b2, p, q):\n al, bo = mixed_payoff(J(g), a1, a2, b1, b2, p, q, po)\n return round(al.real,2), round(bo.real,2)\n for i in range(len(sl)):\n t.append(['', sl[i]])\n for j in range(len(sl)):\n if len(sa[sl[i]][0]) == 3:\n t[1+i].append(mp(U(sa[sl[i]][0][0], sa[sl[i]][0][1]), U(sa[sl[i]][1][0], sa[sl[i]][1][1]), U(sa[sl[j]][0][0], sa[sl[j]][0][1]), U(sa[sl[j]][1][0], sa[sl[j]][1][1]), sa[sl[i]][0][2], sa[sl[j]][1][2]))\n elif len(sa[sl[i]][0]) == 4:\n t[1+i].append(mp(U(sa[sl[i]][0][0], sa[sl[i]][0][1], sa[sl[i]][0][2]), U(sa[sl[i]][1][0], sa[sl[i]][1][1], sa[sl[i]][1][2]), U(sa[sl[j]][0][0], sa[sl[j]][0][1], sa[sl[j]][0][2]), U(sa[sl[j]][1][0], sa[sl[j]][1][1], sa[sl[j]][1][2]), sa[sl[i]][0][3], sa[sl[j]][1][3]))\n \n t[1][0] = 'Al'\n headers = [\"Bob\",'']\n print(tabulate(t, headers, tablefmt=\"pretty\"))\n" ]
[ [ "numpy.array", "numpy.matmul", "numpy.zeros", "numpy.exp", "numpy.outer", "numpy.kron" ] ]
mkelley/comadyn
[ "7a75908bd58172fc95e076a8ce788a94cf26011e" ]
[ "comadyn/scalers.py" ]
[ "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\n\"\"\"scalers --- Parameter scale factors\n======================================\n\nScalers create parameter scale factors. They may depend on particle\nparameters, such as size, heliocentric distance, etc.\n\nScalers may be chained together using the `*` operator into a\n`CompositeScaler`:\n\n total_scale = SpeedRh() * SpeedRadius()\n\nOnce defined, scalers may be removed from the chain:\n\n del total_scale[0] # Removes the `SpeedRh` scaler.\n\nTo create the a new scale factor from a `Scaler` or `CompositeScaler`,\nuse the function call syntax:\n\n p = ... # define a new `Particle`\n s = total_scale(p)\n\n # evaluate heliocentric distance scalers at these distances\n s = total_scale(rh=[1, 2, 3])\n\n\n\nClasses\n-------\nScaler\nCompositeScaler\nProductionRateScaler\nPSDScaler\n\nActiveArea\nConstantFactor\nFractalPorosity\nNormalActiveArea\nPSD_Hanner\nPSD_PowerLaw\nPSD_RemoveLogBias\nQRh\nQRhDouble\nScatteredLight\nSpeedLimit\nSpeedRadius\nSpeedRh\nSunCone\nThermalEmission\nUnityScaler\n\n\nExceptions\n----------\nInvalidScaler\nMissingGrainModel\n\n\nFunctions\n---------\nflux_scaler\nmass_calibrate\n\n\"\"\"\n\n__all__ = [\n 'Scaler',\n 'CompositeScaler',\n 'ActiveArea',\n 'ConstantFactor',\n 'FractalPorosity',\n 'NormalActiveArea',\n 'ParameterWeight',\n 'PSD_Hanner',\n 'PSD_PowerLaw',\n 'PSD_RemoveLogBias',\n 'QRh',\n 'QRhDouble',\n 'ScatteredLight',\n 'SpeedLimit',\n 'SpeedRadius',\n 'SpeedRh',\n 'SunCone',\n 'ThermalEmission',\n 'UnityScaler',\n 'flux_scaler'\n]\n\nfrom abc import ABC, abstractmethod\nimport numpy as np\nimport astropy.units as u\n\nclass InvalidScaler(Exception):\n pass\n\nclass MissingGrainModel(Exception):\n pass\n\nclass Scaler(ABC):\n \"\"\"Abstract base class for particle scale factors.\n\n Notes\n -----\n Particle scale factors are multiplicative.\n\n \"\"\"\n\n def __mul__(self, other):\n return CompositeScaler(self, other)\n\n @abstractmethod\n def __str__(self):\n pass\n\n @abstractmethod\n def __call__(self, p=None, **kwargs):\n \"\"\"Evaluate the scaler.\n\n If `p` or `kwargs` do not contain all necessary variables, the\n scaler evaluates to 1.0.\n\n Parameters\n ----------\n p : Particle, optional\n The scaler variables are chosen from this particle parameter\n set. If not defined, then variables are chosen from the\n keyword arguments.\n **kwargs\n Scaler variables as keyword arguments.\n\n Result\n ------\n s : float or ndarray\n The scale factor(s).\n\n Notes\n -----\n One of `p` or `kwargs` must be defined. If `p` is not `None`,\n `kwargs` are ignored.\n\n \"\"\"\n pass\n\n @abstractmethod\n def formula(self):\n pass\n\n def _get(self, keys, p, kwargs):\n \"\"\"Helper for variable getting in `__call__` methods.\"\"\"\n source = kwargs if p is None else p\n v = tuple()\n for k in keys:\n v += (kwargs[k],)\n\n return v\n\nclass CompositeScaler(Scaler):\n \"\"\"Collection of chained scalers.\n\n To create a `CompositeScaler`, multiply two `Scaler` together::\n\n total_scale = SpeedRh() * SpeedRadius()\n\n To remove the `SpeedRh` scale::\n\n del total_scale.scales[0]\n\n Raises\n ------\n InvalidScaler\n\n \"\"\"\n\n def __init__(self, lscaler, rscaler):\n self.scalers = []\n\n if isinstance(lscaler, UnityScaler):\n self = rscaler\n elif isinstance(rscaler, UnityScaler):\n self = lscaler\n else:\n self *= lscale\n self *= rscale\n\n def __mul__(self, scale):\n if isinstance(scale, UnityScaler):\n return self\n\n composite = self\n if isinstance(scale, Scaler):\n composite.scales.append(scale)\n elif isinstance(scale, CompositeScaler):\n composite.scales.extend(scale.scales)\n else:\n raise InvalidScaler\n return composite\n\n def __str__(self):\n return ' * '.join([str(s) for s in self.scales])\n\n def formula(self):\n return '(' + ') * ('.join([s.formula() for s in self.scales]) + ')'\n\n def __call__(self, p=None, **kwargs):\n return np.prod([s.scale(p=p, **kwargs) for s in self.scales])\n\nclass ActiveArea(Scaler):\n \"\"\"Emission from an active area.\n\n Scale factor is 1 if inside the ejection cone, 0 otherwise.\n\n Parameters\n ----------\n w : float\n Cone full opening angle. [rad]\n ll : array\n Longitude and latitude of the active area. [rad]\n pole : array, optional\n The pole in Ecliptic coordinates, angular (lambda, beta) or\n rectangular (x, y, z). The Vernal equinox will be arbitrarily\n defined.\n body_basis : array, optional\n Nx3 array of x, y, and z unit vectors defining the\n planetocentric coordinate system, in Ecliptic rectangular\n coordinates.\n\n Notes\n -----\n If `pole` is provided, the Vernal equinox and first solstice will\n be arbitrarity derived.\n\n The vectors in `body_basis` are:\n `body_basis[0]` (x): the Vernal equinox\n `body_basis[1]` (y): the first solstice\n `body_basis[2]` (z): the pole\n\n Only one of `pole` or `body_basis` may be provided.\n\n \"\"\"\n\n def __init__(self, w, ll, pole=None, body_basis=None):\n from astropy.coordinates import spherical_to_cartesian\n from .generators import Vej\n \n self.w = w\n self.ll = ll\n \n if body_basis is None:\n if pole is None:\n body_basis = np.array(((1, 0, 0), (0, 1, 0), (0, 0, 1)), float)\n else:\n body_basis = Vej.pole2basis(pole)\n self.body_basis = body_basis\n\n # active area normal vector\n self.normal = spherical_to_cartesian(1.0, ll[1], ll[0])\n\n @property\n def vernal_eq(self):\n return body_basis[0]\n\n @property\n def solstice(self):\n return body_basis[1]\n\n @property\n def pole(self):\n return body_basis[2]\n\n def __str__(self):\n return 'ActiveArea({}, {}, body_basis={})'.format(\n self.w, self.ll, np.array2string(self.body_basis, separator=','))\n\n def __call__(self, p=None, **kwargs):\n \"\"\"Evaluate the scaler.\n\n Requires ejection direction, `v_ej`; ejection speed, `s_ej`,\n is optional.\n\n \"\"\"\n \n from .util import mhat\n\n try:\n v_ej = self._get(['v_ej'], p, kwargs)\n except KeyError:\n return 1.0\n\n try:\n s_ej = self._get(['s_ej'], p, kwargs)\n except KeyError:\n v_ej = mhat(v_ej)[1]\n s_ej = 1.0\n\n assert v_ej.shape[-1] == 3\n\n cth = np.sum(self.normal * v_ej, -1) / s_ej\n\n return (cth >= np.cos(self.w / 2)).astype(int)\n\n def formula():\n return '1 if within active area, else 0'\n\n __call__.__doc__ += '\\n'.join(Scaler.__call__.__doc__.splitlines()[2:])\n\nclass ConstantFactor(Scaler):\n \"\"\"Constant scale factor.\"\"\"\n def __init__(self, c):\n self.c = c\n\n def __str__(self):\n return 'ConstantFactor({})'.format(self.c)\n\n def formula(self):\n return r\"$C = {:.3g}$\".format(self.c)\n\n def __call__(self, p=None, **kwargs):\n return self.c\n\nclass FractalPorosity(Scaler):\n \"\"\"Density scale factor based on fractal porosity.\n\n For the bulk material density `rho0`, minimum grain size `a0`, and\n fractal dimension `D`::\n\n rho = rho0 * (a / a0)**(D - 3)\n\n Parameters\n ----------\n D : float\n Fractal dimension.\n a0 : float, optional\n Minimum grian size. Particles smaller than this will always be\n solid. [μm]\n\n \"\"\"\n\n def __init__(self, D, a0=0.1):\n self.D = D\n self.a0 = a0\n\n def __str__(self):\n return 'FractalPorosity(D={}, a0={})'.format(self.D, self.a0)\n\n def formula(self):\n return r\"$P = (a / a_0)^{{D-{:.3f}}}$\".format(self.a0, self.D)\n\n def __call__(self, p=None, **kwargs):\n \"\"\"Evaluate the scaler.\n\n Requires `radius`.\n \n \"\"\"\n\n try:\n radius = self._get(['radius'], p, kwargs)\n except KeyError:\n return 1.0\n\n return (radius / self.a0)**(self.D - 3.0)\n \n __call__.__doc__ += '\\n'.join(Scaler.__call__.__doc__.splitlines()[2:])\n\nclass NormalActiveArea(ActiveArea):\n \"\"\"Emission from an active area with a normal distribution.\n\n Scale factor is > 0 and < 1 inside the cone, 0 otherwise.\n\n Parameters\n ----------\n sigma : float\n The width of the distribution. [rad]\n \"\"\"\n \n def __init__(self, sigma, w, ll, pole=None, body_basis=None):\n self.sigma = sigma\n ActiveArea.__init__(self, w, ll, pole=pole, body_basis=body_basis)\n\n def __str__(self):\n return 'NormalActiveArea({}, {}, {}, {})'.format(\n self.sig, self.w, self.ll,\n np.array2string(self.body_basis, separator=','))\n\n def __call__(self, p=None, **kwargs):\n from .util import mhat\n \n try:\n v_ej = self._get(['v_ej'], p, kwargs)\n except KeyError:\n return 1.0\n\n try:\n s_ej = self._get(['s_ej'], p, kwargs)\n except KeyError:\n v_ej = mhat(v_ej)[1]\n s_ej = 1.0\n\n assert v_ej.shape[-1] == 3\n\n th = np.arccos(np.sum(self.normal * v_ej, -1) / s_ej)\n s = (th >= (self.w / 2)).astype(float)\n s *= np.exp(-th**2 / 2 / self.sigma**2)\n s /= np.sqrt(2 * np.pi) * self.sigma\n return s\n\n __doc__ += '\\n'.join(ActiveArea.__doc__.splitlines()[6:])\n\nclass ParameterWeight(Scaler):\n \"\"\"Scale value based on a parameter.\n\n Parameters\n ----------\n key : string\n The particle parameter key that defines the scale factor, e.g.,\n 'age'.\n\n \"\"\"\n\n def __init__(self, key):\n self.key = key\n\n def __str__(self):\n return 'ParameterWeight({})'.format(self.key)\n\n def formula(self):\n return \"W = {}\".format(self.key)\n\n def __call__(self, p=None, **kwargs):\n try:\n w = self._get([self.key], p, kwargs)\n except KeyError:\n return 1.0\n\n return w\n\nclass PSD_Hanner(Scaler):\n \"\"\"Hanner modified power-law particle size distribuion.\n\n n(a) = Np * (1 - a0 / a)**M * (a0 / a)**N\n\n Parameters\n ----------\n a0 : float\n Minimum grain radius. [μm]\n N : float\n PSD for large grains (`a >> ap`) is `a**-N`.\n M : float, optional\n `ap = a0 * (M + N) / N`.\n ap : float, optional\n Peak grain radius. [μm]\n Np : float, optional\n Number of grains with radius `ap`.\n\n Note\n ----\n One of `M` or `ap` must be provided.\n\n \"\"\"\n\n def __init__(self, a0, N, M=None, ap=None, Np=1):\n self.a0 = a0\n self.N = N\n self.M = M\n self.ap = ap\n self.Np = 1\n\n assert (M is None) != (ap is None), 'One and only one of `M` or `ap` may be provided.'\n \n if M is None:\n self.M = (self.ap / self.a0 - 1) * self.N\n else:\n self.ap = self.a0 * (self.M + self.N) / self.N\n\n def __str__(self):\n return 'PSD_Hanner({}, {}, ap={}, Np={})'.format(\n self.a0, self.N, self.ap, self.Np)\n\n def formula(self):\n return r\"dn/da = {Np:.3g} (1 - {a0:.2g} / a)^M ({a0:.2g} / a)^N\".format(\n a0=self.a0, N=self.N, M=self.M, Np=self.Np)\n\n def __call__(self, p=None, **kwargs):\n \"\"\"Evaluate the scaler.\n\n Requires `radius` in μm.\n\n \"\"\"\n\n try:\n radius = self._get(['radius'], p, kwargs)\n except KeyError:\n return 1.0\n\n return (self.Np * (1 - self.a0 / radius)**self.M\n * (self.a0 / radius)**self.N)\n\n __call__.__doc__ += '\\n'.join(Scaler.__call__.__doc__.splitlines()[2:])\n\nclass PSD_PowerLaw(Scaler):\n \"\"\"Power law particle size distribuion.\n\n n(a) = N1 * a**N\n\n Parameters\n ----------\n N : float\n Power-law slope.\n N1 : float, optional\n Number of 1-μm-radius particles.\n\n\n \"\"\"\n\n def __init__(self, N, Np=1):\n self.N = N\n self.Np = Np\n\n def __str__(self):\n return 'PSD_PowerLaw({}, Np={})'.format(self.N, self.Np)\n\n def formula(self):\n return r\"$dn/da = {:.3g}\\times\\,a^{{{:.1f}}}$\".format(\n self.Np, self.N)\n\n def __call__(self, p=None, **kwargs):\n \"\"\"Evaluate the scaler.\n\n Requires `radius` in μm.\n\n \"\"\"\n\n try:\n radius = self._get(['radius'], p, kwargs)\n except KeyError:\n return 1.0\n\n return self.Np * radius**self.N\n\n __call__.__doc__ += '\\n'.join(Scaler.__call__.__doc__.splitlines()[2:])\n\nclass PSD_RemoveLogBias(Scaler):\n \"\"\"Remove the log bias of a simulation.\n\n For simulations with radius picked from the `Log` generator.\n\n Parameters\n ----------\n Nt : float, optional\n aminmax : array, optional\n Normalize to `Nt` total particles over the radius range\n `aminmax`.\n\n \"\"\"\n\n _Nt = None\n _aminmax = None\n\n def __init__(self, Nt=None, aminmax=None):\n self.Nt = Nt\n self.aminmax = aminmax\n\n def __str__(self):\n return 'PSD_RemoveLogBias(Nt={}, aminmax={})'.format(\n self.Nt, self.aminmax)\n\n def formula(self):\n return r\"dn/da_{{correction}} = {:.3g} a\".format(self.N0)\n\n @property\n def Nt(self):\n return self._Nt\n\n @Nt.setter\n def Nt(self, n):\n self._Nt = n\n self._update_N0()\n\n @property\n def aminmax(self):\n return self._aminmax\n\n @aminmax.setter\n def aminmax(self, amm):\n self._aminmax = amm\n self._update_N0()\n\n def _update_N0(self):\n if (self.Nt is not None) and (self.aminmax is not None):\n self.N0 = self.Nt / np.log(max(self.aminmax) / min(self.aminmax))\n else:\n self.N0 = 1.0\n\n def __call__(self, p=None, **kwargs):\n \"\"\"Evaluate the scaler.\n\n Requires `radius`.\n\n \"\"\"\n\n try:\n radius = self._get(['radius'], p, kwargs)\n except KeyError:\n return 1.0\n \n return self.N0 * radius\n \n __call__.__doc__ += '\\n'.join(Scaler.__call__.__doc__.splitlines()[2:])\n\nclass QRh(Scaler):\n \"\"\"Dust production rate dependence on heliocentric distance using a single power-law.\n\n Qd \\propto rh_i**k\n\n Parameters\n ----------\n k : float\n Power-law scale factor slope.\n\n \"\"\"\n\n def __init__(self, k):\n self.k = k\n\n def __str__(self):\n return 'QRh({})'.format(self.k)\n\n def formula(self):\n return (r\"$Q \\propto r_h^{{{}}}$\").format(self.k)\n\n def __call__(self, p=None, **kwargs):\n \"\"\"Evaluate the scaler.\n\n Requires rh_i.\n\n \"\"\"\n\n try:\n rh = self._get(['rh_i'], p, kwargs)\n except KeyError:\n return 1.0\n \n return rh**self.k\n\nclass QRhDouble(Scaler):\n \"\"\"Production rate dependence on heliocentric distance using a double power-law.\n\n Qd \\propto rh_i**k1 for rh_i < rh0\n Qd \\propto rh_i**k2 for rh_i > rh0\n\n The width of the transition from `k1` to `k2` is parameterized by\n `k12`. Larger `k12` yields shorter transitions. Try 100.\n\n The function is normalized to 1.0 at `rh0`.\n\n Parameters\n ----------\n k1, k2 : float\n Power-law scale factor slopes.\n k12 : float\n Parameter controlling the width of the transition from `k1` to\n `k2`.\n rh0 : float\n The transition heliocentric distance. [AU]\n\n \"\"\"\n\n def __init__(self, k1, k2, k12, rh0):\n self.k1 = k1\n self.k2 = k2\n self.k12 = k12\n self.rh0 = rh0\n\n def __str__(self):\n return 'QRhDouble({}, {}, {}, {})'.format(self.k1, self.k2,\n self.k12, self.rh0)\n\n def formula(self):\n return (r\"\"\"$Q \\propto r_h^{{{}}}$ for $r_h < {}$ AU\n$Q \\propto r_h^{{{}}}$ for $r_h > {}$ AU\"\"\").format(self.k1, self.rh0,\n self.k2, self.rh0)\n\n def __call__(self, p=None, **kwargs):\n \"\"\"Evaluate the scaler.\n\n Requires `rh_i`.\n\n \"\"\"\n try:\n rh = self._get(['rh_i'], p, kwargs)\n except KeyError:\n return 1.0\n \n alpha = ((self.k1 - self.k2) / self.k12)\n s = 2**-alpha\n s *= (rh / self.rh0)**self.k2\n s *= (1 + (rh / self.rh0)**self.k12)**alpha\n\n return s\n \n __call__.__doc__ += '\\n'.join(Scaler.__call__.__doc__.splitlines()[2:])\n\nclass ScatteredLight(Scaler):\n \"\"\"Radius-based scaler to simulate light scattering.\n\n The scale factor is::\n\n Qsca * sigma * S / rh_f / Delta**2\n\n where `sigma` is the cross-sectional area of the grain, and `S` is\n the solar flux at 1 au, `rh_f` and `Delta` are in au. The\n scattering efficiency is::\n\n Qsca = (2 * pi * a / wave)**4 for a < wave / 2 / pi\n Qsca = 1.0 for a >= wave / 2 / pi\n\n Parameters\n ----------\n wave : float\n Wavelength of the light. [μm]\n unit : astropy Unit or string\n The flux density units of the scale factor.\n\n \"\"\"\n\n def __init__(self, wave, unit='W/(m2 um)'):\n self.unit = unit\n self.wave = wave\n\n def __str__(self):\n return 'ScatteredLight({}, unit={})'.format(self.wave, repr(self.unit))\n\n def __call__(self, p=None, **kwargs):\n \"\"\"Evaluate the scaler.\n\n Requires `radius`, `rh_f`, and `Delta`.\n\n \"\"\"\n \n from mskpy.calib import solar_flux\n \n try:\n radius, rh_f, Delta = self._get(\n ('radius', 'rh_f', 'Delta'), p, kwargs)\n except KeyError:\n return 1.0\n\n radius = np.array(radius)\n if radius.ndim == 0:\n radius = radius[np.newaxis]\n\n Q = np.ones_like(radius)\n k = self.wave / 2 / np.pi\n\n i = radius < k\n if any(i):\n Q[i] = (radius[i] / k)**4\n\n sigma = np.pi * (radius * 1e-9)**2 # km**2\n S = solar_flux(self.wave, unit=self.unit).value # at 1 AU\n \n return Q * sigma * S / rh_f**2 / Delta**2\n\n __call__.__doc__ += '\\n'.join(Scaler.__call__.__doc__.splitlines()[2:])\n\nclass SpeedLimit(Scaler):\n \"\"\"Limit speed to given values.\n\n If the particle speed is outside the range [`smin`, `smax`], the\n returned scale factor is 0.0. 1.0, otherwise.\n\n Parameters\n ----------\n smin : float, optional\n Minimum ejection speed. [km/s]\n smax : float, optional\n Maximum ejection speed. [km/s]\n scales : Scaler or CompositeScaler, optional\n Normalize the speed with `scales` before applying limits. For\n example, if a simulation was picked using over a range of\n values, then scaled with `SpeedRadius`, set `scales` to use the\n same SpeedRadius to undo the scaling.\n\n \"\"\"\n \n def __init__(self, smin=0, smax=np.inf, scalers=None):\n self.smin = smin\n self.smax = smax\n if scalers is None:\n self.scalers = UnityScaler()\n else:\n self.scalers = scalers\n\n def __str__(self):\n return 'SpeedLimit(smin={}, smax={}, scalers={})'.format(\n self.smin, self.smax, self.scalers)\n\n def __call__(self, p=None, **kwargs):\n \"\"\"Evaluate the scaler.\n\n Requires `s_ej` plus any variable needed for `self.scalers`.\n\n \"\"\"\n\n try:\n s_ej = self._get(['s_ej'], p, kwargs)\n except KeyError:\n return 1.0\n \n s = s_ej / self.scalers.scale(p=p, **kwargs)\n i = (s < self.smin) + (s > self.smax)\n if np.iterable(i):\n scale = np.ones_like(s)\n if any(i):\n scale[i] = 0.0\n else:\n scale = 0.0 if i else 1.0\n \n return scale\n\n __call__.__doc__ += '\\n'.join(Scaler.__call__.__doc__.splitlines()[2:])\n\nclass SpeedRadius(Scaler):\n \"\"\"Speed scale factor based on grain raidus.\n\n For `a` measured in micrometers::\n\n scale = (a / a0)**k\n\n Parameters\n ----------\n k : float, optional\n Power-law exponent.\n a0 : float, optional\n Normalization radius.\n\n \"\"\"\n\n def __init__(self, k=-0.5, a0=1.0):\n self.k = k\n self.a0 = a0\n\n def __str__(self):\n return 'SpeedRadius(k={}, a0={})'.format(self.k, self.a0)\n\n def __call__(self, p=None, **kwargs):\n \"\"\"Evaluate the scaler.\n\n Requires `radius`.\n\n \"\"\"\n \n try:\n radius = self._get(['radius'], p, kwargs)\n except KeyError:\n return 1.0\n\n return (radius / self.a0)**self.k\n\n __call__.__doc__ += '\\n'.join(Scaler.__call__.__doc__.splitlines()[2:])\n\nclass SpeedRh(Scaler):\n \"\"\"Speed scale factor based on heliocentric distance.\n\n For `rh_i` measured in au::\n\n scale = (rh_i / rh0)**k\n\n Parameters\n ----------\n k : float, optional\n Power-law exponent.\n rh0 : float, optional\n Normalization distance.\n\n \"\"\"\n\n def __init__(self, k=-0.5, rh0=1.0):\n self.k = k\n self.rh0 = rh0\n\n def __str__(self):\n return 'SpeedRh(k={}, rh0={})'.format(self.k, self.rh0)\n\n def __call__(self, p=None, **kwargs):\n \"\"\"Evaluate the scaler.\n\n Requires `rh_i`.\n\n \"\"\"\n \n try:\n rh = self._get(['rh_i'], p, kwargs)\n except KeyError:\n return 1.0\n\n return (rh / self.rh0)**self.k\n\n __call__.__doc__ += '\\n'.join(Scaler.__call__.__doc__.splitlines()[2:])\n\nclass SunCone(Scaler):\n \"\"\"A cone of emission ejected toward the Sun.\n\n Parameters\n ----------\n w : float\n Cone full opening angle. [rad]\n\n \"\"\"\n\n def __init__(self, w):\n self.w = w\n\n def __str__(self):\n return 'SunCone({})'.format(self.w)\n\n def __call__(self, p=None, **kwargs):\n \"\"\"Evaluate the scaler.\n\n Requires `r_i` and `v_ej`; initial distance to the Sun, `d_i`,\n and ejection speed, `s_ej` are optional.\n\n \"\"\"\n\n from .util import mhat\n \n try:\n r_i, v_ej = self._get(('r_i', 'v_ej'), p, kwargs)\n except KeyError:\n return 1.0\n\n try:\n s_ej = self._get(['s_ej'], p, kwargs)\n except KeyError:\n v_ej = mhat(v_ej)[1]\n s_ej = 1.0\n\n try:\n d_i = self._get(['d_i'], p, kwargs)\n except KeyError:\n r_i = mhat(r_i)[1]\n d_i = 1.0\n\n cth = np.sum(-r_i * v_ej, -1) / d_i / s_ej\n\n return (cth >= np.cos(self.w / 2.0)).astype(int)\n\n __call__.__doc__ += '\\n'.join(Scaler.__call__.__doc__.splitlines()[2:])\n\nclass ThermalEmission(Scaler):\n \"\"\"Radius-based scaler to simulate thermal emission.\n\n The scale factor is::\n\n Qem * sigma * B / Delta**2\n\n where `sigma` is the cross-sectional area of the grain, and `S` is\n the solar flux. The scattering efficiency is::\n\n Qem = 2 * pi * a / wave for a < wave / 2 / pi\n Qem = 1.0 for a >= wave / 2 / pi\n\n Parameters\n ----------\n wave : float\n Wavelength of the light. [micrometers]\n unit : astropy Unit or string, optional\n The flux density units of the scale factor.\n composition : Composition, optional\n Use this composition, rather than anything specified in the\n simluation.\n require_grain_model : bool, optional\n If `True`, and a grain temperature model cannot be found, throw\n an exception. If `False`, use a blackbody temperature as a\n fail-safe model.\n\n \"\"\"\n\n def __init__(self, wave, unit='W/(m2 um)', composition=None,\n require_grain_model=False):\n self.unit = unit\n self.wave = wave\n self.composition = composition\n self.require_grain_model = require_grain_model\n print('ThermalEmission is assuming solid grains at the median rh')\n\n def __str__(self):\n return (('ThermalEmission({}, unit={}, composition={}, '\n 'require_grain_model={})'\n ).format(self.wave, repr(self.unit), str(self.composition),\n self.require_grain_model))\n\n def __call__(self, p=None, composition=None, **kwargs):\n \"\"\"Evaluate the scaler.\n\n Requires `radius`, `rh_f`, `Delta`, and `composition`. If\n `self.composition` is defined, then it takes precedence.\n\n \"\"\"\n from mskpy.util import planck\n from . import particle\n\n gtm_filename = {'amorphouscarbon': 'am-carbon.fits',\n 'amorphousolivine50': 'am-olivine50.fits'}\n\n if self.composition is None:\n if p is not None:\n composition = p.params['pfunc']['composition'].split('(')[0]\n else:\n composition = str(composition).split('(')[0]\n else:\n composition = str(self.composition).split('(')[0]\n composition = composition.lower().strip()\n\n try:\n radius, rh_f, Delta = self._get(\n ('radius', 'rh_f', 'Delta'), p, kwargs)\n except KeyError:\n return 1.0\n \n if composition in gtm_filename:\n from dust import readgtm, gtmInterp\n from scipy import interpolate\n from scipy.interpolate import splrep, splev\n gtm = readgtm(gtm_filename[composition])\n T = np.zeros_like(radius)\n rh = np.median(rh_f)\n\n T_rh = np.zeros_like(gtm[2])\n for i in range(len(gtm[2])):\n T_rh[i] = splev(rh, splrep(gtm[3], gtm[0][0, i]))\n\n T = splev(radius, splrep(gtm[2], T_rh))\n else:\n if self.require_grain_model:\n raise MissingGrainModel\n\n T = 278. / np.sqrt(rh_f)\n \n radius = np.array(radius)\n if radius.ndim == 0:\n radius = radius[np.newaxis]\n\n Q = np.ones_like(radius)\n k = self.wave / 2 / np.pi\n \n i = radius < k\n if any(i):\n Q[i] = radius[i] / k\n \n sigma = np.pi * (radius * 1e-9)**2 # km**2\n B = planck(self.wave, T, unit=u.Unit(self.unit) / u.sr).value\n \n return Q * sigma * B / Delta**2\n\n __call__.__doc__ += '\\n'.join(Scaler.__call__.__doc__.splitlines()[2:])\n\nclass UnityScaler(Scaler):\n \"\"\"Scale factor of 1.0.\"\"\"\n def __init__(self):\n pass\n\n def __str__(self):\n return 'UnityScaler()'\n\n def __call__(self, p=None, **kwargs):\n return 1.0\n\ndef flux_scaler(Qd=0, psd='a^-3.5', thermal=24, scattered=-1, log_bias=True):\n \"\"\"Weight a comet simulation with commonly used scalers.\n\n Parameters\n ----------\n Qd : float, optional\n Specify `k` in `QRh(k)`.\n psd : string, optional\n Particle size distribution, one of 'ism', 'a^k', or\n 'hanner a0 N ap'.\n thermal : float, optional\n Wavelength of the thermal emission. Set to <= 0 to\n disable. [micrometers]\n scattered : float, optional\n Wavelength of the scattered light. Set to <= 0 to\n disable. [micrometers]\n log_bias : bool, optional\n If `True`, include `PSD_RemoveLogBias` in the scaler.\n\n Returns\n -------\n scale : CompositeScaler\n\n \"\"\"\n\n psd = psd.lower().strip()\n if psd == 'ism':\n psd_scaler = PSD_PowerLaw(-3.5)\n elif psd[0] == 'k':\n psd_scaler = PSD_PowerLaw(float(psd[2:]))\n elif psd.startswith('hanner'):\n a0, N, ap = [float(x) for x in psd.split()[1:]]\n psd_scaler = PSD_Hanner(a0, N, ap=ap)\n else:\n psd_scaler = UnityScaler()\n\n if thermal <= 0:\n therm = UnityScaler()\n else:\n therm = ThermalEmission(thermal)\n\n if scattered <= 0:\n scat = UnityScaler()\n else:\n scat = ScatteredLight(scattered)\n\n return QRh(Qd) * psd_scaler * PSD_RemoveLogBias() * therm * scat\n\ndef mass_calibrate(Q0, rh0, arange, scaler, params, n=None):\n \"\"\"Calibrate a simulation given a dust production rate.\n\n Currently considers `ProductionRateScaler`s and `PSDScaler`s.\n\n Parameters\n ----------\n Q0 : Quantity\n The dust production rate (mass per time) at `rh0`.\n rh0 : Quantity\n The heliocentric distance for which `Q0` is valid.\n arange : Quantity array\n The coma radius range over which `Q0` is computed.\n scaler : Scaler or CompositeScaler\n The simluation scale factors.\n params : dict\n The parameters of the simulation.\n n : int, optional\n The number of particles in the simulation. The default is to\n use `params['nparticles']`, but this may not always be desired.\n\n Returns\n -------\n calib : float\n The calibration factor for the simulation to place simulation\n particles in units of coma particles.\n\n \"\"\"\n\n from scipy.integrate import quad\n from mskpy import getspiceobj, cal2time\n from . import generators as csg\n\n Q0 = Q0.to(u.kg / u.s)\n rh0 = rh0.to(u.au)\n arange = arange.to(u.um)\n\n if n is None:\n n = params['nparticles']\n\n gen = eval('csg.' + params['pfunc']['age'])\n trange_sim = gen.min() / 365.25, gen.max() / 365.25\n\n gen = eval('csg.' + params['pfunc']['radius'])\n arange_sim = gen.min(), gen.max()\n\n # search scaler for production rate scalers\n Q = UnityScaler()\n if isinstance(scaler, ProductionRateScaler):\n Q = Q * eval(str(scaler))\n elif isinstance(scaler, CompositeScaler):\n for i in range(len(scaler.scales)):\n if isinstance(scaler.scales[i], ProductionRateScaler):\n Q = Q * eval(str(scaler.scales[i]))\n\n # search scaler for size frequency\n PSD = UnityScaler()\n if isinstance(scaler, PSDScaler):\n PSD = PSD * eval(str(scaler))\n elif isinstance(scaler, CompositeScaler):\n for i in range(len(scaler.scales)):\n if isinstance(scaler.scales[i], PSDScaler):\n PSD = PSD * eval(str(scaler.scales[i]))\n\n if params['comet']['kernel'] == 'None':\n kernel = None\n else:\n kernel = params['comet']['kernel']\n\n comet = getspiceobj(params['comet']['name'], kernel=kernel)\n t0 = cal2time(params['date'])\n\n def mass(a):\n # a in um, mass in g\n from numpy import pi\n #m = 4/3. * pi * (a * 1e-4)**3\n m = 4/3. * pi * a**3 * 1e-12\n dnda = PSD.scale_a(a)\n return m * dnda\n\n def production_rate(age):\n # unitless\n r = comet.r(t0 - age * u.yr)\n rh = np.sqrt(np.dot(r, r)) / 1.495978707e8\n return Q.scale_rh(rh)\n\n # theoretical mass of the simulation\n # raw particles / year\n m_sim = float(n) / ((trange_sim[1] - trange_sim[0]) * u.yr)\n # kg / year\n m_sim *= quad(mass, *arange_sim)[0] * 1e-3 * u.kg\n # kg\n m_sim *= quad(production_rate, *trange_sim)[0] * u.yr\n m_sim = m_sim.decompose()\n\n # mass fraction of simulation compared to coma\n m_frac = quad(mass, *arange_sim)[0] / quad(mass, *arange.value)[0]\n\n # coma mass\n m_com = (Q0 * quad(production_rate, *trange_sim)[0] * u.yr).decompose()\n\n return (m_com * m_frac / m_sim).value\n" ]
[ [ "numpy.array", "numpy.ones_like", "numpy.iterable", "numpy.zeros_like", "numpy.dot", "numpy.median", "numpy.sum", "scipy.interpolate.splrep", "numpy.exp", "numpy.sqrt", "numpy.cos", "scipy.integrate.quad", "numpy.array2string" ] ]
boyentenbi/jax
[ "3a9ce3990eb0c7a271dc5a37e6f2c30306d7f3fa" ]
[ "jax/experimental/jax2tf/tests/shape_poly_test.py" ]
[ "# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for the shape-polymorphic jax2tf conversion.\"\"\"\n\nfrom absl.testing import absltest\nfrom typing import Dict, Optional, Sequence, Union\n\nimport collections\nimport functools\nimport operator\nimport re\n\nimport jax\nfrom jax import core\nfrom jax.experimental import jax2tf\nfrom jax.experimental.jax2tf import shape_poly\nfrom jax import lax\nimport jax.numpy as jnp\nfrom jax import test_util as jtu\nfrom jax._src.lax import control_flow as lax_control_flow\nimport numpy as np\n\nfrom jax.experimental.jax2tf.tests import tf_test_util\n\nimport tensorflow as tf # type: ignore[import]\nimport unittest\n\nfrom jax.config import config\n\nconfig.parse_flags_with_absl()\n\n# Import after parsing flags\nfrom jax.experimental.jax2tf.tests import primitive_harness\nfrom jax.experimental.jax2tf.tests.jax2tf_limitations import Jax2TfLimitation\n\nPS = jax2tf.PolyShape\n\n\nclass ShapePolyTest(tf_test_util.JaxToTfTestCase):\n\n def test_simple(self):\n \"\"\"Test shape polymorphism for a simple case.\"\"\"\n\n def f_jax(x):\n return x + jnp.sin(x)\n\n self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([2, 3])],\n polymorphic_shapes=None,\n expected_output_signature=tf.TensorSpec([2, 3]))\n\n self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([2, None])],\n polymorphic_shapes=[\"_, h\"],\n expected_output_signature=tf.TensorSpec([2, None]))\n\n self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([None, None])],\n polymorphic_shapes=[\"h, h\"],\n expected_output_signature=tf.TensorSpec([None, None]))\n\n def test_arg_avals(self):\n \"\"\"Test conversion of actual arguments to abstract values.\"\"\"\n\n def check_avals(*, args: Sequence[jax2tf.jax2tf.TfVal],\n polymorphic_shapes: Sequence[Optional[Union[str, PS]]],\n expected_avals: Sequence[core.ShapedArray]):\n avals, shape_env = jax2tf.jax2tf._args_to_avals_and_env(\n args, polymorphic_shapes) # The function under test\n self.assertEqual(expected_avals, avals)\n # TODO: Check the shape_env\n\n def shaped_array(shape_spec: str, actual_shape: core.Shape):\n return core.ShapedArray(\n shape_poly.parse_spec(shape_spec, actual_shape), np.float32)\n\n def const(shape):\n return np.ones(shape, dtype=np.float32)\n\n def tf_const(shape):\n return tf.convert_to_tensor(np.ones(shape, dtype=np.float32))\n\n def tf_var(shape, *, initializer_shape=None):\n initializer_shape = initializer_shape or shape\n self.assertEmpty([d for d in initializer_shape if d is None])\n return tf.Variable(\n np.ones(initializer_shape, np.float32), dtype=tf.float32, shape=shape)\n\n # Known shapes for the arguments\n check_avals(\n args=[const((2, 3))],\n polymorphic_shapes=[None],\n expected_avals=(shaped_array(\"2, 3\", [2, 3]),))\n\n check_avals(\n args=[tf_const((2, 3))],\n polymorphic_shapes=[None],\n expected_avals=(shaped_array(\"2, 3,\", [2, 3]),))\n\n check_avals(\n args=[tf_var((2, 3))],\n polymorphic_shapes=[None],\n expected_avals=(shaped_array(\"(2, 3)\", [2, 3]),))\n\n check_avals(\n args=[const((2, 3))],\n polymorphic_shapes=[\"(2, 3)\"],\n expected_avals=(shaped_array(\"2, 3\", [2, 3]),))\n\n check_avals(\n args=[tf_const((2, 3))],\n polymorphic_shapes=[\"(_, 3)\"],\n expected_avals=(shaped_array(\"2, 3\", [2, 3]),))\n\n check_avals(\n args=[tf_const((2, 3))],\n polymorphic_shapes=[PS(\"_\", 3)],\n expected_avals=(shaped_array(\"2, 3\", [2, 3]),))\n\n # Partially known shapes for the arguments\n check_avals(\n args=[tf_var([None, 3], initializer_shape=(2, 3))],\n polymorphic_shapes=[PS(\"b\", ...)],\n expected_avals=(shaped_array(\"(b, 3)\", (2, 3)),))\n\n check_avals(\n args=[tf_var([None, None], initializer_shape=(2, 3))],\n polymorphic_shapes=[\"h, h\"],\n expected_avals=(shaped_array(\"(h, h)\", (2, 2)),))\n\n check_avals(\n args=[tf_var([2, None], initializer_shape=(2, 3))],\n polymorphic_shapes=[(\"h, h\")],\n expected_avals=(shaped_array(\"(h, h)\", (2, 2)),))\n\n check_avals(\n args=[tf_var([None, 3, 4], initializer_shape=(2, 3, 4))],\n polymorphic_shapes=[\"(c, b, a)\"],\n expected_avals=(shaped_array(\"(c, b, a)\", (2, 3, 4)),),\n )\n\n # Some errors\n with self.assertRaisesRegex(ValueError,\n re.escape(\"PolyShape ')(' has invalid syntax\")):\n check_avals(\n args=[const((2, 3))], polymorphic_shapes=[\")(\"], expected_avals=None)\n\n with self.assertRaisesRegex(\n ValueError,\n re.escape(\"PolyShape '..., 3' can contain Ellipsis only at the end.\")):\n check_avals(\n args=[const((2, 3))],\n polymorphic_shapes=[\"..., 3\"],\n expected_avals=None)\n\n with self.assertRaisesRegex(\n ValueError,\n re.escape(\n \"PolyShape '2, 3, 4, ...' must match the rank of arguments (2, 3).\")\n ):\n check_avals(\n args=[const((2, 3))],\n polymorphic_shapes=[\"2, 3, 4, ...\"],\n expected_avals=None)\n\n with self.assertRaisesRegex(\n ValueError,\n re.escape(\n \"PolyShape '(Ellipsis, 3)' can contain Ellipsis only at the end.\")):\n check_avals(\n args=[const((2, 3))],\n polymorphic_shapes=[PS(..., 3)],\n expected_avals=None)\n\n with self.assertRaisesRegex(\n ValueError,\n re.escape(\n \"PolyShape 'None' in axis 1 must contain a shape variable for unknown dimension in argument shape (2, None)\"\n )):\n check_avals(\n args=[tf_var([2, None], initializer_shape=(2, 3))],\n polymorphic_shapes=[None],\n expected_avals=None)\n\n with self.assertRaisesRegex(\n ValueError,\n re.escape(\"PolyShape '()' must match the rank of arguments (2, 3)\")):\n check_avals(\n args=[const((2, 3))], polymorphic_shapes=[\"()\"], expected_avals=None)\n\n with self.assertRaisesRegex(\n ValueError,\n re.escape(\n \"PolyShape '(_, _)' in axis 1 must contain a shape variable \"\n \"for unknown dimension in argument shape (2, None)\"\n )):\n check_avals(\n args=[tf_var([2, None], initializer_shape=(2, 3))],\n polymorphic_shapes=[\"(_, _)\"],\n expected_avals=None)\n\n with self.assertRaisesRegex(\n ValueError,\n re.escape(\n \"PolyShape '(2, 13)' in axis 1 must contain a constant or '_' for \"\n \"known dimension in argument shape (2, 3)\"\n )):\n check_avals(\n args=[const((2, 3))],\n polymorphic_shapes=[\"(2, 13)\"],\n expected_avals=None)\n\n with self.assertRaisesRegex(\n ValueError,\n re.escape(\n \"PolyShape '(2, 3)' in axis 1 must contain a shape variable for \"\n \"unknown dimension in argument shape (2, None)\"\n )):\n check_avals(\n args=[tf_var([2, None], initializer_shape=(2, 3))],\n polymorphic_shapes=[\"(2, 3)\"],\n expected_avals=None)\n\n with self.assertRaisesRegex(\n ValueError,\n re.escape(\n \"PolyShape '(a, a)' has dimension variable 'a' corresponding to \"\n \"multiple values ([2, 3]), for argument shape (2, 3)\"\n )):\n check_avals(\n args=[tf_var([2, 3], initializer_shape=(2, 3))],\n polymorphic_shapes=[\"(a, a)\"],\n expected_avals=None)\n\n def test_pytree(self):\n \"\"\"Arguments and polymorphic_shapes are pytrees.\"\"\"\n\n # Arguments are of the form [([x00, x01], [x10]), dict(a=ya, b=yb)]\n def add_all_jax(x_pair_of_list, y_dict):\n x_list_0, x_list_1 = x_pair_of_list\n return functools.reduce(operator.add,\n x_list_0 + x_list_1 + [y_dict[\"a\"], y_dict[\"b\"]])\n\n self.CheckShapePolymorphism(\n add_all_jax,\n input_signature=[([tf.TensorSpec([None]),\n tf.TensorSpec([None])], [tf.TensorSpec([None])]),\n dict(a=tf.TensorSpec([None]),\n b=tf.TensorSpec([None]))],\n polymorphic_shapes=[([\"v\", \"v\"], [(\"v\")]),\n dict(a=\"v\", b=\"v\")],\n expected_output_signature=tf.TensorSpec([None]))\n\n # Now partial polymorphic_shapes; the parts of the polymorphic_shapes that\n # are not specified must have full input_signatures.\n self.CheckShapePolymorphism(\n add_all_jax,\n input_signature=[([tf.TensorSpec([4]),\n tf.TensorSpec([4])], [tf.TensorSpec([4])]),\n dict(a=tf.TensorSpec([4]), b=tf.TensorSpec([4]))],\n polymorphic_shapes=[([\"(4,)\", \"(_,)\"], [(\"4,\")]),\n dict(a=\"(_,)\", b=\"(4,)\")],\n expected_output_signature=tf.TensorSpec([4]))\n\n def test_with_custom_vjp(self):\n \"\"\"Shape-polymorphic custom VJP.\"\"\"\n\n @jax.custom_vjp\n def f(x):\n # x: [b1, b2, d1, d2] (a batch of matrices)\n # res: [b1, b2, d1, d1]\n return jnp.matmul(x, jnp.transpose(x, axes=(0, 1, 3, 2)))\n\n # f_fwd: a -> (b, residual)\n def f_fwd(x):\n # x: [b1, b2, d1, d2]\n # b: [b1, b2, d1, d1]\n # residual: [b1, b2, d1, d2]\n return f(x), 3. * x\n\n # f_bwd: (residual, CT b) -> [CT a]\n def f_bwd(residual, ct_b):\n # residual: [b1, b2, d1, d2]\n # ct_b: [b1, b2, d1, d1]\n # ct_a: [b1, b2, d1, d2]\n return jnp.matmul(ct_b, residual),\n\n f.defvjp(f_fwd, f_bwd)\n x = np.ones((2, 3, 4, 5), dtype=np.float32)\n res_jax = f(x)\n res_jax_grad = jax.grad(lambda x: jnp.sum(f(x)))(x)\n\n f_tf = self.CheckShapePolymorphism(\n f,\n input_signature=[tf.TensorSpec([None, None, None, None])],\n polymorphic_shapes=[\"(batch1, batch2, d1, d2)\"],\n expected_output_signature=tf.TensorSpec([None, None, None, None]))\n\n self.assertAllClose(res_jax, f_tf(x))\n\n xv = tf.Variable(x, dtype=np.float32)\n\n def tf_value_and_grad(xv):\n with tf.GradientTape() as tape:\n tape.watch(xv)\n res_tf = f_tf(xv)\n res_tf_grad = tape.gradient(res_tf, xv)\n return res_tf, res_tf_grad\n\n res_tf, res_tf_grad = tf_value_and_grad(xv)\n self.assertAllClose(res_jax, res_tf)\n self.assertAllClose(res_jax_grad, res_tf_grad)\n\n # Now use TF tracing for the gradient\n tf_grad = tf.function(\n tf_value_and_grad, autograph=False).get_concrete_function(\n tf.TensorSpec([None, None, 8, 9]))\n\n # The shape of the value\n self.assertEqual((None, None, 8, 8), tuple(tf_grad.output_shapes[0]))\n # The shape of the gradient should match the input\n # TODO: there seems to be a bug here, the output should be (None, None, 8, 9)\n # self.assertEqual((None, None, 8, None), tuple(tf_grad.output_shapes[1]))\n\n def test_gradients_pytree(self):\n \"\"\"Shape polymorphism with gradients and pytrees for inputs and outputs.\"\"\"\n\n def f(x):\n # x: dict(x=[b, 3, 4])\n # res: dict(res=[b, 3, 4])\n return dict(res=x[\"x\"] * 2.)\n\n f_tf = self.CheckShapePolymorphism(\n f,\n input_signature=[dict(x=tf.TensorSpec([None, 3, 4]))],\n polymorphic_shapes=[dict(x=(\"b, 3, 4\"))],\n expected_output_signature=None)\n\n x = dict(x=np.ones((2, 3, 4), dtype=np.float32))\n xv = tf.Variable(x[\"x\"], dtype=np.float32)\n\n def tf_value_and_grad(xv):\n # xv: [b, 3, 4]\n # res_value: dict(res=[b, 3, 4])\n # res_grad: dict(grad=[b, 3, 4])\n with tf.GradientTape() as tape:\n tape.watch(xv)\n res_tf = f_tf(dict(x=xv))\n res_tf_grad = tape.gradient(res_tf, xv)\n return res_tf, dict(grad=res_tf_grad)\n\n res_tf, res_tf_grad = tf_value_and_grad(xv)\n # Now use TF tracing for the gradient\n tf_grad = tf.function(\n tf_value_and_grad,\n autograph=False).get_concrete_function(tf.TensorSpec([None, 3, 4]))\n # The shape of the value\n self.assertEqual((None, 3, 4), tuple(tf_grad.output_shapes[0][\"res\"]))\n # The shape of the gradient should match the input\n self.assertEqual((None, 3, 4), tuple(tf_grad.output_shapes[1][\"grad\"]))\n\n def test_cond(self):\n # Test the primitive under conditional\n def f(x, y):\n # x: f32[B, H], y : f32[H]\n return lax.cond(\n jnp.sum(x) > 0.,\n lambda _: x + y,\n lambda _: jnp.zeros_like(x),\n operand=None)\n\n x = np.ones((2, 3))\n y = np.ones((3,))\n res_jax = f(x, y)\n self.assertAllClose(\n res_jax,\n jax2tf.convert(f, polymorphic_shapes=[\"(b, h)\", \"h\"])(x, y))\n\n def test_shape_error(self):\n \"\"\"Some of the examples from the README.\"\"\"\n with self.assertRaisesRegex(\n TypeError,\n re.escape(\"add got incompatible shapes for broadcasting: (v,), (4,)\")):\n self.CheckShapePolymorphism(\n lambda x, y: x + y,\n input_signature=[tf.TensorSpec([None]),\n tf.TensorSpec([4])],\n polymorphic_shapes=[\"(v,)\", \"(4,)\"],\n expected_output_signature=tf.TensorSpec([None]))\n\n four_ones = np.ones((4,))\n # We get the error even if we use correct actual arguments\n with self.assertRaisesRegex(\n TypeError,\n re.escape(\"add got incompatible shapes for broadcasting: (v,), (4,)\")):\n jax2tf.convert(\n lambda x, y: x + y, polymorphic_shapes=[\"(v,)\", \"(4,)\"])(four_ones,\n four_ones)\n\n with self.assertRaisesRegex(\n core.InconclusiveDimensionOperation,\n re.escape(\"Shape variable comparison v == 4 is inconclusive\")):\n jax2tf.convert(\n lambda x: jnp.matmul(x, x), polymorphic_shapes=[\"(v, 4)\"])(\n np.ones((4, 4)))\n\n def test_parse_poly_spec(self):\n self.assertEqual((2, 3), shape_poly.parse_spec(None, (2, 3)))\n self.assertEqual((2, 3), shape_poly.parse_spec(\"2, 3\", (2, 3)))\n self.assertEqual((2, 3), shape_poly.parse_spec(\"2, _\", (2, 3)))\n self.assertEqual((2, 3), shape_poly.parse_spec(\"2, ...\", (2, 3)))\n self.assertEqual((2, 3), shape_poly.parse_spec(\"...\", (2, 3)))\n self.assertEqual((2, 3), shape_poly.parse_spec(\" ( 2 , 3 ) \", (2, 3)))\n\n def test_dim_vars(self):\n \"\"\"Unit tests for DimVar.\"\"\"\n da, db = shape_poly.parse_spec(\"a, b\", (2, 3))\n self.assertEqual(True, da == da)\n self.assertEqual(False, da != da)\n with self.assertRaisesRegex(core.InconclusiveDimensionOperation, \"\"):\n da == db\n with self.assertRaisesRegex(core.InconclusiveDimensionOperation, \"\"):\n da != db\n\n self.assertLen({da, da}, 1)\n self.assertLen({da, db}, 2)\n self.assertIn(da, {da, db})\n self.assertIn(db, {da, db})\n self.assertIn(da, [da, db])\n with self.assertRaisesRegex(core.InconclusiveDimensionOperation, \"\"):\n db in [da, db]\n\n def test_dim_vars_symbolic_equal(self):\n da, db = shape_poly.parse_spec(\"a, b\", (2, 3))\n self.assertTrue(core.symbolic_equal_dim(da, da))\n self.assertFalse(core.symbolic_equal_dim(da, 1))\n self.assertFalse(core.symbolic_equal_dim(da, db))\n\n self.assertTrue(core.symbolic_equal_one_of_dim(da, [2, da]))\n self.assertFalse(core.symbolic_equal_one_of_dim(da, [2, db]))\n self.assertFalse(core.symbolic_equal_one_of_dim(da, []))\n\n self.assertTrue(core.symbolic_equal_one_of_dim(2, [da, 3, 2]))\n self.assertFalse(core.symbolic_equal_one_of_dim(1, [2, db]))\n self.assertFalse(core.symbolic_equal_one_of_dim(3, []))\n\n def test_dim_vars_greater_equal(self):\n da, db = shape_poly.parse_spec(\"a, b\", (2, 3))\n self.assertTrue(core.greater_equal_dim(da, da))\n self.assertTrue(core.greater_equal_dim(da, 0))\n self.assertTrue(core.greater_equal_dim(da, 1))\n\n self.assertTrue(core.greater_equal_shape((da, 2), (1, 1)))\n\n with self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n \"Shape variable comparison .* is inconclusive\"):\n core.greater_equal_dim(da, 2)\n\n with self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n \"Shape variable comparison .* is inconclusive\"):\n core.greater_equal_dim(da, db)\n\n\nclass ShapeAsValueTest(tf_test_util.JaxToTfTestCase):\n\n def setUp(self):\n raise unittest.SkipTest(\"shape_as_value not supported anymore. See #6080.\")\n\n def test_concrete_shapes(self):\n # Test shape_as_value with concrete shapes. All transformations work.\n def f(x):\n return jnp.sum(x, axis=0) * jax2tf.shape_as_value(x)[0]\n\n x = np.arange(3.)\n self.assertAllClose(9., f(x))\n self.assertAllClose(9., jax.jit(f)(x))\n\n res_primal, res_tangent = jax.jvp(f, (x,), (np.array([0.1, 0.2, 0.3]),))\n self.assertAllClose((9., 1.8), (res_primal, res_tangent))\n\n self.assertAllClose(np.array([3., 3., 3.]), jax.grad(f)(x))\n\n xv = np.arange(24.).reshape((2, 3, 4))\n res_vmap = jax.vmap(f, in_axes=1)(xv)\n # Implement by iteration\n res_iter = jnp.stack([f(xv[:, i, :]) for i in range(xv.shape[1])])\n self.assertAllClose(res_iter, res_vmap)\n\n res_mask2, _ = jax.mask(f, polymorphic_shapes=[\"(b,)\"])([x], dict(b=2))\n self.assertAllClose(2., res_mask2)\n res_mask3, _ = jax.mask(f, polymorphic_shapes=[\"(b,)\"])([x], dict(b=3))\n self.assertAllClose(9., res_mask3)\n\n def test_dynamic_shapes(self):\n # Test shape_as_value with dynamic shapes. All transformations work.\n def f(x):\n return jnp.sum(x, axis=0) * jax2tf.shape_as_value(x)[0]\n\n x = np.arange(3.)\n self.assertAllClose(9., jax2tf.convert(f, polymorphic_shapes=[\"(b,)\"])(x))\n self.assertAllClose(\n 9.,\n jax2tf.convert(jax.jit(f), polymorphic_shapes=[\"(b,)\"])(x))\n self.assertAllClose(\n 9.,\n tf.function(jax2tf.convert(f, polymorphic_shapes=[\"(b,)\"]))(x))\n\n res_primal, res_tangent = jax2tf.convert(\n lambda x, xt: jax.jvp(f, (x,), (xt,)),\n polymorphic_shapes=[\"b\", \"b\"])(x, np.array([0.1, 0.2, 0.3]))\n self.assertAllClose((9., 1.8), (res_primal, res_tangent))\n\n self.assertAllClose(\n np.array([3., 3., 3.]),\n jax2tf.convert(jax.grad(f), polymorphic_shapes=[\"b\"])(x))\n\n xv = np.arange(24.).reshape((2, 3, 4))\n res_vmap = jax.vmap(f, in_axes=1)(xv)\n # Implement by iteration\n res_iter = jnp.stack([f(xv[:, i, :]) for i in range(xv.shape[1])])\n self.assertAllClose(res_iter, res_vmap)\n\n res_mask2, _ = jax.mask(f, polymorphic_shapes=[\"(b,)\"])([x], dict(b=2))\n self.assertAllClose(2., res_mask2)\n res_mask3, _ = jax.mask(f, polymorphic_shapes=[\"(b,)\"])([x], dict(b=3))\n self.assertAllClose(9., res_mask3)\n\n def test_cond(self):\n # Test the primitive under conditional\n def f(x):\n return lax.cond(\n jnp.sum(x) > 0.,\n lambda _: jnp.sum(x) / functools.reduce(lax.mul,\n jax2tf.shape_as_value(x)),\n lambda _: 0.,\n operand=None)\n\n x = np.ones((2, 3, 4))\n self.assertAllClose(1., f(x))\n self.assertAllClose(1.,\n jax2tf.convert(f, polymorphic_shapes=[\"(a, b, 4)\"])(x))\n\n def test_mean0(self):\n\n def f_jax(x):\n return jnp.sum(x, axis=0) / jax2tf.shape_as_value(x)[0]\n\n x = np.arange(12.).reshape((3, 4))\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([None, 4], dtype=x.dtype)],\n polymorphic_shapes=[(\"batch, _\")],\n expected_output_signature=tf.TensorSpec([4]))\n self.assertAllClose(np.array([4., 5., 6., 7.]), f_tf(x))\n\n def test_mean_all_axes(self):\n\n def f_jax(x):\n return jnp.sum(x) / np.prod(jax2tf.shape_as_value(x))\n\n x = np.arange(12.).reshape((3, 4))\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([None, 4], dtype=x.dtype)],\n polymorphic_shapes=[(\"batch, _\")],\n expected_output_signature=tf.TensorSpec([]))\n\n self.assertAllClose(jnp.mean(x), f_tf(x))\n\n\ndef _all_shape_poly_harnesses() -> Sequence[primitive_harness.Harness]:\n \"\"\"For each harness group, pick a single dtype.\n\n Ignore harnesses that fail in graph mode in jax2tf.\n \"\"\"\n all_h = primitive_harness.all_harnesses\n\n # Index by group\n harness_groups: Dict[\n str, Sequence[primitive_harness.Harness]] = collections.defaultdict(list)\n device = jtu.device_under_test()\n\n for h in all_h:\n # Drop the the JAX limitations\n if not h.filter(device_under_test=device, include_jax_unimpl=False):\n continue\n # And the jax2tf limitations\n if _get_jax2tf_limitations(device, h):\n continue\n harness_groups[h.group_name].append(h)\n\n res = []\n for group_name, hlist in harness_groups.items():\n # Pick the dtype with the most harnesses in this group. Some harness\n # groups only test different use cases at a few dtypes.\n c = collections.Counter([h.dtype for h in hlist])\n (dtype, _), = c.most_common(1)\n res.extend([h for h in hlist if h.dtype == dtype])\n return res\n\n\ndef _get_jax2tf_limitations(\n device, h: primitive_harness.Harness) -> Sequence[Jax2TfLimitation]:\n # And the jax2tf limitations\n def applicable_jax2tf_limitation(l: Jax2TfLimitation) -> bool:\n return (l.filter(device=device, dtype=h.dtype, mode=\"graph\") and\n l.expect_tf_error)\n\n limitations = Jax2TfLimitation.limitations_for_harness(h)\n return tuple(filter(applicable_jax2tf_limitation, limitations))\n\n\n# We do not yet support shape polymorphism for vmap for some primitives\n_VMAP_NOT_POLY_YET = frozenset([\n # In the random._gamma_impl we do reshape(-1, 2) for the keys\n \"random_gamma\",\n\n # In linalg._lu_python we do reshape(-1, ...)\n \"lu\",\n \"custom_linear_solve\",\n\n # We do *= shapes in the batching rule for conv_general_dilated\n \"conv_general_dilated\",\n\n # vmap(clamp) fails in JAX\n \"clamp\",\n])\n\n\nclass ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n \"\"\"Tests for primitives that take shape values as parameters.\"\"\"\n\n # This test runs for all primitive harnesses, and verifies that the result\n # of vmap over a primitive harness can be converted batch-polymorphically.\n @primitive_harness.parameterized(\n _all_shape_poly_harnesses(), include_jax_unimpl=False)\n @jtu.ignore_warning(\n category=UserWarning, message=\"Using reduced precision for gradient.*\")\n def test_prim_vmap(self, harness: primitive_harness.Harness):\n if harness.group_name in _VMAP_NOT_POLY_YET:\n raise unittest.SkipTest(\n f\"TODO: vmap({harness.group_name}) not yet supported\")\n func_jax = harness.dyn_fun\n args = harness.dyn_args_maker(self.rng())\n if len(args) == 0:\n # vmap not defined for functions with no args\n return\n\n res_jax = func_jax(*args)\n\n # Replicate all arguments\n batch_size = 3\n batched_args = [np.stack([a] * batch_size) for a in args]\n func_jax_vmap = jax.vmap(func_jax, in_axes=0, out_axes=0)\n # Check that batching works\n res_jax_vmap = func_jax_vmap(*batched_args)\n\n def arr_to_shape_spec(a):\n return \"b, \" + \", \".join(str(d) for d in a.shape)\n\n func_jax_vmap_polymorphic_shapes = jax.tree_map(arr_to_shape_spec,\n tuple(args))\n\n def arr_to_tf_tensor_spec(a):\n return tf.TensorSpec((None,) + a.shape, a.dtype)\n\n func_jax_vmap_input_signature = jax.tree_map(arr_to_tf_tensor_spec,\n tuple(args))\n func_jax_vmap_output_signature = jax.tree_map(arr_to_tf_tensor_spec,\n res_jax)\n f_tf = self.CheckShapePolymorphism(\n func_jax_vmap,\n input_signature=func_jax_vmap_input_signature,\n polymorphic_shapes=func_jax_vmap_polymorphic_shapes,\n expected_output_signature=func_jax_vmap_output_signature)\n\n limitations = _get_jax2tf_limitations(jtu.device_under_test(), harness)\n if any([l.custom_assert or l.skip_comparison for l in limitations]):\n self.assertAllClose(res_jax_vmap, f_tf(*batched_args))\n\n def test_add_with_broadcast(self):\n\n def f_jax(x, y):\n return jnp.add(x, y)\n\n x = np.arange(12.).reshape((3, 4))\n y = np.arange(24).reshape((2, 3, 4))\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[\n tf.TensorSpec([None, 4], dtype=x.dtype),\n tf.TensorSpec([None, None, 4], dtype=y.dtype)\n ],\n polymorphic_shapes=[\"(d, _)\", \"(batch, d, _)\"],\n expected_output_signature=tf.TensorSpec([None, None, 4]))\n\n self.assertAllClose(f_jax(x, y), f_tf(x, y))\n\n def test_broadcast(self):\n\n def f_jax(x):\n return jnp.broadcast_to(x, [x.shape[0], x.shape[0], x.shape[1]])\n\n x = np.arange(12.).reshape((3, 4))\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([None, 4], dtype=x.dtype)],\n polymorphic_shapes=[(\"batch, _\")],\n expected_output_signature=tf.TensorSpec([None, None, 4]))\n\n self.assertAllClose(f_jax(x), f_tf(x))\n\n def test_ones(self):\n\n def f_jax(x):\n return jnp.ones(x.shape, dtype=x.dtype)\n\n x_shape = (5, 6, 4)\n x = np.arange(np.prod(x_shape), dtype=np.float32).reshape(x_shape)\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([None, None, 4], dtype=x.dtype)],\n polymorphic_shapes=[(\"width, height, _\")],\n expected_output_signature=tf.TensorSpec([None, None, 4]))\n\n self.assertAllClose(f_jax(x), f_tf(x))\n\n def test_clamp(self):\n\n @jax.vmap\n def f_jax(mi, x, ma):\n return lax.clamp(mi, x, ma)\n\n x = np.ones((7, 2, 3))\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[\n tf.TensorSpec([None, 2, 3], dtype=x.dtype),\n tf.TensorSpec([None, 2, 3], dtype=x.dtype),\n tf.TensorSpec([None, 2, 3], dtype=x.dtype),\n ],\n polymorphic_shapes=[\"b, _, _\", \"b, _, _\", \"b, _, _\"],\n expected_output_signature=tf.TensorSpec([None, 2, 3], dtype=x.dtype))\n self.assertAllClose(f_jax(x, x, x), f_tf(x, x, x))\n\n def test_conv_general_dilated(self):\n batch_size = 7\n lhs_shape = (batch_size, 3, 9, 10) # 2 spatial dimensions (9, 10)\n rhs_shape = (3, 3, 4, 5)\n window_strides = (2, 3)\n padding = ((0, 0), (0, 0))\n lhs_dilation = (1, 1)\n rhs_dilation = (1, 2)\n dimension_numbers = (\"NCHW\", \"OIHW\", \"NCHW\")\n feature_group_count = 1\n batch_group_count = 1\n precision = None\n\n lhs = np.random.rand(*lhs_shape)\n rhs = np.random.rand(*rhs_shape)\n\n def f_jax(lhs, rhs):\n return lax.conv_general_dilated(lhs, rhs, window_strides, padding,\n lhs_dilation, rhs_dilation,\n dimension_numbers, feature_group_count,\n batch_group_count, precision)\n\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec(lhs_shape, dtype=lhs.dtype),\n tf.TensorSpec(rhs_shape, dtype=rhs.dtype)],\n polymorphic_shapes=[\"B, ...\", None],\n expected_output_signature=tf.TensorSpec([None, 3, 3, 1],\n dtype=lhs.dtype))\n self.assertAllClose(f_jax(lhs, rhs), f_tf(lhs, rhs))\n\n def test_conv_general_dilated_vmap(self):\n raise unittest.SkipTest(\n \"TODO: vmap(conv_general_dilated) not yet supported\")\n lhs_shape = (2, 3, 9, 10)\n rhs_shape = (3, 3, 4, 5)\n window_strides = (2, 3)\n padding = ((0, 0), (0, 0))\n lhs_dilation = (1, 1)\n rhs_dilation = (1, 2)\n dimension_numbers = (\"NCHW\", \"OIHW\", \"NCHW\")\n feature_group_count = 1\n batch_group_count = 1\n precision = None\n\n batch_size = 7\n\n lhs = np.random.rand(batch_size, *lhs_shape)\n rhs = np.random.rand(batch_size, *rhs_shape)\n\n @jax.vmap\n def f_jax(lhs, rhs):\n return lax.conv_general_dilated(lhs, rhs, window_strides, padding,\n lhs_dilation, rhs_dilation,\n dimension_numbers, feature_group_count,\n batch_group_count, precision)\n\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[\n tf.TensorSpec((None,) + lhs_shape),\n tf.TensorSpec((None,) + rhs_shape)\n ],\n polymorphic_shapes=[\"b, _, _, _, _\", \"b, _, _, _, _\"],\n expected_output_signature=tf.TensorSpec([None, 2, 3]))\n self.assertAllClose(f_jax(lhs, rhs), f_tf(lhs, rhs))\n\n def test_cummax(self):\n\n @jax.vmap\n def f_jax(x):\n return lax_control_flow.cummax(x, axis=0, reverse=False)\n\n batch_size = 7\n x = np.random.rand(batch_size, 8, 9)\n\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([None, 8, 9], dtype=x.dtype)],\n polymorphic_shapes=[\"b, _, _\"],\n expected_output_signature=tf.TensorSpec([None, 8, 9], dtype=x.dtype))\n self.assertAllClose(f_jax(x), f_tf(x))\n\n def test_dot_general(self):\n dimension_numbers = (((2,), (1,)), ((0,), (0,)))\n\n def f_jax(lhs, rhs): # lhs: [b, 4, 4], rhs: [b, 4]\n return lax.dot_general(lhs, rhs, dimension_numbers=dimension_numbers)\n\n batch_size = 7\n lhs = np.random.rand(batch_size, 4, 4)\n rhs = np.random.rand(batch_size, 4)\n\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([None, 4, 4], dtype=lhs.dtype),\n tf.TensorSpec([None, 4], dtype=rhs.dtype)],\n polymorphic_shapes=[\"b, _, _\", \"b, _\"],\n expected_output_signature=tf.TensorSpec([None, 4], dtype=lhs.dtype))\n self.assertAllClose(f_jax(lhs, rhs), f_tf(lhs, rhs))\n\n def test_dynamic_slice(self):\n\n def f_jax(x): # x:shape: (b, 4)\n return lax.dynamic_slice(x, (\n 0,\n 1,\n ), (\n x.shape[0],\n 2,\n ))\n\n batch_size = 7\n x = np.arange(100, dtype=np.float32).reshape((10, 10))[:batch_size, :4]\n\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec((None, 4))],\n polymorphic_shapes=[\"b, _\"],\n expected_output_signature=tf.TensorSpec([None, 2]))\n self.assertAllClose(f_jax(x), f_tf(x))\n\n def test_dynamic_slice_vmap(self):\n\n @jax.vmap\n def f_jax(x, idx): # x.shape : (4,)\n return lax.dynamic_slice(x, idx, slice_sizes=(2,))\n\n batch_size = 7\n x = np.arange(100, dtype=np.float32).reshape((10, 10))[:batch_size, :4]\n idx = np.arange(batch_size, dtype=np.int32).reshape((batch_size, 1))\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[\n tf.TensorSpec([None, 4]),\n tf.TensorSpec([None, 1], dtype=idx.dtype)\n ],\n polymorphic_shapes=[\"b, _\", \"b, _\"],\n expected_output_signature=tf.TensorSpec([None, 2]))\n self.assertAllClose(f_jax(x, idx), f_tf(x, idx))\n\n def test_gather(self):\n\n def f(a, i):\n return jnp.take(a, i, axis=1)\n\n x = np.arange(1000, dtype=np.float32).reshape((10, 10, 10))[:2, :3, :4]\n i = np.array([1, 2], np.int32)\n\n f_tf = self.CheckShapePolymorphism(\n f,\n input_signature=[\n tf.TensorSpec([None, 3, 4], dtype=x.dtype),\n tf.TensorSpec([2], np.int32)\n ],\n polymorphic_shapes=[\"(batch, _, _)\", \"(_)\"],\n expected_output_signature=tf.TensorSpec([None, 2, 4], dtype=x.dtype))\n\n self.assertAllClose(f(x, i), f_tf(x, i))\n\n # Does not yet work\n # f_tf = self.CheckShapePolymorphism(\n # f,\n # input_signature=[tf.TensorSpec([None, 3, 4]), tf.TensorSpec([None], np.int32)],\n # polymorphic_shapes=[\"batch, _, _\", \"batch\"],\n # expected_output_signature=tf.TensorSpec([None, None, 4]))\n # self.assertAllClose(f(x, i), f_tf(x, i))\n\n def test_gather_vmap(self):\n\n @jax.vmap\n def f(a, i):\n return jnp.take(a, i, axis=0)\n\n x = np.arange(1000, dtype=np.float32).reshape((10, 10, 10))[:2, :3, :4]\n i = np.array([1, 2], np.int32)\n\n f_tf = self.CheckShapePolymorphism(\n f,\n input_signature=[\n tf.TensorSpec([None, 3, 4], dtype=x.dtype),\n tf.TensorSpec([None], np.int32)\n ],\n polymorphic_shapes=[\"batch, _, _\", \"batch\"],\n expected_output_signature=tf.TensorSpec([None, 4], dtype=x.dtype))\n\n self.assertAllClose(f(x, i), f_tf(x, i))\n\n def test_iota(self):\n\n def f_jax(x):\n x + lax.iota(np.float32, x.shape[0])\n\n x = np.arange(12.)\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([None], dtype=x.dtype)],\n polymorphic_shapes=[\"d\"],\n expected_output_signature=None)\n\n self.assertAllClose(f_jax(x), f_tf(x))\n\n def test_matmul(self):\n\n def f_jax(x, y):\n return jnp.matmul(x, y)\n\n x = np.random.rand(7, 8, 4)\n y = np.random.rand(7, 4, 5)\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[\n tf.TensorSpec([None, 8, 4], dtype=x.dtype),\n tf.TensorSpec([None, 4, None], dtype=y.dtype)\n ],\n polymorphic_shapes=[\"(batch, _, 4)\", \"(batch, 4, w)\"],\n expected_output_signature=tf.TensorSpec([None, 8, None], dtype=x.dtype))\n\n self.assertAllClose(f_jax(x, y), f_tf(x, y))\n\n def test_pad(self):\n\n def f_jax(x):\n return lax.pad(x, np.float_(5.), ((0, 0, 0), (0, 0, 0), (1, 1, 1)))\n\n batch_size = 7\n x = np.random.rand(batch_size, 2, 3)\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([None, 2, 3], dtype=x.dtype)],\n polymorphic_shapes=[\"(batch, _, _)\"],\n expected_output_signature=tf.TensorSpec([None, 2, 7], dtype=x.dtype))\n self.assertAllClose(f_jax(x), f_tf(x))\n\n def test_random_gamma(self):\n if \"random_gamma\" in _VMAP_NOT_POLY_YET:\n raise unittest.SkipTest(\"TODO: vmap(random_gamma) not yet supported\")\n\n def f_jax(key, a):\n return jax.random.gamma(key, a)\n\n batch_size = 7\n key = np.random.rand(batch_size, 2)\n a = np.random.rand(batch_size, 3)\n\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[\n tf.TensorSpec([None, 2], dtype=key.dtype),\n tf.TensorSpec([None, 3], dtype=a.dtype)\n ],\n polymorphic_shapes=[\"(batch, _)\", \"(batch, _)\"],\n expected_output_signature=tf.TensorSpec([None, 3]))\n self.assertAllClose(f_jax(key, a), f_tf(key, a))\n\n def test_reshape(self):\n\n self.CheckShapePolymorphism(\n lambda x: x.reshape([x.shape[0], -1]),\n input_signature=[tf.TensorSpec([None, 2, 3])],\n polymorphic_shapes=[\"batch, _, _\"],\n expected_output_signature=tf.TensorSpec([None, 6]))\n\n self.CheckShapePolymorphism(\n lambda x: x.reshape([x.shape[0], -1, x.shape[3], x.shape[2]]),\n input_signature=[tf.TensorSpec([None, 2, None, None, 3])],\n polymorphic_shapes=[\"batch, 2, batch, height, 3\"],\n expected_output_signature=tf.TensorSpec([None, 6, None, None]))\n\n with self.assertRaisesRegex(\n core.InconclusiveDimensionOperation,\n re.escape(\n \"Shapes (batch, 2, batch, height, 3) and (batch, -1, batch) must have the same set of shape variables\"\n )):\n self.CheckShapePolymorphism(\n lambda x: x.reshape([x.shape[0], -1, x.shape[2]]),\n input_signature=[tf.TensorSpec([None, 2, None, None, 3])],\n polymorphic_shapes=[\"batch, 2, batch, height, 3\"],\n expected_output_signature=tf.TensorSpec([None, 6, None]))\n\n with self.assertRaisesRegex(\n core.InconclusiveDimensionOperation,\n re.escape(\n \"Cannot divide evenly the sizes of shapes (2, 4) and (-1, 3)\")):\n self.CheckShapePolymorphism(\n lambda x: x.reshape([x.shape[0], -1, 3]),\n input_signature=[tf.TensorSpec([None, 2, 4])],\n polymorphic_shapes=[PS(\"batch\", ...)],\n expected_output_signature=tf.TensorSpec([None, 1]))\n\n def test_reshape_compiled(self):\n # We compile the result of conversion for two shapes, hence we need to\n # involve the TF compiler twice, but we trace only once with shape polymorphism\n traced = False\n\n def f_jax(x):\n nonlocal traced\n traced = True\n y = jnp.sin(x)\n return y.reshape([x.shape[0], -1])\n\n x = np.random.rand(4, 2, 3)\n res_jax = f_jax(x)\n\n traced = False\n # If we get_concrete_function we trace once\n f_tf = tf.function(\n jax2tf.convert(f_jax, polymorphic_shapes=[PS(\"b\", ...)]),\n autograph=False,\n jit_compile=True).get_concrete_function(\n tf.TensorSpec([None, 2, 3], x.dtype))\n self.assertTrue(traced)\n traced = False\n self.assertAllClose(res_jax, f_tf(x))\n self.assertFalse(traced) # We are not tracing again\n\n x = np.random.rand(6, 2, 3)\n res_jax = f_jax(x)\n traced = False\n\n self.assertAllClose(res_jax, f_tf(x))\n self.assertFalse(traced) # We are not tracing again\n\n def test_scatter(self):\n batch_size = 7\n x = np.arange(100, dtype=np.float32).reshape((10, 10))[:batch_size, :4]\n idx = np.array([[1], [2]], np.int32)\n upd = -np.arange(100, dtype=np.float32).reshape((10, 10))[:batch_size, :2]\n dimension_numbers = ((0,), (1,), (1,))\n\n def f_jax(x, upd):\n return lax.scatter_add(\n x,\n scatter_indices=idx,\n updates=upd,\n dimension_numbers=lax.ScatterDimensionNumbers(*dimension_numbers),\n indices_are_sorted=False,\n unique_indices=True)\n\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[\n tf.TensorSpec([None, 4], dtype=x.dtype),\n tf.TensorSpec([None, 2], dtype=upd.dtype)\n ],\n polymorphic_shapes=[\"b, _\", \"b, _\"],\n expected_output_signature=tf.TensorSpec([None, 4]))\n\n self.assertAllClose(f_jax(x, upd), f_tf(x, upd))\n\n def test_select(self):\n\n def f_jax(x): # x.shape = (b, 3)\n return lax.select(x > 5., x, x)\n\n x = np.arange(100, dtype=np.float32).reshape((10, 10))[:7, :3]\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([None, 3], dtype=x.dtype)],\n polymorphic_shapes=[\"(b, _)\"],\n expected_output_signature=tf.TensorSpec([None, 3]))\n\n self.assertAllClose(f_jax(x), f_tf(x))\n\n def test_select_vmap_0(self):\n\n @jax.vmap\n def f_jax(x): # x.shape = (3,)\n return lax.select(x > 5., x, x)\n\n x = np.arange(100, dtype=np.float32).reshape((10, 10))[:7, :3]\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([None, 3], dtype=x.dtype)],\n polymorphic_shapes=[\"(b, _)\"],\n expected_output_signature=tf.TensorSpec([None, 3]))\n\n self.assertAllClose(f_jax(x), f_tf(x))\n\n def test_select_vmap_1(self):\n\n @functools.partial(jax.vmap, in_axes=(0, None))\n def f_jax(x, y): # x.shape = (3,)\n return lax.select(x > 5., x, y)\n\n x = np.arange(100, dtype=np.float32).reshape((10, 10))[:7, :3]\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[\n tf.TensorSpec([None, 3], dtype=x.dtype),\n tf.TensorSpec([3], dtype=x.dtype)\n ],\n polymorphic_shapes=[\"(b, _)\", \"_\"],\n expected_output_signature=tf.TensorSpec([None, 3]))\n\n self.assertAllClose(f_jax(x, x[0]), f_tf(x, x[0]))\n\n def test_slice(self):\n\n def f_jax(x): # x.shape = (b, 3)\n return lax.slice(x, start_indices=(0, 1), limit_indices=(x.shape[0], 3))\n\n x = np.arange(100, dtype=np.float32).reshape((10, 10))[:7, :3]\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([None, 3], dtype=x.dtype)],\n polymorphic_shapes=[\"(b, _)\"],\n expected_output_signature=tf.TensorSpec([None, 2]))\n\n self.assertAllClose(f_jax(x), f_tf(x))\n\n def test_squeeze(self):\n\n def f_jax(x):\n return jnp.squeeze(x, axis=1)\n\n x = np.random.rand(4, 1)\n res_jax = f_jax(x)\n\n # Trace with a known dimension to squeeze\n f_tf = self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([None, 1], dtype=x.dtype)],\n polymorphic_shapes=[PS(\"b\", ...)],\n expected_output_signature=tf.TensorSpec([None]))\n\n self.assertAllClose(res_jax, f_tf(x))\n\n with self.assertRaisesRegex(\n core.InconclusiveDimensionOperation,\n re.escape(\"Shape variable comparison b2 == 1 is inconclusive\")):\n # Trace with unknown dimension to squeeze\n self.CheckShapePolymorphism(\n f_jax,\n input_signature=[tf.TensorSpec([None, None])],\n polymorphic_shapes=[PS(\"b1\", \"b2\")],\n expected_output_signature=tf.TensorSpec([None]))\n\n\nif __name__ == \"__main__\":\n absltest.main(testLoader=jtu.JaxTestLoader())\n" ]
[ [ "tensorflow.TensorSpec", "numpy.array", "numpy.random.rand", "tensorflow.GradientTape", "numpy.ones", "tensorflow.Variable", "numpy.float_", "tensorflow.function", "numpy.stack", "numpy.arange", "numpy.prod" ] ]
jogvanb/sdg-faroese-translation
[ "d21278ae0b0c5845f40137bb75cdf01eb931f64f" ]
[ "scripts/export_translation_file.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nExport all translation keys to a CSV file for easy translation.\n\"\"\"\n\nimport os\nimport yaml\nimport pandas as pd\nimport csv\nimport sys\n\n# Decide if we actually want to export a particular key.\ndef should_we_omit_key(key, language):\n\n # Ignore keys that start with and end with these values.\n starts_with_and_ends_with = [\n # No need to translate URLs.\n ('global_indicators', 'metadata_link'),\n # No need to translate organisation names.\n ('global_indicators', 'custodian_agency'),\n # For now let's leave off the \"Definition\" as well, only because it\n # would be a significant translation effort, and we may want to find out\n # whether the UN may eventually do this translation.\n ('global_indicators', 'definition'),\n ]\n # Add some more for offical UN languages.\n official_un_languages = ['es', 'fr', 'zh-Hans']\n if language in official_un_languages:\n starts_with_and_ends_with.extend([\n # The titles for these are pulled directly from UN sources.\n ('global_indicators', 'title'),\n ('global_targets', 'title'),\n ('global_goals', 'title'),\n ])\n # Ignore keys that start with these values.\n starts_with = [\n # This key is identical in all languages.\n 'languages'\n ]\n\n # Now do the actual ignoring.\n for item in starts_with_and_ends_with:\n if key.startswith(item[0]) and key.endswith(item[1]):\n return True\n for item in starts_with:\n if key.startswith(item):\n return True\n\n # Still here? It must be fine.\n return False\n\n# Parse and \"flatten\" the yaml from a translation file.\ndef parse_translation_data(filepath):\n try:\n with open(filepath, 'r') as stream:\n yamldata = yaml.load(stream)\n # Use an unusual \"sep\" below so that dots can still be used in keys.\n df = pd.io.json.json_normalize(yamldata, sep='---')\n return df.to_dict(orient='records')[0]\n except Exception as exc:\n # Could not load the file, return an empty object.\n return {}\n\ndef export_language(language, folder):\n src_language = 'en'\n rows = []\n src = os.path.join('translations', src_language)\n dest = os.path.join('translations', language)\n # A flag to remember whether a translation already exists or not.\n translation_exists = os.path.isdir(dest)\n\n # Loop through the translation files in the source language.\n for filename in os.listdir(src):\n file_parts = os.path.splitext(filename)\n no_extension = file_parts[0]\n extension = file_parts[1]\n # Only operate on Yaml files.\n if extension == '.yml':\n src_filepath = os.path.join(src, filename)\n src_data = parse_translation_data(src_filepath)\n # If a translation does not exist, the third column will be blank.\n # But if a translation exists, we want to populate the third column\n # with the current translation.\n dest_data = {}\n if translation_exists:\n dest_filepath = os.path.join(dest, filename)\n dest_data = parse_translation_data(dest_filepath)\n # Loop through the source data and append rows for the CSV output.\n for key in src_data:\n full_key = no_extension + ':' + key\n # First make sure we shouldn't ignore this one.\n if should_we_omit_key(full_key, language):\n continue\n rows.append({\n # First column is a combination of the filename and the\n # \"flattened\" key, separated by a colon. For example:\n # frontpage:disclaimer_text\n 'key': full_key,\n # Second column is the source language - English.\n src_language: src_data[key],\n # Third column is the destination language, if it exists.\n language: dest_data[key] if key in dest_data else ''\n })\n keys = rows[0].keys()\n\n # Write our results to a file.\n if not os.path.exists(folder):\n os.makedirs(folder, exist_ok=True)\n csv_filename = 'sdg-translations-' + language + '.csv'\n csv_filepath = os.path.join(folder, csv_filename)\n with open(csv_filepath, 'w', encoding='utf-8-sig') as output_file:\n dict_writer = csv.DictWriter(output_file, keys)\n dict_writer.writeheader()\n dict_writer.writerows(rows)\n\ndef main():\n\n # Abort if there is no parameter provided.\n if len(sys.argv) < 2:\n sys.exit('Provide a 2-letter abbreviation for the target language.')\n language = sys.argv[1]\n export_language(language, '.')\n\n# Boilerplace syntax for running the main function.\nif __name__ == '__main__':\n main()\n" ]
[ [ "pandas.io.json.json_normalize" ] ]
gauravb12/Dos-Attack-Detection-using-Machine-Learning
[ "5ccaa2796c016c85a6f579ee6862078817e434f1" ]
[ "Dataset.py" ]
[ "import sklearn\nimport numpy as np\nfrom utils.LogHelper import Logs\nfrom utils.DateUtil import get_microseconds\nfrom utils.Anomaly import Anomaly\nfrom sklearn import preprocessing\n\n\nclass Dataset:\n\n def __init__(self):\n\n self.logs = Logs().read()\n self.client_ip_label_encoder = preprocessing.LabelEncoder()\n self.request_method_label_encoder = preprocessing.LabelEncoder()\n self.request_status_label_encoder = preprocessing.LabelEncoder()\n self.request_size_label_encoder = preprocessing.LabelEncoder()\n self.time_taken_to_serve_label_encoder =preprocessing.LabelEncoder()\n self.user_agent_label_encoder =preprocessing.LabelEncoder()\n self.request_header_label_encoder = preprocessing.LabelEncoder()\n\n self.scores = []\n self.client_ips = []\n self.request_methods = []\n self.request_status = []\n self.request_size = []\n self.times_taken_to_serve = []\n self.user_agents = []\n self.request_headers = []\n\n self.dataset = []\n\n def preprocess_time(self):\n timestamp_clusters = {}\n for row in self.logs:\n timestamp = get_microseconds(row[0])\n if timestamp not in timestamp_clusters:\n timestamp_clusters[timestamp]=0\n timestamp_clusters[timestamp] = timestamp_clusters[timestamp] + 1\n anomaly_scores = Anomaly().detect(timestamp_clusters)\n for row in self.logs:\n self.scores.append(anomaly_scores[row[0]])\n\n def preprocess_client_ip(self):\n self.client_ip_label_encoder.fit([row[1] for row in self.logs])\n inst = [row[1] for row in self.logs]\n self.client_ips = self.client_ip_label_encoder.transform(inst)\n\n def preprocess_request_method(self):\n self.request_method_label_encoder.fit([row[2] for row in self.logs])\n inst = [row[2] for row in self.logs]\n self.request_methods = self.request_method_label_encoder.transform(inst)\n\n def preprocess_request_status(self):\n self.request_status_label_encoder.fit([row[3] for row in self.logs])\n inst = [row[3] for row in self.logs]\n self.request_status = self.request_status_label_encoder.transform(inst)\n\n def preprocess_request_size(self):\n self.request_size_label_encoder.fit([row[4] for row in self.logs])\n inst = [row[4] for row in self.logs]\n self.request_size = self.request_size_label_encoder.transform(inst)\n\n def preprocess_time_taken_to_serve(self):\n self.time_taken_to_serve_label_encoder.fit([row[5] for row in self.logs])\n inst = [row[5] for row in self.logs]\n self.times_taken_to_serve = self.time_taken_to_serve_label_encoder.transform(inst)\n\n def proprocess_user_agent(self):\n self.user_agent_label_encoder.fit([row[6] for row in self.logs])\n inst = [row[6] for row in self.logs]\n self.user_agents = self.user_agent_label_encoder.transform(inst)\n\n def preprocess_request_header(self):\n self.request_header_label_encoder.fit([row[7] for row in self.logs])\n inst = [row[7] for row in self.logs]\n self.request_headers = self.request_header_label_encoder.transform(inst)\n\n def detransform_client_ip(self, client_ip_list):\n return self.client_ip_label_encoder.inverse_transform(client_ip_list)\n\n def preprocess(self):\n\n self.preprocess_time()\n self.preprocess_client_ip()\n self.preprocess_request_method()\n self.preprocess_request_status()\n self.preprocess_request_size()\n self.preprocess_time_taken_to_serve()\n self.proprocess_user_agent()\n self.preprocess_request_header()\n\n dataset_size = len(self.logs)\n for i in range(dataset_size):\n obj = [\n self.logs[i][0],\n self.scores[i],\n self.client_ips[i],\n self.request_methods[i],\n self.request_status[i],\n self.request_size[i],\n self.times_taken_to_serve[i],\n self.user_agents[i],\n self.request_headers[i]\n ]\n self.dataset.append(obj)\n\n def read_dataset(self):\n self.preprocess()\n return self.dataset\n\n\nif __name__=='__main__':\n dataset_obj = Dataset()\n dataset_obj.preprocess()" ]
[ [ "sklearn.preprocessing.LabelEncoder" ] ]
aouedions11/flower
[ "70bfbcfab2fedff1abf7a59a5539621cfc1adcc1" ]
[ "examples/pytorch_from_centralized_to_federated/cifar.py" ]
[ "\"\"\"PyTorch CIFAR-10 image classification.\n\nThe code is generally adapted from 'PyTorch: A 60 Minute Blitz'. Further\nexplanations are given in the official PyTorch tutorial:\n\nhttps://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html\n\"\"\"\n\n\n# mypy: ignore-errors\n# pylint: disable=W0223\n\n\nfrom typing import Tuple\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch import Tensor\nfrom torchvision.datasets import CIFAR10\n\nDATA_ROOT = \"~/.flower/data/cifar-10\"\n\n# pylint: disable=unsubscriptable-object\nclass Net(nn.Module):\n \"\"\"Simple CNN adapted from 'PyTorch: A 60 Minute Blitz'.\"\"\"\n\n def __init__(self) -> None:\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n\n # pylint: disable=arguments-differ,invalid-name\n def forward(self, x: Tensor) -> Tensor:\n \"\"\"Compute forward pass.\"\"\"\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 16 * 5 * 5)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\ndef load_data() -> Tuple[torch.utils.data.DataLoader, torch.utils.data.DataLoader]:\n \"\"\"Load CIFAR-10 (training and test set).\"\"\"\n transform = transforms.Compose(\n [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]\n )\n trainset = CIFAR10(DATA_ROOT, train=True, download=True, transform=transform)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=32, shuffle=True)\n testset = CIFAR10(DATA_ROOT, train=False, download=True, transform=transform)\n testloader = torch.utils.data.DataLoader(testset, batch_size=32, shuffle=False)\n return trainloader, testloader\n\n\ndef train(\n net: Net,\n trainloader: torch.utils.data.DataLoader,\n epochs: int,\n device: torch.device, # pylint: disable=no-member\n) -> None:\n \"\"\"Train the network.\"\"\"\n # Define loss and optimizer\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\n\n print(f\"Training {epochs} epoch(s) w/ {len(trainloader)} batches each\")\n\n # Train the network\n for epoch in range(epochs): # loop over the dataset multiple times\n running_loss = 0.0\n for i, data in enumerate(trainloader, 0):\n images, labels = data[0].to(device), data[1].to(device)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = net(images)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n if i % 100 == 99: # print every 100 mini-batches\n print(\"[%d, %5d] loss: %.3f\" % (epoch + 1, i + 1, running_loss / 2000))\n running_loss = 0.0\n\n\ndef test(\n net: Net,\n testloader: torch.utils.data.DataLoader,\n device: torch.device, # pylint: disable=no-member\n) -> Tuple[float, float]:\n \"\"\"Validate the network on the entire test set.\"\"\"\n criterion = nn.CrossEntropyLoss()\n correct = 0\n total = 0\n loss = 0.0\n with torch.no_grad():\n for data in testloader:\n images, labels = data[0].to(device), data[1].to(device)\n outputs = net(images)\n loss += criterion(outputs, labels).item()\n _, predicted = torch.max(outputs.data, 1) # pylint: disable=no-member\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n accuracy = correct / total\n return loss, accuracy\n\n\ndef main():\n DEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n print(\"Centralized PyTorch training\")\n print(\"Load data\")\n trainloader, testloader = load_data()\n net = Net()\n print(\"Start training\")\n train(net=net, trainloader=trainloader, epochs=2, device=DEVICE)\n print(\"Evaluate model\")\n loss, accuracy = test(net=net, testloader=testloader, device=DEVICE)\n print(\"Loss: \", loss)\n print(\"Accuracy: \", accuracy)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "torch.nn.Linear", "torch.nn.MaxPool2d", "torch.max", "torch.no_grad", "torch.nn.Conv2d", "torch.cuda.is_available", "torch.utils.data.DataLoader", "torch.nn.CrossEntropyLoss" ] ]
zampie/male-female-transfer
[ "6f72a2c2fb4df2c7669723dd27c192a594ffe4e6" ]
[ "inference_my_m.py" ]
[ "\"\"\"Translate an image to another image\nAn example of command-line usage is:\npython export_graph.py --model pretrained/apple2orange.pb \\\n --input input_sample.jpg \\\n --output output_sample.jpg \\\n --image_size 256\n\"\"\"\n\nimport tensorflow as tf\nimport os\n#import cv2\n#from model import CycleGAN\nimport utils\nimport glob\n\n# FLAGS = tf.flags.FLAGS\n#\n# name = '202580.jpg'\n#\n#\n# tf.flags.DEFINE_string('model', 'pretrained/female2anime.pb', 'model path (.pb)')\n# tf.flags.DEFINE_string('input', 'C:/Users/Zampie/Desktop/inf/' + name, 'input image path (.jpg)')\n# tf.flags.DEFINE_string('output', 'C:/Users/Zampie/Desktop/inf/a_' + name, 'output image path (.jpg)')\n# tf.flags.DEFINE_integer('image_size', '128', 'image size, default: 256')\n\npath = './dataM/'\nimgs = glob.glob(path + '*.jpg')\n#model = 'pretrained/male2female_5d_2.pb'\nmodel = './pretrained/female2male_2d.pb'\nimage_size = 128\n\n\ndef inference():\n graph = tf.Graph()\n\n with tf.Session(graph=graph) as sess:\n with graph.as_default():\n '''\n for input in imgs:\n output = input[0:-4] + '_f.jpg'\n\n with tf.gfile.FastGFile(input, 'rb') as f:\n image_data = f.read()\n input_image = tf.image.decode_jpeg(image_data, channels=3)\n input_image = tf.image.resize_images(input_image, size=(image_size, image_size))\n input_image = utils.convert2float(input_image)\n input_image.set_shape([image_size, image_size, 3])\n\n with tf.gfile.FastGFile(model, 'rb') as model_file:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(model_file.read())\n\n [output_image] = tf.import_graph_def(graph_def,\n input_map={'input_image': input_image},\n return_elements=['output_image:0'],\n name='output')\n\n generated = output_image.eval()\n\t\t#cv2.imshow('frame', output_image)\n\n with open(output, 'wb') as f:\n f.write(generated)\n #cv2.imshow('frame', generated)\n '''\n for i in range(3):\n inputdata = \"./dataM/img_{}.jpg\".format(i)\n output = \"./dataM/img_{}.jpg\".format(i+1)\n\n with tf.gfile.FastGFile(inputdata, 'rb') as f:\n image_data = f.read()\n input_image = tf.image.decode_jpeg(image_data, channels=3)\n input_image = tf.image.resize_images(input_image, size=(image_size, image_size))\n input_image = utils.convert2float(input_image)\n input_image.set_shape([image_size, image_size, 3])\n\n with tf.gfile.FastGFile(model, 'rb') as model_file:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(model_file.read())\n\n [output_image] = tf.import_graph_def(graph_def,\n input_map={'input_image': input_image},\n return_elements=['output_image:0'],\n name='output')\n\n generated = output_image.eval()\n\t\t#cv2.imshow('frame', output_image)\n\n with open(output, 'wb') as f:\n f.write(generated)\n #cv2.imshow('frame', generated)\n\ndef main(unused_argv):\n inference()\n\n\nif __name__ == '__main__':\n tf.app.run()\n" ]
[ [ "tensorflow.Graph", "tensorflow.Session", "tensorflow.import_graph_def", "tensorflow.GraphDef", "tensorflow.gfile.FastGFile", "tensorflow.app.run", "tensorflow.image.resize_images", "tensorflow.image.decode_jpeg" ] ]
isabelaconstantin/wikinet
[ "d12ac15d494c65502c8e2ec8165351fefa676282" ]
[ "milestone1/sparse.py" ]
[ "from scipy import sparse\nimport time\n\nstart = time.perf_counter()\nAs = sparse.csr_matrix(adjacency_undirected)\nAs = As*As*As\nAd = np.empty(adjacency_undirected.shape, dtype=adjacency_undirected.dtype)\nAs.todense(out=Ad)\nprint(time.perf_counter() - start)\n\nstart = time.perf_counter()\nadjacency_undirected_power_3=np.linalg.matrix_power(adjacency_undirected,3)\nprint(time.perf_counter() - start)" ]
[ [ "scipy.sparse.csr_matrix" ] ]
jiwidi/lightning-tutorials
[ "70ba437447f345d4d6ba089d5b30fd1da2cbc04b" ]
[ "lightning_examples/mnist-hello-world/hello-world.py" ]
[ "# %%\nimport os\n\nimport torch\nfrom pytorch_lightning import LightningModule, Trainer\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.utils.data import DataLoader, random_split\nfrom torchmetrics import Accuracy\nfrom torchvision import transforms\nfrom torchvision.datasets import MNIST\n\nPATH_DATASETS = os.environ.get(\"PATH_DATASETS\", \".\")\nAVAIL_GPUS = min(1, torch.cuda.device_count())\nBATCH_SIZE = 256 if AVAIL_GPUS else 64\n\n# %% [markdown]\n# ## Simplest example\n#\n# Here's the simplest most minimal example with just a training loop (no validation, no testing).\n#\n# **Keep in Mind** - A `LightningModule` *is* a PyTorch `nn.Module` - it just has a few more helpful features.\n\n\n# %%\nclass MNISTModel(LightningModule):\n def __init__(self):\n super().__init__()\n self.l1 = torch.nn.Linear(28 * 28, 10)\n\n def forward(self, x):\n return torch.relu(self.l1(x.view(x.size(0), -1)))\n\n def training_step(self, batch, batch_nb):\n x, y = batch\n loss = F.cross_entropy(self(x), y)\n return loss\n\n def configure_optimizers(self):\n return torch.optim.Adam(self.parameters(), lr=0.02)\n\n\n# %% [markdown]\n# By using the `Trainer` you automatically get:\n# 1. Tensorboard logging\n# 2. Model checkpointing\n# 3. Training and validation loop\n# 4. early-stopping\n\n# %%\n# Init our model\nmnist_model = MNISTModel()\n\n# Init DataLoader from MNIST Dataset\ntrain_ds = MNIST(PATH_DATASETS, train=True, download=True, transform=transforms.ToTensor())\ntrain_loader = DataLoader(train_ds, batch_size=BATCH_SIZE)\n\n# Initialize a trainer\ntrainer = Trainer(\n gpus=AVAIL_GPUS,\n max_epochs=3,\n progress_bar_refresh_rate=20,\n)\n\n# Train the model ⚡\ntrainer.fit(mnist_model, train_loader)\n\n# %% [markdown]\n# ## A more complete MNIST Lightning Module Example\n#\n# That wasn't so hard was it?\n#\n# Now that we've got our feet wet, let's dive in a bit deeper and write a more complete `LightningModule` for MNIST...\n#\n# This time, we'll bake in all the dataset specific pieces directly in the `LightningModule`.\n# This way, we can avoid writing extra code at the beginning of our script every time we want to run it.\n#\n# ---\n#\n# ### Note what the following built-in functions are doing:\n#\n# 1. [prepare_data()](https://pytorch-lightning.readthedocs.io/en/stable/common/lightning_module.html#prepare-data) 💾\n# - This is where we can download the dataset. We point to our desired dataset and ask torchvision's `MNIST` dataset class to download if the dataset isn't found there.\n# - **Note we do not make any state assignments in this function** (i.e. `self.something = ...`)\n#\n# 2. [setup(stage)](https://pytorch-lightning.readthedocs.io/en/stable/common/lightning_module.html#setup) ⚙️\n# - Loads in data from file and prepares PyTorch tensor datasets for each split (train, val, test).\n# - Setup expects a 'stage' arg which is used to separate logic for 'fit' and 'test'.\n# - If you don't mind loading all your datasets at once, you can set up a condition to allow for both 'fit' related setup and 'test' related setup to run whenever `None` is passed to `stage` (or ignore it altogether and exclude any conditionals).\n# - **Note this runs across all GPUs and it *is* safe to make state assignments here**\n#\n# 3. [x_dataloader()](https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.core.hooks.html) ♻️\n# - `train_dataloader()`, `val_dataloader()`, and `test_dataloader()` all return PyTorch `DataLoader` instances that are created by wrapping their respective datasets that we prepared in `setup()`\n\n\n# %%\nclass LitMNIST(LightningModule):\n def __init__(self, data_dir=PATH_DATASETS, hidden_size=64, learning_rate=2e-4):\n\n super().__init__()\n\n # Set our init args as class attributes\n self.data_dir = data_dir\n self.hidden_size = hidden_size\n self.learning_rate = learning_rate\n\n # Hardcode some dataset specific attributes\n self.num_classes = 10\n self.dims = (1, 28, 28)\n channels, width, height = self.dims\n self.transform = transforms.Compose(\n [\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,)),\n ]\n )\n\n # Define PyTorch model\n self.model = nn.Sequential(\n nn.Flatten(),\n nn.Linear(channels * width * height, hidden_size),\n nn.ReLU(),\n nn.Dropout(0.1),\n nn.Linear(hidden_size, hidden_size),\n nn.ReLU(),\n nn.Dropout(0.1),\n nn.Linear(hidden_size, self.num_classes),\n )\n\n self.accuracy = Accuracy()\n\n def forward(self, x):\n x = self.model(x)\n return F.log_softmax(x, dim=1)\n\n def training_step(self, batch, batch_idx):\n x, y = batch\n logits = self(x)\n loss = F.nll_loss(logits, y)\n return loss\n\n def validation_step(self, batch, batch_idx):\n x, y = batch\n logits = self(x)\n loss = F.nll_loss(logits, y)\n preds = torch.argmax(logits, dim=1)\n self.accuracy(preds, y)\n\n # Calling self.log will surface up scalars for you in TensorBoard\n self.log(\"val_loss\", loss, prog_bar=True)\n self.log(\"val_acc\", self.accuracy, prog_bar=True)\n return loss\n\n def test_step(self, batch, batch_idx):\n # Here we just reuse the validation_step for testing\n return self.validation_step(batch, batch_idx)\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=self.learning_rate)\n return optimizer\n\n ####################\n # DATA RELATED HOOKS\n ####################\n\n def prepare_data(self):\n # download\n MNIST(self.data_dir, train=True, download=True)\n MNIST(self.data_dir, train=False, download=True)\n\n def setup(self, stage=None):\n\n # Assign train/val datasets for use in dataloaders\n if stage == \"fit\" or stage is None:\n mnist_full = MNIST(self.data_dir, train=True, transform=self.transform)\n self.mnist_train, self.mnist_val = random_split(mnist_full, [55000, 5000])\n\n # Assign test dataset for use in dataloader(s)\n if stage == \"test\" or stage is None:\n self.mnist_test = MNIST(self.data_dir, train=False, transform=self.transform)\n\n def train_dataloader(self):\n return DataLoader(self.mnist_train, batch_size=BATCH_SIZE)\n\n def val_dataloader(self):\n return DataLoader(self.mnist_val, batch_size=BATCH_SIZE)\n\n def test_dataloader(self):\n return DataLoader(self.mnist_test, batch_size=BATCH_SIZE)\n\n\n# %%\nmodel = LitMNIST()\ntrainer = Trainer(\n gpus=AVAIL_GPUS,\n max_epochs=3,\n progress_bar_refresh_rate=20,\n)\ntrainer.fit(model)\n\n# %% [markdown]\n# ### Testing\n#\n# To test a model, call `trainer.test(model)`.\n#\n# Or, if you've just trained a model, you can just call `trainer.test()` and Lightning will automatically\n# test using the best saved checkpoint (conditioned on val_loss).\n\n# %%\ntrainer.test()\n\n# %% [markdown]\n# ### Bonus Tip\n#\n# You can keep calling `trainer.fit(model)` as many times as you'd like to continue training\n\n# %%\ntrainer.fit(model)\n\n# %% [markdown]\n# In Colab, you can use the TensorBoard magic function to view the logs that Lightning has created for you!\n\n# %%\n# Start tensorboard.\n# %load_ext tensorboard\n# %tensorboard --logdir lightning_logs/\n" ]
[ [ "torch.nn.Linear", "torch.nn.Dropout", "torch.utils.data.random_split", "torch.nn.functional.log_softmax", "torch.cuda.device_count", "torch.nn.ReLU", "torch.utils.data.DataLoader", "torch.nn.functional.nll_loss", "torch.argmax", "torch.nn.Flatten" ] ]
hrc2da/armtui
[ "316c20fba975c2456e4a19162a66d431f97d20cb" ]
[ "SimpleHTR/wordnet/eval.py" ]
[ "import argparse\nfrom collections import namedtuple\n\nimport numpy as np\nimport torch\nfrom path import Path\n\nfrom wordnet.aabb import AABB\nfrom wordnet.aabb_clustering import cluster_aabbs\nfrom wordnet.coding import decode, fg_by_cc\nfrom wordnet.dataloader import DataLoaderIAM\nfrom wordnet.dataset import DatasetIAM, DatasetIAMSplit, DatasetHIRO, DatasetHIROSplit\nfrom wordnet.iou import compute_dist_mat_2\nfrom wordnet.loss import compute_loss\nfrom wordnet.net import WordDetectorNet\nfrom wordnet.utils import compute_scale_down\nfrom wordnet.visualization import visualize_and_plot\n\nEvaluateRes = namedtuple('EvaluateRes', 'batch_imgs,batch_aabbs,loss,metrics')\n\n\nclass BinaryClassificationMetrics:\n def __init__(self, tp, fp, fn):\n self.tp = tp\n self.fp = fp\n self.fn = fn\n\n def accumulate(self, other):\n tp = self.tp + other.tp\n fp = self.fp + other.fp\n fn = self.fn + other.fn\n return BinaryClassificationMetrics(tp, fp, fn)\n\n def recall(self):\n return self.tp / (self.tp + self.fp) if self.tp + self.fp > 0 else 0\n\n def precision(self):\n return self.tp / (self.tp + self.fn) if self.tp + self.fn > 0 else 0\n\n def f1(self):\n re = self.recall()\n pr = self.precision()\n return 2 * pr * re / (pr + re) if pr + re > 0 else 0\n\n\ndef binary_classification_metrics(gt_aabbs, pred_aabbs):\n iou_thres = 0.7\n\n ious = 1 - compute_dist_mat_2(gt_aabbs, pred_aabbs)\n match_counter = (ious > iou_thres).astype(np.int)\n gt_counter = np.sum(match_counter, axis=1)\n pred_counter = np.sum(match_counter, axis=0)\n\n tp = np.count_nonzero(pred_counter == 1)\n fp = np.count_nonzero(pred_counter == 0)\n fn = np.count_nonzero(gt_counter == 0)\n\n return BinaryClassificationMetrics(tp, fp, fn)\n\n\ndef infer_one(net, img, thres=0.5, max_aabbs=None):\n with torch.no_grad():\n y = net(img, apply_softmax=True)\n pred_map = y.to('cpu').numpy()[0]\n scale_up = 1 / compute_scale_down(net.input_size, net.output_size)\n aabbs = decode(pred_map, comp_fg=fg_by_cc(thres, max_aabbs), f=scale_up)\n h, w = img.to('cpu').numpy()[0][0].shape\n aabbs = [aabb.clip(AABB(0, w - 1, 0, h - 1)) for aabb in aabbs]\n clustered_aabbs = cluster_aabbs(aabbs)\n return clustered_aabbs \n\ndef evaluate(net, loader, thres=0.5, max_aabbs=None):\n batch_imgs = []\n batch_aabbs = []\n loss = 0\n\n for i in range(len(loader)):\n # get batch\n loader_item = loader[i]\n with torch.no_grad():\n y = net(loader_item.batch_imgs, apply_softmax=True)\n y_np = y.to('cpu').numpy()\n if loader_item.batch_gt_maps is not None:\n loss += compute_loss(y, loader_item.batch_gt_maps).to('cpu').numpy()\n\n scale_up = 1 / compute_scale_down(WordDetectorNet.input_size, WordDetectorNet.output_size)\n metrics = BinaryClassificationMetrics(0, 0, 0)\n # import pdb; pdb.set_trace()\n for i in range(len(y_np)):\n img_np = loader_item.batch_imgs[i, 0].to('cpu').numpy()\n pred_map = y_np[i]\n\n aabbs = decode(pred_map, comp_fg=fg_by_cc(thres, max_aabbs), f=scale_up)\n h, w = img_np.shape\n aabbs = [aabb.clip(AABB(0, w - 1, 0, h - 1)) for aabb in aabbs] # bounding box must be inside img\n clustered_aabbs = cluster_aabbs(aabbs)\n\n if loader_item.batch_aabbs is not None:\n curr_metrics = binary_classification_metrics(loader_item.batch_aabbs[i], clustered_aabbs)\n metrics = metrics.accumulate(curr_metrics)\n\n batch_imgs.append(img_np)\n batch_aabbs.append(clustered_aabbs)\n\n return EvaluateRes(batch_imgs, batch_aabbs, loss / len(loader), metrics)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--batch_size', type=int, default=10)\n parser.add_argument('--data_dir', type=Path, required=True)\n args = parser.parse_args()\n\n net = WordDetectorNet()\n net.load_state_dict(torch.load('../model/weights'))\n net.eval()\n net.to('cuda')\n\n dataset = DatasetHIRO(args.data_dir, net.input_size, net.output_size, caching=False)\n dataset_eval = DatasetHIROSplit(dataset, 0, 10)\n loader = DataLoaderIAM(dataset_eval, args.batch_size, net.input_size, net.output_size)\n\n res = evaluate(net, loader, max_aabbs=1000)\n print(f'Loss: {res.loss}')\n print(f'Recall: {res.metrics.recall()}')\n print(f'Precision: {res.metrics.precision()}')\n print(f'F1 score: {res.metrics.f1()}')\n\n for img, aabbs in zip(res.batch_imgs, res.batch_aabbs):\n visualize_and_plot(img, aabbs)\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.sum", "numpy.count_nonzero", "torch.no_grad", "torch.load" ] ]
yotam/numpy
[ "d61ee81e0220318ebe9404f0381c7fdfe189f647" ]
[ "numpy/lib/tests/test_io.py" ]
[ "from __future__ import division, absolute_import, print_function\n\nimport sys\nimport gzip\nimport os\nimport threading\nfrom tempfile import mkstemp, NamedTemporaryFile\nimport time\nimport warnings\nimport gc\nfrom io import BytesIO\nfrom datetime import datetime\n\nimport numpy as np\nimport numpy.ma as ma\nfrom numpy.lib._iotools import (ConverterError, ConverterLockError,\n ConversionWarning)\nfrom numpy.compat import asbytes, asbytes_nested, bytes, asstr\nfrom nose import SkipTest\nfrom numpy.ma.testutils import (\n TestCase, assert_equal, assert_array_equal,\n assert_raises, assert_raises_regex, run_module_suite\n)\nfrom numpy.testing import assert_warns, assert_, build_err_msg\nfrom numpy.testing.utils import tempdir\n\n\nclass TextIO(BytesIO):\n \"\"\"Helper IO class.\n\n Writes encode strings to bytes if needed, reads return bytes.\n This makes it easier to emulate files opened in binary mode\n without needing to explicitly convert strings to bytes in\n setting up the test data.\n\n \"\"\"\n def __init__(self, s=\"\"):\n BytesIO.__init__(self, asbytes(s))\n\n def write(self, s):\n BytesIO.write(self, asbytes(s))\n\n def writelines(self, lines):\n BytesIO.writelines(self, [asbytes(s) for s in lines])\n\n\nMAJVER, MINVER = sys.version_info[:2]\nIS_64BIT = sys.maxsize > 2**32\n\n\ndef strptime(s, fmt=None):\n \"\"\"This function is available in the datetime module only\n from Python >= 2.5.\n\n \"\"\"\n if sys.version_info[0] >= 3:\n return datetime(*time.strptime(s.decode('latin1'), fmt)[:3])\n else:\n return datetime(*time.strptime(s, fmt)[:3])\n\n\nclass RoundtripTest(object):\n def roundtrip(self, save_func, *args, **kwargs):\n \"\"\"\n save_func : callable\n Function used to save arrays to file.\n file_on_disk : bool\n If true, store the file on disk, instead of in a\n string buffer.\n save_kwds : dict\n Parameters passed to `save_func`.\n load_kwds : dict\n Parameters passed to `numpy.load`.\n args : tuple of arrays\n Arrays stored to file.\n\n \"\"\"\n save_kwds = kwargs.get('save_kwds', {})\n load_kwds = kwargs.get('load_kwds', {})\n file_on_disk = kwargs.get('file_on_disk', False)\n\n if file_on_disk:\n target_file = NamedTemporaryFile(delete=False)\n load_file = target_file.name\n else:\n target_file = BytesIO()\n load_file = target_file\n\n try:\n arr = args\n\n save_func(target_file, *arr, **save_kwds)\n target_file.flush()\n target_file.seek(0)\n\n if sys.platform == 'win32' and not isinstance(target_file, BytesIO):\n target_file.close()\n\n arr_reloaded = np.load(load_file, **load_kwds)\n\n self.arr = arr\n self.arr_reloaded = arr_reloaded\n finally:\n if not isinstance(target_file, BytesIO):\n target_file.close()\n # holds an open file descriptor so it can't be deleted on win\n if not isinstance(arr_reloaded, np.lib.npyio.NpzFile):\n os.remove(target_file.name)\n\n def check_roundtrips(self, a):\n self.roundtrip(a)\n self.roundtrip(a, file_on_disk=True)\n self.roundtrip(np.asfortranarray(a))\n self.roundtrip(np.asfortranarray(a), file_on_disk=True)\n if a.shape[0] > 1:\n # neither C nor Fortran contiguous for 2D arrays or more\n self.roundtrip(np.asfortranarray(a)[1:])\n self.roundtrip(np.asfortranarray(a)[1:], file_on_disk=True)\n\n def test_array(self):\n a = np.array([], float)\n self.check_roundtrips(a)\n\n a = np.array([[1, 2], [3, 4]], float)\n self.check_roundtrips(a)\n\n a = np.array([[1, 2], [3, 4]], int)\n self.check_roundtrips(a)\n\n a = np.array([[1 + 5j, 2 + 6j], [3 + 7j, 4 + 8j]], dtype=np.csingle)\n self.check_roundtrips(a)\n\n a = np.array([[1 + 5j, 2 + 6j], [3 + 7j, 4 + 8j]], dtype=np.cdouble)\n self.check_roundtrips(a)\n\n def test_array_object(self):\n if sys.version_info[:2] >= (2, 7):\n a = np.array([], object)\n self.check_roundtrips(a)\n\n a = np.array([[1, 2], [3, 4]], object)\n self.check_roundtrips(a)\n # Fails with UnpicklingError: could not find MARK on Python 2.6\n\n def test_1D(self):\n a = np.array([1, 2, 3, 4], int)\n self.roundtrip(a)\n\n @np.testing.dec.knownfailureif(sys.platform == 'win32', \"Fail on Win32\")\n def test_mmap(self):\n a = np.array([[1, 2.5], [4, 7.3]])\n self.roundtrip(a, file_on_disk=True, load_kwds={'mmap_mode': 'r'})\n\n a = np.asfortranarray([[1, 2.5], [4, 7.3]])\n self.roundtrip(a, file_on_disk=True, load_kwds={'mmap_mode': 'r'})\n\n def test_record(self):\n a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])\n self.check_roundtrips(a)\n\n def test_format_2_0(self):\n dt = [((\"%d\" % i) * 100, float) for i in range(500)]\n a = np.ones(1000, dtype=dt)\n with warnings.catch_warnings(record=True):\n warnings.filterwarnings('always', '', UserWarning)\n self.check_roundtrips(a)\n\n\nclass TestSaveLoad(RoundtripTest, TestCase):\n def roundtrip(self, *args, **kwargs):\n RoundtripTest.roundtrip(self, np.save, *args, **kwargs)\n assert_equal(self.arr[0], self.arr_reloaded)\n assert_equal(self.arr[0].dtype, self.arr_reloaded.dtype)\n assert_equal(self.arr[0].flags.fnc, self.arr_reloaded.flags.fnc)\n\n\nclass TestSavezLoad(RoundtripTest, TestCase):\n def roundtrip(self, *args, **kwargs):\n RoundtripTest.roundtrip(self, np.savez, *args, **kwargs)\n try:\n for n, arr in enumerate(self.arr):\n reloaded = self.arr_reloaded['arr_%d' % n]\n assert_equal(arr, reloaded)\n assert_equal(arr.dtype, reloaded.dtype)\n assert_equal(arr.flags.fnc, reloaded.flags.fnc)\n finally:\n # delete tempfile, must be done here on windows\n if self.arr_reloaded.fid:\n self.arr_reloaded.fid.close()\n os.remove(self.arr_reloaded.fid.name)\n\n @np.testing.dec.skipif(not IS_64BIT, \"Works only with 64bit systems\")\n @np.testing.dec.slow\n def test_big_arrays(self):\n L = (1 << 31) + 100000\n a = np.empty(L, dtype=np.uint8)\n with tempdir(prefix=\"numpy_test_big_arrays_\") as tmpdir:\n tmp = os.path.join(tmpdir, \"file.npz\")\n np.savez(tmp, a=a)\n del a\n npfile = np.load(tmp)\n a = npfile['a']\n npfile.close()\n\n def test_multiple_arrays(self):\n a = np.array([[1, 2], [3, 4]], float)\n b = np.array([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex)\n self.roundtrip(a, b)\n\n def test_named_arrays(self):\n a = np.array([[1, 2], [3, 4]], float)\n b = np.array([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex)\n c = BytesIO()\n np.savez(c, file_a=a, file_b=b)\n c.seek(0)\n l = np.load(c)\n assert_equal(a, l['file_a'])\n assert_equal(b, l['file_b'])\n\n def test_savez_filename_clashes(self):\n # Test that issue #852 is fixed\n # and savez functions in multithreaded environment\n\n def writer(error_list):\n fd, tmp = mkstemp(suffix='.npz')\n os.close(fd)\n try:\n arr = np.random.randn(500, 500)\n try:\n np.savez(tmp, arr=arr)\n except OSError as err:\n error_list.append(err)\n finally:\n os.remove(tmp)\n\n errors = []\n threads = [threading.Thread(target=writer, args=(errors,))\n for j in range(3)]\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n\n if errors:\n raise AssertionError(errors)\n\n def test_not_closing_opened_fid(self):\n # Test that issue #2178 is fixed:\n # verify could seek on 'loaded' file\n\n fd, tmp = mkstemp(suffix='.npz')\n os.close(fd)\n try:\n fp = open(tmp, 'wb')\n np.savez(fp, data='LOVELY LOAD')\n fp.close()\n\n fp = open(tmp, 'rb', 10000)\n fp.seek(0)\n assert_(not fp.closed)\n _ = np.load(fp)['data']\n assert_(not fp.closed)\n # must not get closed by .load(opened fp)\n fp.seek(0)\n assert_(not fp.closed)\n\n finally:\n fp.close()\n os.remove(tmp)\n\n def test_closing_fid(self):\n # Test that issue #1517 (too many opened files) remains closed\n # It might be a \"weak\" test since failed to get triggered on\n # e.g. Debian sid of 2012 Jul 05 but was reported to\n # trigger the failure on Ubuntu 10.04:\n # http://projects.scipy.org/numpy/ticket/1517#comment:2\n fd, tmp = mkstemp(suffix='.npz')\n os.close(fd)\n\n try:\n fp = open(tmp, 'wb')\n np.savez(fp, data='LOVELY LOAD')\n fp.close()\n # We need to check if the garbage collector can properly close\n # numpy npz file returned by np.load when their reference count\n # goes to zero. Python 3 running in debug mode raises a\n # ResourceWarning when file closing is left to the garbage\n # collector, so we catch the warnings. Because ResourceWarning\n # is unknown in Python < 3.x, we take the easy way out and\n # catch all warnings.\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n for i in range(1, 1025):\n try:\n np.load(tmp)[\"data\"]\n except Exception as e:\n msg = \"Failed to load data from a file: %s\" % e\n raise AssertionError(msg)\n finally:\n os.remove(tmp)\n\n def test_closing_zipfile_after_load(self):\n # Check that zipfile owns file and can close it.\n # This needs to pass a file name to load for the\n # test.\n with tempdir(prefix=\"numpy_test_closing_zipfile_after_load_\") as tmpdir:\n fd, tmp = mkstemp(suffix='.npz', dir=tmpdir)\n os.close(fd)\n np.savez(tmp, lab='place holder')\n data = np.load(tmp)\n fp = data.zip.fp\n data.close()\n assert_(fp.closed)\n\n\nclass TestSaveTxt(TestCase):\n def test_array(self):\n a = np.array([[1, 2], [3, 4]], float)\n fmt = \"%.18e\"\n c = BytesIO()\n np.savetxt(c, a, fmt=fmt)\n c.seek(0)\n assert_equal(c.readlines(),\n [asbytes((fmt + ' ' + fmt + '\\n') % (1, 2)),\n asbytes((fmt + ' ' + fmt + '\\n') % (3, 4))])\n\n a = np.array([[1, 2], [3, 4]], int)\n c = BytesIO()\n np.savetxt(c, a, fmt='%d')\n c.seek(0)\n assert_equal(c.readlines(), [b'1 2\\n', b'3 4\\n'])\n\n def test_1D(self):\n a = np.array([1, 2, 3, 4], int)\n c = BytesIO()\n np.savetxt(c, a, fmt='%d')\n c.seek(0)\n lines = c.readlines()\n assert_equal(lines, [b'1\\n', b'2\\n', b'3\\n', b'4\\n'])\n\n def test_record(self):\n a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])\n c = BytesIO()\n np.savetxt(c, a, fmt='%d')\n c.seek(0)\n assert_equal(c.readlines(), [b'1 2\\n', b'3 4\\n'])\n\n def test_delimiter(self):\n a = np.array([[1., 2.], [3., 4.]])\n c = BytesIO()\n np.savetxt(c, a, delimiter=',', fmt='%d')\n c.seek(0)\n assert_equal(c.readlines(), [b'1,2\\n', b'3,4\\n'])\n\n def test_format(self):\n a = np.array([(1, 2), (3, 4)])\n c = BytesIO()\n # Sequence of formats\n np.savetxt(c, a, fmt=['%02d', '%3.1f'])\n c.seek(0)\n assert_equal(c.readlines(), [b'01 2.0\\n', b'03 4.0\\n'])\n\n # A single multiformat string\n c = BytesIO()\n np.savetxt(c, a, fmt='%02d : %3.1f')\n c.seek(0)\n lines = c.readlines()\n assert_equal(lines, [b'01 : 2.0\\n', b'03 : 4.0\\n'])\n\n # Specify delimiter, should be overiden\n c = BytesIO()\n np.savetxt(c, a, fmt='%02d : %3.1f', delimiter=',')\n c.seek(0)\n lines = c.readlines()\n assert_equal(lines, [b'01 : 2.0\\n', b'03 : 4.0\\n'])\n\n # Bad fmt, should raise a ValueError\n c = BytesIO()\n assert_raises(ValueError, np.savetxt, c, a, fmt=99)\n\n def test_header_footer(self):\n \"\"\"\n Test the functionality of the header and footer keyword argument.\n \"\"\"\n c = BytesIO()\n a = np.array([(1, 2), (3, 4)], dtype=np.int)\n test_header_footer = 'Test header / footer'\n # Test the header keyword argument\n np.savetxt(c, a, fmt='%1d', header=test_header_footer)\n c.seek(0)\n assert_equal(c.read(),\n asbytes('# ' + test_header_footer + '\\n1 2\\n3 4\\n'))\n # Test the footer keyword argument\n c = BytesIO()\n np.savetxt(c, a, fmt='%1d', footer=test_header_footer)\n c.seek(0)\n assert_equal(c.read(),\n asbytes('1 2\\n3 4\\n# ' + test_header_footer + '\\n'))\n # Test the commentstr keyword argument used on the header\n c = BytesIO()\n commentstr = '% '\n np.savetxt(c, a, fmt='%1d',\n header=test_header_footer, comments=commentstr)\n c.seek(0)\n assert_equal(c.read(),\n asbytes(commentstr + test_header_footer + '\\n' + '1 2\\n3 4\\n'))\n # Test the commentstr keyword argument used on the footer\n c = BytesIO()\n commentstr = '% '\n np.savetxt(c, a, fmt='%1d',\n footer=test_header_footer, comments=commentstr)\n c.seek(0)\n assert_equal(c.read(),\n asbytes('1 2\\n3 4\\n' + commentstr + test_header_footer + '\\n'))\n\n def test_file_roundtrip(self):\n f, name = mkstemp()\n os.close(f)\n try:\n a = np.array([(1, 2), (3, 4)])\n np.savetxt(name, a)\n b = np.loadtxt(name)\n assert_array_equal(a, b)\n finally:\n os.unlink(name)\n\n def test_complex_arrays(self):\n ncols = 2\n nrows = 2\n a = np.zeros((ncols, nrows), dtype=np.complex128)\n re = np.pi\n im = np.e\n a[:] = re + 1.0j * im\n\n # One format only\n c = BytesIO()\n np.savetxt(c, a, fmt=' %+.3e')\n c.seek(0)\n lines = c.readlines()\n assert_equal(\n lines,\n [b' ( +3.142e+00+ +2.718e+00j) ( +3.142e+00+ +2.718e+00j)\\n',\n b' ( +3.142e+00+ +2.718e+00j) ( +3.142e+00+ +2.718e+00j)\\n'])\n\n # One format for each real and imaginary part\n c = BytesIO()\n np.savetxt(c, a, fmt=' %+.3e' * 2 * ncols)\n c.seek(0)\n lines = c.readlines()\n assert_equal(\n lines,\n [b' +3.142e+00 +2.718e+00 +3.142e+00 +2.718e+00\\n',\n b' +3.142e+00 +2.718e+00 +3.142e+00 +2.718e+00\\n'])\n\n # One format for each complex number\n c = BytesIO()\n np.savetxt(c, a, fmt=['(%.3e%+.3ej)'] * ncols)\n c.seek(0)\n lines = c.readlines()\n assert_equal(\n lines,\n [b'(3.142e+00+2.718e+00j) (3.142e+00+2.718e+00j)\\n',\n b'(3.142e+00+2.718e+00j) (3.142e+00+2.718e+00j)\\n'])\n\n def test_custom_writer(self):\n\n class CustomWriter(list):\n def write(self, text):\n self.extend(text.split(b'\\n'))\n\n w = CustomWriter()\n a = np.array([(1, 2), (3, 4)])\n np.savetxt(w, a)\n b = np.loadtxt(w)\n assert_array_equal(a, b)\n\n\nclass TestLoadTxt(TestCase):\n def test_record(self):\n c = TextIO()\n c.write('1 2\\n3 4')\n c.seek(0)\n x = np.loadtxt(c, dtype=[('x', np.int32), ('y', np.int32)])\n a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])\n assert_array_equal(x, a)\n\n d = TextIO()\n d.write('M 64.0 75.0\\nF 25.0 60.0')\n d.seek(0)\n mydescriptor = {'names': ('gender', 'age', 'weight'),\n 'formats': ('S1', 'i4', 'f4')}\n b = np.array([('M', 64.0, 75.0),\n ('F', 25.0, 60.0)], dtype=mydescriptor)\n y = np.loadtxt(d, dtype=mydescriptor)\n assert_array_equal(y, b)\n\n def test_array(self):\n c = TextIO()\n c.write('1 2\\n3 4')\n\n c.seek(0)\n x = np.loadtxt(c, dtype=np.int)\n a = np.array([[1, 2], [3, 4]], int)\n assert_array_equal(x, a)\n\n c.seek(0)\n x = np.loadtxt(c, dtype=float)\n a = np.array([[1, 2], [3, 4]], float)\n assert_array_equal(x, a)\n\n def test_1D(self):\n c = TextIO()\n c.write('1\\n2\\n3\\n4\\n')\n c.seek(0)\n x = np.loadtxt(c, dtype=int)\n a = np.array([1, 2, 3, 4], int)\n assert_array_equal(x, a)\n\n c = TextIO()\n c.write('1,2,3,4\\n')\n c.seek(0)\n x = np.loadtxt(c, dtype=int, delimiter=',')\n a = np.array([1, 2, 3, 4], int)\n assert_array_equal(x, a)\n\n def test_missing(self):\n c = TextIO()\n c.write('1,2,3,,5\\n')\n c.seek(0)\n x = np.loadtxt(c, dtype=int, delimiter=',',\n converters={3: lambda s: int(s or - 999)})\n a = np.array([1, 2, 3, -999, 5], int)\n assert_array_equal(x, a)\n\n def test_converters_with_usecols(self):\n c = TextIO()\n c.write('1,2,3,,5\\n6,7,8,9,10\\n')\n c.seek(0)\n x = np.loadtxt(c, dtype=int, delimiter=',',\n converters={3: lambda s: int(s or - 999)},\n usecols=(1, 3,))\n a = np.array([[2, -999], [7, 9]], int)\n assert_array_equal(x, a)\n\n def test_comments(self):\n c = TextIO()\n c.write('# comment\\n1,2,3,5\\n')\n c.seek(0)\n x = np.loadtxt(c, dtype=int, delimiter=',',\n comments='#')\n a = np.array([1, 2, 3, 5], int)\n assert_array_equal(x, a)\n\n def test_skiprows(self):\n c = TextIO()\n c.write('comment\\n1,2,3,5\\n')\n c.seek(0)\n x = np.loadtxt(c, dtype=int, delimiter=',',\n skiprows=1)\n a = np.array([1, 2, 3, 5], int)\n assert_array_equal(x, a)\n\n c = TextIO()\n c.write('# comment\\n1,2,3,5\\n')\n c.seek(0)\n x = np.loadtxt(c, dtype=int, delimiter=',',\n skiprows=1)\n a = np.array([1, 2, 3, 5], int)\n assert_array_equal(x, a)\n\n def test_usecols(self):\n a = np.array([[1, 2], [3, 4]], float)\n c = BytesIO()\n np.savetxt(c, a)\n c.seek(0)\n x = np.loadtxt(c, dtype=float, usecols=(1,))\n assert_array_equal(x, a[:, 1])\n\n a = np.array([[1, 2, 3], [3, 4, 5]], float)\n c = BytesIO()\n np.savetxt(c, a)\n c.seek(0)\n x = np.loadtxt(c, dtype=float, usecols=(1, 2))\n assert_array_equal(x, a[:, 1:])\n\n # Testing with arrays instead of tuples.\n c.seek(0)\n x = np.loadtxt(c, dtype=float, usecols=np.array([1, 2]))\n assert_array_equal(x, a[:, 1:])\n\n # Checking with dtypes defined converters.\n data = '''JOE 70.1 25.3\n BOB 60.5 27.9\n '''\n c = TextIO(data)\n names = ['stid', 'temp']\n dtypes = ['S4', 'f8']\n arr = np.loadtxt(c, usecols=(0, 2), dtype=list(zip(names, dtypes)))\n assert_equal(arr['stid'], [b\"JOE\", b\"BOB\"])\n assert_equal(arr['temp'], [25.3, 27.9])\n\n def test_fancy_dtype(self):\n c = TextIO()\n c.write('1,2,3.0\\n4,5,6.0\\n')\n c.seek(0)\n dt = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])\n x = np.loadtxt(c, dtype=dt, delimiter=',')\n a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dt)\n assert_array_equal(x, a)\n\n def test_shaped_dtype(self):\n c = TextIO(\"aaaa 1.0 8.0 1 2 3 4 5 6\")\n dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),\n ('block', int, (2, 3))])\n x = np.loadtxt(c, dtype=dt)\n a = np.array([('aaaa', 1.0, 8.0, [[1, 2, 3], [4, 5, 6]])],\n dtype=dt)\n assert_array_equal(x, a)\n\n def test_3d_shaped_dtype(self):\n c = TextIO(\"aaaa 1.0 8.0 1 2 3 4 5 6 7 8 9 10 11 12\")\n dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),\n ('block', int, (2, 2, 3))])\n x = np.loadtxt(c, dtype=dt)\n a = np.array([('aaaa', 1.0, 8.0,\n [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])],\n dtype=dt)\n assert_array_equal(x, a)\n\n def test_empty_file(self):\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\",\n message=\"loadtxt: Empty input file:\")\n c = TextIO()\n x = np.loadtxt(c)\n assert_equal(x.shape, (0,))\n x = np.loadtxt(c, dtype=np.int64)\n assert_equal(x.shape, (0,))\n assert_(x.dtype == np.int64)\n\n def test_unused_converter(self):\n c = TextIO()\n c.writelines(['1 21\\n', '3 42\\n'])\n c.seek(0)\n data = np.loadtxt(c, usecols=(1,),\n converters={0: lambda s: int(s, 16)})\n assert_array_equal(data, [21, 42])\n\n c.seek(0)\n data = np.loadtxt(c, usecols=(1,),\n converters={1: lambda s: int(s, 16)})\n assert_array_equal(data, [33, 66])\n\n def test_dtype_with_object(self):\n \"Test using an explicit dtype with an object\"\n from datetime import date\n import time\n data = \"\"\" 1; 2001-01-01\n 2; 2002-01-31 \"\"\"\n ndtype = [('idx', int), ('code', np.object)]\n func = lambda s: strptime(s.strip(), \"%Y-%m-%d\")\n converters = {1: func}\n test = np.loadtxt(TextIO(data), delimiter=\";\", dtype=ndtype,\n converters=converters)\n control = np.array(\n [(1, datetime(2001, 1, 1)), (2, datetime(2002, 1, 31))],\n dtype=ndtype)\n assert_equal(test, control)\n\n def test_uint64_type(self):\n tgt = (9223372043271415339, 9223372043271415853)\n c = TextIO()\n c.write(\"%s %s\" % tgt)\n c.seek(0)\n res = np.loadtxt(c, dtype=np.uint64)\n assert_equal(res, tgt)\n\n def test_int64_type(self):\n tgt = (-9223372036854775807, 9223372036854775807)\n c = TextIO()\n c.write(\"%s %s\" % tgt)\n c.seek(0)\n res = np.loadtxt(c, dtype=np.int64)\n assert_equal(res, tgt)\n\n def test_universal_newline(self):\n f, name = mkstemp()\n os.write(f, b'1 21\\r3 42\\r')\n os.close(f)\n\n try:\n data = np.loadtxt(name)\n assert_array_equal(data, [[1, 21], [3, 42]])\n finally:\n os.unlink(name)\n\n def test_empty_field_after_tab(self):\n c = TextIO()\n c.write('1 \\t2 \\t3\\tstart \\n4\\t5\\t6\\t \\n7\\t8\\t9.5\\t')\n c.seek(0)\n dt = {'names': ('x', 'y', 'z', 'comment'),\n 'formats': ('<i4', '<i4', '<f4', '|S8')}\n x = np.loadtxt(c, dtype=dt, delimiter='\\t')\n a = np.array([b'start ', b' ', b''])\n assert_array_equal(x['comment'], a)\n\n def test_structure_unpack(self):\n txt = TextIO(\"M 21 72\\nF 35 58\")\n dt = {'names': ('a', 'b', 'c'), 'formats': ('|S1', '<i4', '<f4')}\n a, b, c = np.loadtxt(txt, dtype=dt, unpack=True)\n assert_(a.dtype.str == '|S1')\n assert_(b.dtype.str == '<i4')\n assert_(c.dtype.str == '<f4')\n assert_array_equal(a, np.array([b'M', b'F']))\n assert_array_equal(b, np.array([21, 35]))\n assert_array_equal(c, np.array([72., 58.]))\n\n def test_ndmin_keyword(self):\n c = TextIO()\n c.write('1,2,3\\n4,5,6')\n c.seek(0)\n assert_raises(ValueError, np.loadtxt, c, ndmin=3)\n c.seek(0)\n assert_raises(ValueError, np.loadtxt, c, ndmin=1.5)\n c.seek(0)\n x = np.loadtxt(c, dtype=int, delimiter=',', ndmin=1)\n a = np.array([[1, 2, 3], [4, 5, 6]])\n assert_array_equal(x, a)\n\n d = TextIO()\n d.write('0,1,2')\n d.seek(0)\n x = np.loadtxt(d, dtype=int, delimiter=',', ndmin=2)\n assert_(x.shape == (1, 3))\n d.seek(0)\n x = np.loadtxt(d, dtype=int, delimiter=',', ndmin=1)\n assert_(x.shape == (3,))\n d.seek(0)\n x = np.loadtxt(d, dtype=int, delimiter=',', ndmin=0)\n assert_(x.shape == (3,))\n\n e = TextIO()\n e.write('0\\n1\\n2')\n e.seek(0)\n x = np.loadtxt(e, dtype=int, delimiter=',', ndmin=2)\n assert_(x.shape == (3, 1))\n e.seek(0)\n x = np.loadtxt(e, dtype=int, delimiter=',', ndmin=1)\n assert_(x.shape == (3,))\n e.seek(0)\n x = np.loadtxt(e, dtype=int, delimiter=',', ndmin=0)\n assert_(x.shape == (3,))\n\n # Test ndmin kw with empty file.\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\",\n message=\"loadtxt: Empty input file:\")\n f = TextIO()\n assert_(np.loadtxt(f, ndmin=2).shape == (0, 1,))\n assert_(np.loadtxt(f, ndmin=1).shape == (0,))\n\n def test_generator_source(self):\n def count():\n for i in range(10):\n yield \"%d\" % i\n\n res = np.loadtxt(count())\n assert_array_equal(res, np.arange(10))\n\n def test_bad_line(self):\n c = TextIO()\n c.write('1 2 3\\n4 5 6\\n2 3')\n c.seek(0)\n\n # Check for exception and that exception contains line number\n assert_raises_regex(ValueError, \"3\", np.loadtxt, c)\n\n\nclass Testfromregex(TestCase):\n # np.fromregex expects files opened in binary mode.\n def test_record(self):\n c = TextIO()\n c.write('1.312 foo\\n1.534 bar\\n4.444 qux')\n c.seek(0)\n\n dt = [('num', np.float64), ('val', 'S3')]\n x = np.fromregex(c, r\"([0-9.]+)\\s+(...)\", dt)\n a = np.array([(1.312, 'foo'), (1.534, 'bar'), (4.444, 'qux')],\n dtype=dt)\n assert_array_equal(x, a)\n\n def test_record_2(self):\n c = TextIO()\n c.write('1312 foo\\n1534 bar\\n4444 qux')\n c.seek(0)\n\n dt = [('num', np.int32), ('val', 'S3')]\n x = np.fromregex(c, r\"(\\d+)\\s+(...)\", dt)\n a = np.array([(1312, 'foo'), (1534, 'bar'), (4444, 'qux')],\n dtype=dt)\n assert_array_equal(x, a)\n\n def test_record_3(self):\n c = TextIO()\n c.write('1312 foo\\n1534 bar\\n4444 qux')\n c.seek(0)\n\n dt = [('num', np.float64)]\n x = np.fromregex(c, r\"(\\d+)\\s+...\", dt)\n a = np.array([(1312,), (1534,), (4444,)], dtype=dt)\n assert_array_equal(x, a)\n\n\n#####--------------------------------------------------------------------------\n\n\nclass TestFromTxt(TestCase):\n #\n def test_record(self):\n \"Test w/ explicit dtype\"\n data = TextIO('1 2\\n3 4')\n# data.seek(0)\n test = np.ndfromtxt(data, dtype=[('x', np.int32), ('y', np.int32)])\n control = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])\n assert_equal(test, control)\n #\n data = TextIO('M 64.0 75.0\\nF 25.0 60.0')\n# data.seek(0)\n descriptor = {'names': ('gender', 'age', 'weight'),\n 'formats': ('S1', 'i4', 'f4')}\n control = np.array([('M', 64.0, 75.0), ('F', 25.0, 60.0)],\n dtype=descriptor)\n test = np.ndfromtxt(data, dtype=descriptor)\n assert_equal(test, control)\n\n def test_array(self):\n \"Test outputing a standard ndarray\"\n data = TextIO('1 2\\n3 4')\n control = np.array([[1, 2], [3, 4]], dtype=int)\n test = np.ndfromtxt(data, dtype=int)\n assert_array_equal(test, control)\n #\n data.seek(0)\n control = np.array([[1, 2], [3, 4]], dtype=float)\n test = np.loadtxt(data, dtype=float)\n assert_array_equal(test, control)\n\n def test_1D(self):\n \"Test squeezing to 1D\"\n control = np.array([1, 2, 3, 4], int)\n #\n data = TextIO('1\\n2\\n3\\n4\\n')\n test = np.ndfromtxt(data, dtype=int)\n assert_array_equal(test, control)\n #\n data = TextIO('1,2,3,4\\n')\n test = np.ndfromtxt(data, dtype=int, delimiter=',')\n assert_array_equal(test, control)\n\n def test_comments(self):\n \"Test the stripping of comments\"\n control = np.array([1, 2, 3, 5], int)\n # Comment on its own line\n data = TextIO('# comment\\n1,2,3,5\\n')\n test = np.ndfromtxt(data, dtype=int, delimiter=',', comments='#')\n assert_equal(test, control)\n # Comment at the end of a line\n data = TextIO('1,2,3,5# comment\\n')\n test = np.ndfromtxt(data, dtype=int, delimiter=',', comments='#')\n assert_equal(test, control)\n\n def test_skiprows(self):\n \"Test row skipping\"\n control = np.array([1, 2, 3, 5], int)\n kwargs = dict(dtype=int, delimiter=',')\n #\n data = TextIO('comment\\n1,2,3,5\\n')\n test = np.ndfromtxt(data, skip_header=1, **kwargs)\n assert_equal(test, control)\n #\n data = TextIO('# comment\\n1,2,3,5\\n')\n test = np.loadtxt(data, skiprows=1, **kwargs)\n assert_equal(test, control)\n\n def test_skip_footer(self):\n data = [\"# %i\" % i for i in range(1, 6)]\n data.append(\"A, B, C\")\n data.extend([\"%i,%3.1f,%03s\" % (i, i, i) for i in range(51)])\n data[-1] = \"99,99\"\n kwargs = dict(delimiter=\",\", names=True, skip_header=5, skip_footer=10)\n test = np.genfromtxt(TextIO(\"\\n\".join(data)), **kwargs)\n ctrl = np.array([(\"%f\" % i, \"%f\" % i, \"%f\" % i) for i in range(41)],\n dtype=[(_, float) for _ in \"ABC\"])\n assert_equal(test, ctrl)\n\n def test_skip_footer_with_invalid(self):\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\")\n basestr = '1 1\\n2 2\\n3 3\\n4 4\\n5 \\n6 \\n7 \\n'\n # Footer too small to get rid of all invalid values\n assert_raises(ValueError, np.genfromtxt,\n TextIO(basestr), skip_footer=1)\n # except ValueError:\n # pass\n a = np.genfromtxt(\n TextIO(basestr), skip_footer=1, invalid_raise=False)\n assert_equal(a, np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]]))\n #\n a = np.genfromtxt(TextIO(basestr), skip_footer=3)\n assert_equal(a, np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]]))\n #\n basestr = '1 1\\n2 \\n3 3\\n4 4\\n5 \\n6 6\\n7 7\\n'\n a = np.genfromtxt(\n TextIO(basestr), skip_footer=1, invalid_raise=False)\n assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.], [6., 6.]]))\n a = np.genfromtxt(\n TextIO(basestr), skip_footer=3, invalid_raise=False)\n assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.]]))\n\n def test_header(self):\n \"Test retrieving a header\"\n data = TextIO('gender age weight\\nM 64.0 75.0\\nF 25.0 60.0')\n test = np.ndfromtxt(data, dtype=None, names=True)\n control = {'gender': np.array([b'M', b'F']),\n 'age': np.array([64.0, 25.0]),\n 'weight': np.array([75.0, 60.0])}\n assert_equal(test['gender'], control['gender'])\n assert_equal(test['age'], control['age'])\n assert_equal(test['weight'], control['weight'])\n\n def test_auto_dtype(self):\n \"Test the automatic definition of the output dtype\"\n data = TextIO('A 64 75.0 3+4j True\\nBCD 25 60.0 5+6j False')\n test = np.ndfromtxt(data, dtype=None)\n control = [np.array([b'A', b'BCD']),\n np.array([64, 25]),\n np.array([75.0, 60.0]),\n np.array([3 + 4j, 5 + 6j]),\n np.array([True, False]), ]\n assert_equal(test.dtype.names, ['f0', 'f1', 'f2', 'f3', 'f4'])\n for (i, ctrl) in enumerate(control):\n assert_equal(test['f%i' % i], ctrl)\n\n def test_auto_dtype_uniform(self):\n \"Tests whether the output dtype can be uniformized\"\n data = TextIO('1 2 3 4\\n5 6 7 8\\n')\n test = np.ndfromtxt(data, dtype=None)\n control = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])\n assert_equal(test, control)\n\n def test_fancy_dtype(self):\n \"Check that a nested dtype isn't MIA\"\n data = TextIO('1,2,3.0\\n4,5,6.0\\n')\n fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])\n test = np.ndfromtxt(data, dtype=fancydtype, delimiter=',')\n control = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dtype=fancydtype)\n assert_equal(test, control)\n\n def test_names_overwrite(self):\n \"Test overwriting the names of the dtype\"\n descriptor = {'names': ('g', 'a', 'w'),\n 'formats': ('S1', 'i4', 'f4')}\n data = TextIO(b'M 64.0 75.0\\nF 25.0 60.0')\n names = ('gender', 'age', 'weight')\n test = np.ndfromtxt(data, dtype=descriptor, names=names)\n descriptor['names'] = names\n control = np.array([('M', 64.0, 75.0),\n ('F', 25.0, 60.0)], dtype=descriptor)\n assert_equal(test, control)\n\n def test_commented_header(self):\n \"Check that names can be retrieved even if the line is commented out.\"\n data = TextIO(\"\"\"\n#gender age weight\nM 21 72.100000\nF 35 58.330000\nM 33 21.99\n \"\"\")\n # The # is part of the first name and should be deleted automatically.\n test = np.genfromtxt(data, names=True, dtype=None)\n ctrl = np.array([('M', 21, 72.1), ('F', 35, 58.33), ('M', 33, 21.99)],\n dtype=[('gender', '|S1'), ('age', int), ('weight', float)])\n assert_equal(test, ctrl)\n # Ditto, but we should get rid of the first element\n data = TextIO(b\"\"\"\n# gender age weight\nM 21 72.100000\nF 35 58.330000\nM 33 21.99\n \"\"\")\n test = np.genfromtxt(data, names=True, dtype=None)\n assert_equal(test, ctrl)\n\n def test_autonames_and_usecols(self):\n \"Tests names and usecols\"\n data = TextIO('A B C D\\n aaaa 121 45 9.1')\n test = np.ndfromtxt(data, usecols=('A', 'C', 'D'),\n names=True, dtype=None)\n control = np.array(('aaaa', 45, 9.1),\n dtype=[('A', '|S4'), ('C', int), ('D', float)])\n assert_equal(test, control)\n\n def test_converters_with_usecols(self):\n \"Test the combination user-defined converters and usecol\"\n data = TextIO('1,2,3,,5\\n6,7,8,9,10\\n')\n test = np.ndfromtxt(data, dtype=int, delimiter=',',\n converters={3: lambda s: int(s or - 999)},\n usecols=(1, 3,))\n control = np.array([[2, -999], [7, 9]], int)\n assert_equal(test, control)\n\n def test_converters_with_usecols_and_names(self):\n \"Tests names and usecols\"\n data = TextIO('A B C D\\n aaaa 121 45 9.1')\n test = np.ndfromtxt(data, usecols=('A', 'C', 'D'), names=True,\n dtype=None, converters={'C': lambda s: 2 * int(s)})\n control = np.array(('aaaa', 90, 9.1),\n dtype=[('A', '|S4'), ('C', int), ('D', float)])\n assert_equal(test, control)\n\n def test_converters_cornercases(self):\n \"Test the conversion to datetime.\"\n converter = {\n 'date': lambda s: strptime(s, '%Y-%m-%d %H:%M:%SZ')}\n data = TextIO('2009-02-03 12:00:00Z, 72214.0')\n test = np.ndfromtxt(data, delimiter=',', dtype=None,\n names=['date', 'stid'], converters=converter)\n control = np.array((datetime(2009, 2, 3), 72214.),\n dtype=[('date', np.object_), ('stid', float)])\n assert_equal(test, control)\n\n def test_converters_cornercases2(self):\n \"Test the conversion to datetime64.\"\n converter = {\n 'date': lambda s: np.datetime64(strptime(s, '%Y-%m-%d %H:%M:%SZ'))}\n data = TextIO('2009-02-03 12:00:00Z, 72214.0')\n test = np.ndfromtxt(data, delimiter=',', dtype=None,\n names=['date', 'stid'], converters=converter)\n control = np.array((datetime(2009, 2, 3), 72214.),\n dtype=[('date', 'datetime64[us]'), ('stid', float)])\n assert_equal(test, control)\n\n def test_unused_converter(self):\n \"Test whether unused converters are forgotten\"\n data = TextIO(\"1 21\\n 3 42\\n\")\n test = np.ndfromtxt(data, usecols=(1,),\n converters={0: lambda s: int(s, 16)})\n assert_equal(test, [21, 42])\n #\n data.seek(0)\n test = np.ndfromtxt(data, usecols=(1,),\n converters={1: lambda s: int(s, 16)})\n assert_equal(test, [33, 66])\n\n def test_invalid_converter(self):\n strip_rand = lambda x: float((b'r' in x.lower() and x.split()[-1]) or\n (b'r' not in x.lower() and x.strip() or 0.0))\n strip_per = lambda x: float((b'%' in x.lower() and x.split()[0]) or\n (b'%' not in x.lower() and x.strip() or 0.0))\n s = TextIO(\"D01N01,10/1/2003 ,1 %,R 75,400,600\\r\\n\"\n \"L24U05,12/5/2003, 2 %,1,300, 150.5\\r\\n\"\n \"D02N03,10/10/2004,R 1,,7,145.55\")\n kwargs = dict(\n converters={2: strip_per, 3: strip_rand}, delimiter=\",\",\n dtype=None)\n assert_raises(ConverterError, np.genfromtxt, s, **kwargs)\n\n def test_tricky_converter_bug1666(self):\n \"Test some corner case\"\n s = TextIO('q1,2\\nq3,4')\n cnv = lambda s: float(s[1:])\n test = np.genfromtxt(s, delimiter=',', converters={0: cnv})\n control = np.array([[1., 2.], [3., 4.]])\n assert_equal(test, control)\n\n def test_dtype_with_converters(self):\n dstr = \"2009; 23; 46\"\n test = np.ndfromtxt(TextIO(dstr,),\n delimiter=\";\", dtype=float, converters={0: bytes})\n control = np.array([('2009', 23., 46)],\n dtype=[('f0', '|S4'), ('f1', float), ('f2', float)])\n assert_equal(test, control)\n test = np.ndfromtxt(TextIO(dstr,),\n delimiter=\";\", dtype=float, converters={0: float})\n control = np.array([2009., 23., 46],)\n assert_equal(test, control)\n\n def test_dtype_with_object(self):\n \"Test using an explicit dtype with an object\"\n from datetime import date\n import time\n data = \"\"\" 1; 2001-01-01\n 2; 2002-01-31 \"\"\"\n ndtype = [('idx', int), ('code', np.object)]\n func = lambda s: strptime(s.strip(), \"%Y-%m-%d\")\n converters = {1: func}\n test = np.genfromtxt(TextIO(data), delimiter=\";\", dtype=ndtype,\n converters=converters)\n control = np.array(\n [(1, datetime(2001, 1, 1)), (2, datetime(2002, 1, 31))],\n dtype=ndtype)\n assert_equal(test, control)\n #\n ndtype = [('nest', [('idx', int), ('code', np.object)])]\n try:\n test = np.genfromtxt(TextIO(data), delimiter=\";\",\n dtype=ndtype, converters=converters)\n except NotImplementedError:\n pass\n else:\n errmsg = \"Nested dtype involving objects should be supported.\"\n raise AssertionError(errmsg)\n\n def test_userconverters_with_explicit_dtype(self):\n \"Test user_converters w/ explicit (standard) dtype\"\n data = TextIO('skip,skip,2001-01-01,1.0,skip')\n test = np.genfromtxt(data, delimiter=\",\", names=None, dtype=float,\n usecols=(2, 3), converters={2: bytes})\n control = np.array([('2001-01-01', 1.)],\n dtype=[('', '|S10'), ('', float)])\n assert_equal(test, control)\n\n def test_spacedelimiter(self):\n \"Test space delimiter\"\n data = TextIO(\"1 2 3 4 5\\n6 7 8 9 10\")\n test = np.ndfromtxt(data)\n control = np.array([[1., 2., 3., 4., 5.],\n [6., 7., 8., 9., 10.]])\n assert_equal(test, control)\n\n def test_integer_delimiter(self):\n \"Test using an integer for delimiter\"\n data = \" 1 2 3\\n 4 5 67\\n890123 4\"\n test = np.genfromtxt(TextIO(data), delimiter=3)\n control = np.array([[1, 2, 3], [4, 5, 67], [890, 123, 4]])\n assert_equal(test, control)\n\n def test_missing(self):\n data = TextIO('1,2,3,,5\\n')\n test = np.ndfromtxt(data, dtype=int, delimiter=',',\n converters={3: lambda s: int(s or - 999)})\n control = np.array([1, 2, 3, -999, 5], int)\n assert_equal(test, control)\n\n def test_missing_with_tabs(self):\n \"Test w/ a delimiter tab\"\n txt = \"1\\t2\\t3\\n\\t2\\t\\n1\\t\\t3\"\n test = np.genfromtxt(TextIO(txt), delimiter=\"\\t\",\n usemask=True,)\n ctrl_d = np.array([(1, 2, 3), (np.nan, 2, np.nan), (1, np.nan, 3)],)\n ctrl_m = np.array([(0, 0, 0), (1, 0, 1), (0, 1, 0)], dtype=bool)\n assert_equal(test.data, ctrl_d)\n assert_equal(test.mask, ctrl_m)\n\n def test_usecols(self):\n \"Test the selection of columns\"\n # Select 1 column\n control = np.array([[1, 2], [3, 4]], float)\n data = TextIO()\n np.savetxt(data, control)\n data.seek(0)\n test = np.ndfromtxt(data, dtype=float, usecols=(1,))\n assert_equal(test, control[:, 1])\n #\n control = np.array([[1, 2, 3], [3, 4, 5]], float)\n data = TextIO()\n np.savetxt(data, control)\n data.seek(0)\n test = np.ndfromtxt(data, dtype=float, usecols=(1, 2))\n assert_equal(test, control[:, 1:])\n # Testing with arrays instead of tuples.\n data.seek(0)\n test = np.ndfromtxt(data, dtype=float, usecols=np.array([1, 2]))\n assert_equal(test, control[:, 1:])\n\n def test_usecols_as_css(self):\n \"Test giving usecols with a comma-separated string\"\n data = \"1 2 3\\n4 5 6\"\n test = np.genfromtxt(TextIO(data),\n names=\"a, b, c\", usecols=\"a, c\")\n ctrl = np.array([(1, 3), (4, 6)], dtype=[(_, float) for _ in \"ac\"])\n assert_equal(test, ctrl)\n\n def test_usecols_with_structured_dtype(self):\n \"Test usecols with an explicit structured dtype\"\n data = TextIO(\"JOE 70.1 25.3\\nBOB 60.5 27.9\")\n names = ['stid', 'temp']\n dtypes = ['S4', 'f8']\n test = np.ndfromtxt(\n data, usecols=(0, 2), dtype=list(zip(names, dtypes)))\n assert_equal(test['stid'], [b\"JOE\", b\"BOB\"])\n assert_equal(test['temp'], [25.3, 27.9])\n\n def test_usecols_with_integer(self):\n \"Test usecols with an integer\"\n test = np.genfromtxt(TextIO(b\"1 2 3\\n4 5 6\"), usecols=0)\n assert_equal(test, np.array([1., 4.]))\n\n def test_usecols_with_named_columns(self):\n \"Test usecols with named columns\"\n ctrl = np.array([(1, 3), (4, 6)], dtype=[('a', float), ('c', float)])\n data = \"1 2 3\\n4 5 6\"\n kwargs = dict(names=\"a, b, c\")\n test = np.genfromtxt(TextIO(data), usecols=(0, -1), **kwargs)\n assert_equal(test, ctrl)\n test = np.genfromtxt(TextIO(data),\n usecols=('a', 'c'), **kwargs)\n assert_equal(test, ctrl)\n\n def test_empty_file(self):\n \"Test that an empty file raises the proper warning.\"\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\",\n message=\"genfromtxt: Empty input file:\")\n data = TextIO()\n test = np.genfromtxt(data)\n assert_equal(test, np.array([]))\n\n def test_fancy_dtype_alt(self):\n \"Check that a nested dtype isn't MIA\"\n data = TextIO('1,2,3.0\\n4,5,6.0\\n')\n fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])\n test = np.mafromtxt(data, dtype=fancydtype, delimiter=',')\n control = ma.array([(1, (2, 3.0)), (4, (5, 6.0))], dtype=fancydtype)\n assert_equal(test, control)\n\n def test_shaped_dtype(self):\n c = TextIO(\"aaaa 1.0 8.0 1 2 3 4 5 6\")\n dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),\n ('block', int, (2, 3))])\n x = np.ndfromtxt(c, dtype=dt)\n a = np.array([('aaaa', 1.0, 8.0, [[1, 2, 3], [4, 5, 6]])],\n dtype=dt)\n assert_array_equal(x, a)\n\n def test_withmissing(self):\n data = TextIO('A,B\\n0,1\\n2,N/A')\n kwargs = dict(delimiter=\",\", missing_values=\"N/A\", names=True)\n test = np.mafromtxt(data, dtype=None, **kwargs)\n control = ma.array([(0, 1), (2, -1)],\n mask=[(False, False), (False, True)],\n dtype=[('A', np.int), ('B', np.int)])\n assert_equal(test, control)\n assert_equal(test.mask, control.mask)\n #\n data.seek(0)\n test = np.mafromtxt(data, **kwargs)\n control = ma.array([(0, 1), (2, -1)],\n mask=[(False, False), (False, True)],\n dtype=[('A', np.float), ('B', np.float)])\n assert_equal(test, control)\n assert_equal(test.mask, control.mask)\n\n def test_user_missing_values(self):\n data = \"A, B, C\\n0, 0., 0j\\n1, N/A, 1j\\n-9, 2.2, N/A\\n3, -99, 3j\"\n basekwargs = dict(dtype=None, delimiter=\",\", names=True,)\n mdtype = [('A', int), ('B', float), ('C', complex)]\n #\n test = np.mafromtxt(TextIO(data), missing_values=\"N/A\",\n **basekwargs)\n control = ma.array([(0, 0.0, 0j), (1, -999, 1j),\n (-9, 2.2, -999j), (3, -99, 3j)],\n mask=[(0, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)],\n dtype=mdtype)\n assert_equal(test, control)\n #\n basekwargs['dtype'] = mdtype\n test = np.mafromtxt(TextIO(data),\n missing_values={0: -9, 1: -99, 2: -999j}, **basekwargs)\n control = ma.array([(0, 0.0, 0j), (1, -999, 1j),\n (-9, 2.2, -999j), (3, -99, 3j)],\n mask=[(0, 0, 0), (0, 1, 0), (1, 0, 1), (0, 1, 0)],\n dtype=mdtype)\n assert_equal(test, control)\n #\n test = np.mafromtxt(TextIO(data),\n missing_values={0: -9, 'B': -99, 'C': -999j},\n **basekwargs)\n control = ma.array([(0, 0.0, 0j), (1, -999, 1j),\n (-9, 2.2, -999j), (3, -99, 3j)],\n mask=[(0, 0, 0), (0, 1, 0), (1, 0, 1), (0, 1, 0)],\n dtype=mdtype)\n assert_equal(test, control)\n\n def test_user_filling_values(self):\n \"Test with missing and filling values\"\n ctrl = np.array([(0, 3), (4, -999)], dtype=[('a', int), ('b', int)])\n data = \"N/A, 2, 3\\n4, ,???\"\n kwargs = dict(delimiter=\",\",\n dtype=int,\n names=\"a,b,c\",\n missing_values={0: \"N/A\", 'b': \" \", 2: \"???\"},\n filling_values={0: 0, 'b': 0, 2: -999})\n test = np.genfromtxt(TextIO(data), **kwargs)\n ctrl = np.array([(0, 2, 3), (4, 0, -999)],\n dtype=[(_, int) for _ in \"abc\"])\n assert_equal(test, ctrl)\n #\n test = np.genfromtxt(TextIO(data), usecols=(0, -1), **kwargs)\n ctrl = np.array([(0, 3), (4, -999)], dtype=[(_, int) for _ in \"ac\"])\n assert_equal(test, ctrl)\n\n def test_withmissing_float(self):\n data = TextIO('A,B\\n0,1.5\\n2,-999.00')\n test = np.mafromtxt(data, dtype=None, delimiter=',',\n missing_values='-999.0', names=True,)\n control = ma.array([(0, 1.5), (2, -1.)],\n mask=[(False, False), (False, True)],\n dtype=[('A', np.int), ('B', np.float)])\n assert_equal(test, control)\n assert_equal(test.mask, control.mask)\n\n def test_with_masked_column_uniform(self):\n \"Test masked column\"\n data = TextIO('1 2 3\\n4 5 6\\n')\n test = np.genfromtxt(data, dtype=None,\n missing_values='2,5', usemask=True)\n control = ma.array([[1, 2, 3], [4, 5, 6]], mask=[[0, 1, 0], [0, 1, 0]])\n assert_equal(test, control)\n\n def test_with_masked_column_various(self):\n \"Test masked column\"\n data = TextIO('True 2 3\\nFalse 5 6\\n')\n test = np.genfromtxt(data, dtype=None,\n missing_values='2,5', usemask=True)\n control = ma.array([(1, 2, 3), (0, 5, 6)],\n mask=[(0, 1, 0), (0, 1, 0)],\n dtype=[('f0', bool), ('f1', bool), ('f2', int)])\n assert_equal(test, control)\n\n def test_invalid_raise(self):\n \"Test invalid raise\"\n data = [\"1, 1, 1, 1, 1\"] * 50\n for i in range(5):\n data[10 * i] = \"2, 2, 2, 2 2\"\n data.insert(0, \"a, b, c, d, e\")\n mdata = TextIO(\"\\n\".join(data))\n #\n kwargs = dict(delimiter=\",\", dtype=None, names=True)\n # XXX: is there a better way to get the return value of the callable in\n # assert_warns ?\n ret = {}\n\n def f(_ret={}):\n _ret['mtest'] = np.ndfromtxt(mdata, invalid_raise=False, **kwargs)\n assert_warns(ConversionWarning, f, _ret=ret)\n mtest = ret['mtest']\n assert_equal(len(mtest), 45)\n assert_equal(mtest, np.ones(45, dtype=[(_, int) for _ in 'abcde']))\n #\n mdata.seek(0)\n assert_raises(ValueError, np.ndfromtxt, mdata,\n delimiter=\",\", names=True)\n\n def test_invalid_raise_with_usecols(self):\n \"Test invalid_raise with usecols\"\n data = [\"1, 1, 1, 1, 1\"] * 50\n for i in range(5):\n data[10 * i] = \"2, 2, 2, 2 2\"\n data.insert(0, \"a, b, c, d, e\")\n mdata = TextIO(\"\\n\".join(data))\n kwargs = dict(delimiter=\",\", dtype=None, names=True,\n invalid_raise=False)\n # XXX: is there a better way to get the return value of the callable in\n # assert_warns ?\n ret = {}\n\n def f(_ret={}):\n _ret['mtest'] = np.ndfromtxt(mdata, usecols=(0, 4), **kwargs)\n assert_warns(ConversionWarning, f, _ret=ret)\n mtest = ret['mtest']\n assert_equal(len(mtest), 45)\n assert_equal(mtest, np.ones(45, dtype=[(_, int) for _ in 'ae']))\n #\n mdata.seek(0)\n mtest = np.ndfromtxt(mdata, usecols=(0, 1), **kwargs)\n assert_equal(len(mtest), 50)\n control = np.ones(50, dtype=[(_, int) for _ in 'ab'])\n control[[10 * _ for _ in range(5)]] = (2, 2)\n assert_equal(mtest, control)\n\n def test_inconsistent_dtype(self):\n \"Test inconsistent dtype\"\n data = [\"1, 1, 1, 1, -1.1\"] * 50\n mdata = TextIO(\"\\n\".join(data))\n\n converters = {4: lambda x: \"(%s)\" % x}\n kwargs = dict(delimiter=\",\", converters=converters,\n dtype=[(_, int) for _ in 'abcde'],)\n assert_raises(ValueError, np.genfromtxt, mdata, **kwargs)\n\n def test_default_field_format(self):\n \"Test default format\"\n data = \"0, 1, 2.3\\n4, 5, 6.7\"\n mtest = np.ndfromtxt(TextIO(data),\n delimiter=\",\", dtype=None, defaultfmt=\"f%02i\")\n ctrl = np.array([(0, 1, 2.3), (4, 5, 6.7)],\n dtype=[(\"f00\", int), (\"f01\", int), (\"f02\", float)])\n assert_equal(mtest, ctrl)\n\n def test_single_dtype_wo_names(self):\n \"Test single dtype w/o names\"\n data = \"0, 1, 2.3\\n4, 5, 6.7\"\n mtest = np.ndfromtxt(TextIO(data),\n delimiter=\",\", dtype=float, defaultfmt=\"f%02i\")\n ctrl = np.array([[0., 1., 2.3], [4., 5., 6.7]], dtype=float)\n assert_equal(mtest, ctrl)\n\n def test_single_dtype_w_explicit_names(self):\n \"Test single dtype w explicit names\"\n data = \"0, 1, 2.3\\n4, 5, 6.7\"\n mtest = np.ndfromtxt(TextIO(data),\n delimiter=\",\", dtype=float, names=\"a, b, c\")\n ctrl = np.array([(0., 1., 2.3), (4., 5., 6.7)],\n dtype=[(_, float) for _ in \"abc\"])\n assert_equal(mtest, ctrl)\n\n def test_single_dtype_w_implicit_names(self):\n \"Test single dtype w implicit names\"\n data = \"a, b, c\\n0, 1, 2.3\\n4, 5, 6.7\"\n mtest = np.ndfromtxt(TextIO(data),\n delimiter=\",\", dtype=float, names=True)\n ctrl = np.array([(0., 1., 2.3), (4., 5., 6.7)],\n dtype=[(_, float) for _ in \"abc\"])\n assert_equal(mtest, ctrl)\n\n def test_easy_structured_dtype(self):\n \"Test easy structured dtype\"\n data = \"0, 1, 2.3\\n4, 5, 6.7\"\n mtest = np.ndfromtxt(TextIO(data), delimiter=\",\",\n dtype=(int, float, float), defaultfmt=\"f_%02i\")\n ctrl = np.array([(0, 1., 2.3), (4, 5., 6.7)],\n dtype=[(\"f_00\", int), (\"f_01\", float), (\"f_02\", float)])\n assert_equal(mtest, ctrl)\n\n def test_autostrip(self):\n \"Test autostrip\"\n data = \"01/01/2003 , 1.3, abcde\"\n kwargs = dict(delimiter=\",\", dtype=None)\n mtest = np.ndfromtxt(TextIO(data), **kwargs)\n ctrl = np.array([('01/01/2003 ', 1.3, ' abcde')],\n dtype=[('f0', '|S12'), ('f1', float), ('f2', '|S8')])\n assert_equal(mtest, ctrl)\n mtest = np.ndfromtxt(TextIO(data), autostrip=True, **kwargs)\n ctrl = np.array([('01/01/2003', 1.3, 'abcde')],\n dtype=[('f0', '|S10'), ('f1', float), ('f2', '|S5')])\n assert_equal(mtest, ctrl)\n\n def test_replace_space(self):\n \"Test the 'replace_space' option\"\n txt = \"A.A, B (B), C:C\\n1, 2, 3.14\"\n # Test default: replace ' ' by '_' and delete non-alphanum chars\n test = np.genfromtxt(TextIO(txt),\n delimiter=\",\", names=True, dtype=None)\n ctrl_dtype = [(\"AA\", int), (\"B_B\", int), (\"CC\", float)]\n ctrl = np.array((1, 2, 3.14), dtype=ctrl_dtype)\n assert_equal(test, ctrl)\n # Test: no replace, no delete\n test = np.genfromtxt(TextIO(txt),\n delimiter=\",\", names=True, dtype=None,\n replace_space='', deletechars='')\n ctrl_dtype = [(\"A.A\", int), (\"B (B)\", int), (\"C:C\", float)]\n ctrl = np.array((1, 2, 3.14), dtype=ctrl_dtype)\n assert_equal(test, ctrl)\n # Test: no delete (spaces are replaced by _)\n test = np.genfromtxt(TextIO(txt),\n delimiter=\",\", names=True, dtype=None,\n deletechars='')\n ctrl_dtype = [(\"A.A\", int), (\"B_(B)\", int), (\"C:C\", float)]\n ctrl = np.array((1, 2, 3.14), dtype=ctrl_dtype)\n assert_equal(test, ctrl)\n\n def test_incomplete_names(self):\n \"Test w/ incomplete names\"\n data = \"A,,C\\n0,1,2\\n3,4,5\"\n kwargs = dict(delimiter=\",\", names=True)\n # w/ dtype=None\n ctrl = np.array([(0, 1, 2), (3, 4, 5)],\n dtype=[(_, int) for _ in ('A', 'f0', 'C')])\n test = np.ndfromtxt(TextIO(data), dtype=None, **kwargs)\n assert_equal(test, ctrl)\n # w/ default dtype\n ctrl = np.array([(0, 1, 2), (3, 4, 5)],\n dtype=[(_, float) for _ in ('A', 'f0', 'C')])\n test = np.ndfromtxt(TextIO(data), **kwargs)\n\n def test_names_auto_completion(self):\n \"Make sure that names are properly completed\"\n data = \"1 2 3\\n 4 5 6\"\n test = np.genfromtxt(TextIO(data),\n dtype=(int, float, int), names=\"a\")\n ctrl = np.array([(1, 2, 3), (4, 5, 6)],\n dtype=[('a', int), ('f0', float), ('f1', int)])\n assert_equal(test, ctrl)\n\n def test_names_with_usecols_bug1636(self):\n \"Make sure we pick up the right names w/ usecols\"\n data = \"A,B,C,D,E\\n0,1,2,3,4\\n0,1,2,3,4\\n0,1,2,3,4\"\n ctrl_names = (\"A\", \"C\", \"E\")\n test = np.genfromtxt(TextIO(data),\n dtype=(int, int, int), delimiter=\",\",\n usecols=(0, 2, 4), names=True)\n assert_equal(test.dtype.names, ctrl_names)\n #\n test = np.genfromtxt(TextIO(data),\n dtype=(int, int, int), delimiter=\",\",\n usecols=(\"A\", \"C\", \"E\"), names=True)\n assert_equal(test.dtype.names, ctrl_names)\n #\n test = np.genfromtxt(TextIO(data),\n dtype=int, delimiter=\",\",\n usecols=(\"A\", \"C\", \"E\"), names=True)\n assert_equal(test.dtype.names, ctrl_names)\n\n def test_fixed_width_names(self):\n \"Test fix-width w/ names\"\n data = \" A B C\\n 0 1 2.3\\n 45 67 9.\"\n kwargs = dict(delimiter=(5, 5, 4), names=True, dtype=None)\n ctrl = np.array([(0, 1, 2.3), (45, 67, 9.)],\n dtype=[('A', int), ('B', int), ('C', float)])\n test = np.ndfromtxt(TextIO(data), **kwargs)\n assert_equal(test, ctrl)\n #\n kwargs = dict(delimiter=5, names=True, dtype=None)\n ctrl = np.array([(0, 1, 2.3), (45, 67, 9.)],\n dtype=[('A', int), ('B', int), ('C', float)])\n test = np.ndfromtxt(TextIO(data), **kwargs)\n assert_equal(test, ctrl)\n\n def test_filling_values(self):\n \"Test missing values\"\n data = b\"1, 2, 3\\n1, , 5\\n0, 6, \\n\"\n kwargs = dict(delimiter=\",\", dtype=None, filling_values=-999)\n ctrl = np.array([[1, 2, 3], [1, -999, 5], [0, 6, -999]], dtype=int)\n test = np.ndfromtxt(TextIO(data), **kwargs)\n assert_equal(test, ctrl)\n\n def test_comments_is_none(self):\n # Github issue 329 (None was previously being converted to 'None').\n test = np.genfromtxt(TextIO(\"test1,testNonetherestofthedata\"),\n dtype=None, comments=None, delimiter=',')\n assert_equal(test[1], b'testNonetherestofthedata')\n test = np.genfromtxt(TextIO(\"test1, testNonetherestofthedata\"),\n dtype=None, comments=None, delimiter=',')\n assert_equal(test[1], b' testNonetherestofthedata')\n\n def test_recfromtxt(self):\n #\n data = TextIO('A,B\\n0,1\\n2,3')\n kwargs = dict(delimiter=\",\", missing_values=\"N/A\", names=True)\n test = np.recfromtxt(data, **kwargs)\n control = np.array([(0, 1), (2, 3)],\n dtype=[('A', np.int), ('B', np.int)])\n self.assertTrue(isinstance(test, np.recarray))\n assert_equal(test, control)\n #\n data = TextIO('A,B\\n0,1\\n2,N/A')\n test = np.recfromtxt(data, dtype=None, usemask=True, **kwargs)\n control = ma.array([(0, 1), (2, -1)],\n mask=[(False, False), (False, True)],\n dtype=[('A', np.int), ('B', np.int)])\n assert_equal(test, control)\n assert_equal(test.mask, control.mask)\n assert_equal(test.A, [0, 2])\n\n def test_recfromcsv(self):\n #\n data = TextIO('A,B\\n0,1\\n2,3')\n kwargs = dict(missing_values=\"N/A\", names=True, case_sensitive=True)\n test = np.recfromcsv(data, dtype=None, **kwargs)\n control = np.array([(0, 1), (2, 3)],\n dtype=[('A', np.int), ('B', np.int)])\n self.assertTrue(isinstance(test, np.recarray))\n assert_equal(test, control)\n #\n data = TextIO('A,B\\n0,1\\n2,N/A')\n test = np.recfromcsv(data, dtype=None, usemask=True, **kwargs)\n control = ma.array([(0, 1), (2, -1)],\n mask=[(False, False), (False, True)],\n dtype=[('A', np.int), ('B', np.int)])\n assert_equal(test, control)\n assert_equal(test.mask, control.mask)\n assert_equal(test.A, [0, 2])\n #\n data = TextIO('A,B\\n0,1\\n2,3')\n test = np.recfromcsv(data, missing_values='N/A',)\n control = np.array([(0, 1), (2, 3)],\n dtype=[('a', np.int), ('b', np.int)])\n self.assertTrue(isinstance(test, np.recarray))\n assert_equal(test, control)\n #\n data = TextIO('A,B\\n0,1\\n2,3')\n dtype = [('a', np.int), ('b', np.float)]\n test = np.recfromcsv(data, missing_values='N/A', dtype=dtype)\n control = np.array([(0, 1), (2, 3)],\n dtype=dtype)\n self.assertTrue(isinstance(test, np.recarray))\n assert_equal(test, control)\n\n def test_gft_using_filename(self):\n # Test that we can load data from a filename as well as a file object\n wanted = np.arange(6).reshape((2, 3))\n if sys.version_info[0] >= 3:\n # python 3k is known to fail for '\\r'\n linesep = ('\\n', '\\r\\n')\n else:\n linesep = ('\\n', '\\r\\n', '\\r')\n\n for sep in linesep:\n data = '0 1 2' + sep + '3 4 5'\n f, name = mkstemp()\n # We can't use NamedTemporaryFile on windows, because we cannot\n # reopen the file.\n try:\n os.write(f, asbytes(data))\n assert_array_equal(np.genfromtxt(name), wanted)\n finally:\n os.close(f)\n os.unlink(name)\n\n def test_gft_using_generator(self):\n # gft doesn't work with unicode.\n def count():\n for i in range(10):\n yield asbytes(\"%d\" % i)\n\n res = np.genfromtxt(count())\n assert_array_equal(res, np.arange(10))\n\n\ndef test_gzip_load():\n a = np.random.random((5, 5))\n\n s = BytesIO()\n f = gzip.GzipFile(fileobj=s, mode=\"w\")\n\n np.save(f, a)\n f.close()\n s.seek(0)\n\n f = gzip.GzipFile(fileobj=s, mode=\"r\")\n assert_array_equal(np.load(f), a)\n\n\ndef test_gzip_loadtxt():\n # Thanks to another windows brokeness, we can't use\n # NamedTemporaryFile: a file created from this function cannot be\n # reopened by another open call. So we first put the gzipped string\n # of the test reference array, write it to a securely opened file,\n # which is then read from by the loadtxt function\n s = BytesIO()\n g = gzip.GzipFile(fileobj=s, mode='w')\n g.write(b'1 2 3\\n')\n g.close()\n s.seek(0)\n\n f, name = mkstemp(suffix='.gz')\n try:\n os.write(f, s.read())\n s.close()\n assert_array_equal(np.loadtxt(name), [1, 2, 3])\n finally:\n os.close(f)\n os.unlink(name)\n\n\ndef test_gzip_loadtxt_from_string():\n s = BytesIO()\n f = gzip.GzipFile(fileobj=s, mode=\"w\")\n f.write(b'1 2 3\\n')\n f.close()\n s.seek(0)\n\n f = gzip.GzipFile(fileobj=s, mode=\"r\")\n assert_array_equal(np.loadtxt(f), [1, 2, 3])\n\n\ndef test_npzfile_dict():\n s = BytesIO()\n x = np.zeros((3, 3))\n y = np.zeros((3, 3))\n\n np.savez(s, x=x, y=y)\n s.seek(0)\n\n z = np.load(s)\n\n assert_('x' in z)\n assert_('y' in z)\n assert_('x' in z.keys())\n assert_('y' in z.keys())\n\n for f, a in z.items():\n assert_(f in ['x', 'y'])\n assert_equal(a.shape, (3, 3))\n\n assert_(len(z.items()) == 2)\n\n for f in z:\n assert_(f in ['x', 'y'])\n\n assert_('x' in z.keys())\n\n\ndef test_load_refcount():\n # Check that objects returned by np.load are directly freed based on\n # their refcount, rather than needing the gc to collect them.\n\n f = BytesIO()\n np.savez(f, [1, 2, 3])\n f.seek(0)\n\n gc.collect()\n n_before = len(gc.get_objects())\n np.load(f)\n n_after = len(gc.get_objects())\n\n assert_equal(n_before, n_after)\n\nif __name__ == \"__main__\":\n run_module_suite()\n" ]
[ [ "numpy.ma.testutils.assert_array_equal", "numpy.genfromtxt", "numpy.load", "numpy.asfortranarray", "numpy.ma.testutils.assert_raises_regex", "numpy.random.random", "numpy.mafromtxt", "numpy.dtype", "numpy.empty", "numpy.testing.assert_warns", "numpy.testing.dec.skipif", "numpy.ma.testutils.run_module_suite", "numpy.save", "numpy.arange", "numpy.ma.testutils.assert_equal", "numpy.recfromcsv", "numpy.testing.dec.knownfailureif", "numpy.array", "numpy.savetxt", "numpy.zeros", "numpy.random.randn", "numpy.testing.assert_", "numpy.loadtxt", "numpy.ma.testutils.assert_raises", "numpy.compat.asbytes", "numpy.ones", "numpy.fromregex", "numpy.recfromtxt", "numpy.testing.utils.tempdir", "numpy.savez", "numpy.ma.array", "numpy.ndfromtxt" ] ]
tanujdhiman/ReAgent
[ "0a085ebdf088b75dcac1839344d2fa2b37fc638b" ]
[ "reagent/gym/tests/test_gym.py" ]
[ "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\nimport logging\nimport os\nimport pprint\nimport unittest\nimport uuid\nfrom typing import Optional\n\nimport numpy as np\nimport pytest\nimport pytorch_lightning as pl\nimport torch\nfrom parameterized import parameterized\nfrom reagent.gym.agents.agent import Agent\nfrom reagent.gym.datasets.episodic_dataset import (\n EpisodicDataset,\n)\nfrom reagent.gym.datasets.replay_buffer_dataset import ReplayBufferDataset\nfrom reagent.gym.envs import Env__Union\nfrom reagent.gym.envs.env_wrapper import EnvWrapper\nfrom reagent.gym.policies.policy import Policy\nfrom reagent.gym.policies.random_policies import make_random_policy_for_env\nfrom reagent.gym.runners.gymrunner import evaluate_for_n_episodes\nfrom reagent.gym.utils import build_normalizer, fill_replay_buffer\nfrom reagent.model_managers.union import ModelManager__Union\nfrom reagent.replay_memory.circular_replay_buffer import ReplayBuffer\nfrom reagent.test.base.horizon_test_base import HorizonTestBase\n\n\n# for seeding the environment\nSEED = 0\n# exponential moving average parameter for tracking reward progress\nREWARD_DECAY = 0.8\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n\n\"\"\"\nPut on-policy gym tests here in the format (test name, path to yaml config).\nFormat path to be: \"configs/<env_name>/<model_name>_<env_name>_online.yaml.\"\nNOTE: These tests should ideally finish quickly (within 10 minutes) since they are\nunit tests which are run many times.\n\"\"\"\nREPLAY_BUFFER_GYM_TESTS_1 = [\n (\"Discrete CRR Cartpole\", \"configs/cartpole/discrete_crr_cartpole_online.yaml\"),\n (\"Discrete DQN Cartpole\", \"configs/cartpole/discrete_dqn_cartpole_online.yaml\"),\n (\"Discrete C51 Cartpole\", \"configs/cartpole/discrete_c51_cartpole_online.yaml\"),\n (\"Discrete QR Cartpole\", \"configs/cartpole/discrete_qr_cartpole_online.yaml\"),\n (\n \"Discrete DQN Open Gridworld\",\n \"configs/open_gridworld/discrete_dqn_open_gridworld.yaml\",\n ),\n (\"SAC Pendulum\", \"configs/pendulum/sac_pendulum_online.yaml\"),\n]\nREPLAY_BUFFER_GYM_TESTS_2 = [\n (\"Continuous CRR Pendulum\", \"configs/pendulum/continuous_crr_pendulum_online.yaml\"),\n (\"TD3 Pendulum\", \"configs/pendulum/td3_pendulum_online.yaml\"),\n (\"Parametric DQN Cartpole\", \"configs/cartpole/parametric_dqn_cartpole_online.yaml\"),\n (\n \"Parametric SARSA Cartpole\",\n \"configs/cartpole/parametric_sarsa_cartpole_online.yaml\",\n ),\n # Disabled for now because flaky.\n # (\n # \"Sparse DQN Changing Arms\",\n # \"configs/sparse/discrete_dqn_changing_arms_online.yaml\",\n # ),\n (\"SlateQ RecSim\", \"configs/recsim/slate_q_recsim_online.yaml\"),\n (\n \"SlateQ RecSim with Discount Scaled by Time Diff\",\n \"configs/recsim/slate_q_recsim_online_with_time_scale.yaml\",\n ),\n (\n \"SlateQ RecSim multi selection\",\n \"configs/recsim/slate_q_recsim_online_multi_selection.yaml\",\n ),\n (\"PossibleActionsMask DQN\", \"configs/functionality/dqn_possible_actions_mask.yaml\"),\n]\n\nONLINE_EPISODE_GYM_TESTS = [\n (\n \"REINFORCE Cartpole online\",\n \"configs/cartpole/discrete_reinforce_cartpole_online.yaml\",\n ),\n (\n \"PPO Cartpole online\",\n \"configs/cartpole/discrete_ppo_cartpole_online.yaml\",\n ),\n]\n\n\ncurr_dir = os.path.dirname(__file__)\n\n\nclass TestGym(HorizonTestBase):\n # pyre-fixme[16]: Module `parameterized` has no attribute `expand`.\n @parameterized.expand(REPLAY_BUFFER_GYM_TESTS_1)\n def test_replay_buffer_gym_cpu_1(self, name: str, config_path: str):\n self._test_replay_buffer_gym_cpu(name, config_path)\n\n # pyre-fixme[16]: Module `parameterized` has no attribute `expand`.\n @parameterized.expand(REPLAY_BUFFER_GYM_TESTS_2)\n def test_replay_buffer_gym_cpu_2(self, name: str, config_path: str):\n self._test_replay_buffer_gym_cpu(name, config_path)\n\n def _test_replay_buffer_gym_cpu(self, name: str, config_path: str):\n logger.info(f\"Starting {name} on CPU\")\n self.run_from_config(\n run_test=run_test_replay_buffer,\n config_path=os.path.join(curr_dir, config_path),\n use_gpu=False,\n )\n logger.info(f\"{name} passes!\")\n\n # pyre-fixme[16]: Module `parameterized` has no attribute `expand`.\n @parameterized.expand(REPLAY_BUFFER_GYM_TESTS_1)\n @pytest.mark.serial\n @unittest.skipIf(not torch.cuda.is_available(), \"CUDA not available\")\n def test_replay_buffer_gym_gpu_1(self, name: str, config_path: str):\n self._test_replay_buffer_gym_gpu(name, config_path)\n\n # pyre-fixme[16]: Module `parameterized` has no attribute `expand`.\n @parameterized.expand(REPLAY_BUFFER_GYM_TESTS_2)\n @pytest.mark.serial\n @unittest.skipIf(not torch.cuda.is_available(), \"CUDA not available\")\n def test_replay_buffer_gym_gpu_2(self, name: str, config_path: str):\n self._test_replay_buffer_gym_gpu(name, config_path)\n\n def _test_replay_buffer_gym_gpu(self, name: str, config_path: str):\n logger.info(f\"Starting {name} on GPU\")\n self.run_from_config(\n run_test=run_test_replay_buffer,\n config_path=os.path.join(curr_dir, config_path),\n use_gpu=True,\n )\n logger.info(f\"{name} passes!\")\n\n # pyre-fixme[16]: Module `parameterized` has no attribute `expand`.\n @parameterized.expand(ONLINE_EPISODE_GYM_TESTS)\n def test_online_episode_gym_cpu(self, name: str, config_path: str):\n logger.info(f\"Starting {name} on CPU\")\n self.run_from_config(\n run_test=run_test_online_episode,\n config_path=os.path.join(curr_dir, config_path),\n use_gpu=False,\n )\n logger.info(f\"{name} passes!\")\n\n\ndef eval_policy(\n env: EnvWrapper,\n serving_policy: Policy,\n num_eval_episodes: int,\n serving: bool = True,\n) -> np.ndarray:\n agent = (\n Agent.create_for_env_with_serving_policy(env, serving_policy)\n if serving\n else Agent.create_for_env(env, serving_policy)\n )\n\n eval_rewards = evaluate_for_n_episodes(\n n=num_eval_episodes,\n env=env,\n agent=agent,\n max_steps=env.max_steps,\n num_processes=1,\n ).squeeze(1)\n\n logger.info(\"============Eval rewards==============\")\n logger.info(eval_rewards)\n mean_eval = np.mean(eval_rewards)\n logger.info(f\"average: {mean_eval};\\tmax: {np.max(eval_rewards)}\")\n return np.array(eval_rewards)\n\n\ndef identity_collate(batch):\n assert isinstance(batch, list) and len(batch) == 1, f\"Got {batch}\"\n return batch[0]\n\n\ndef run_test_replay_buffer(\n env: Env__Union,\n model: ModelManager__Union,\n replay_memory_size: int,\n train_every_ts: int,\n train_after_ts: int,\n num_train_episodes: int,\n passing_score_bar: float,\n num_eval_episodes: int,\n use_gpu: bool,\n minibatch_size: Optional[int] = None,\n):\n \"\"\"\n Run an online learning test with a replay buffer. The replay buffer is pre-filled, then the training starts.\n Each transition is added to the replay buffer immediately after it takes place.\n \"\"\"\n env = env.value\n pl.seed_everything(SEED)\n env.seed(SEED)\n env.action_space.seed(SEED)\n\n normalization = build_normalizer(env)\n logger.info(f\"Normalization is: \\n{pprint.pformat(normalization)}\")\n\n manager = model.value\n trainer = manager.build_trainer(\n use_gpu=use_gpu,\n normalization_data_map=normalization,\n )\n training_policy = manager.create_policy(trainer, serving=False)\n\n if not isinstance(trainer, pl.LightningModule):\n if minibatch_size is None:\n minibatch_size = trainer.minibatch_size\n assert minibatch_size == trainer.minibatch_size\n\n assert minibatch_size is not None\n\n replay_buffer = ReplayBuffer(\n replay_capacity=replay_memory_size, batch_size=minibatch_size\n )\n\n device = torch.device(\"cuda\") if use_gpu else torch.device(\"cpu\")\n # first fill the replay buffer using random policy\n train_after_ts = max(train_after_ts, minibatch_size)\n random_policy = make_random_policy_for_env(env)\n agent = Agent.create_for_env(env, policy=random_policy)\n fill_replay_buffer(\n env=env,\n replay_buffer=replay_buffer,\n desired_size=train_after_ts,\n agent=agent,\n )\n\n agent = Agent.create_for_env(env, policy=training_policy, device=device)\n # TODO: Simplify this setup by creating LightningDataModule\n dataset = ReplayBufferDataset.create_for_trainer(\n trainer,\n env,\n agent,\n replay_buffer,\n batch_size=minibatch_size,\n training_frequency=train_every_ts,\n num_episodes=num_train_episodes,\n max_steps=200,\n device=device,\n )\n data_loader = torch.utils.data.DataLoader(dataset, collate_fn=identity_collate)\n pl_trainer = pl.Trainer(\n max_epochs=1,\n gpus=int(use_gpu),\n deterministic=True,\n default_root_dir=f\"lightning_log_{str(uuid.uuid4())}\",\n )\n # Note: the fit() function below also evaluates the agent along the way\n # and adds the new transitions to the replay buffer, so it is training\n # on incrementally larger and larger buffers.\n pl_trainer.fit(trainer, data_loader)\n\n # TODO: Also check train_reward\n\n serving_policy = manager.create_policy(\n trainer, serving=True, normalization_data_map=normalization\n )\n\n eval_rewards = eval_policy(env, serving_policy, num_eval_episodes, serving=True)\n assert (\n eval_rewards.mean() >= passing_score_bar\n ), f\"Eval reward is {eval_rewards.mean()}, less than < {passing_score_bar}.\\n\"\n\n\ndef run_test_online_episode(\n env: Env__Union,\n model: ModelManager__Union,\n num_train_episodes: int,\n passing_score_bar: float,\n num_eval_episodes: int,\n use_gpu: bool,\n):\n \"\"\"\n Run an online learning test. At the end of each episode training is run on the trajectory.\n \"\"\"\n env = env.value\n pl.seed_everything(SEED)\n env.seed(SEED)\n env.action_space.seed(SEED)\n\n normalization = build_normalizer(env)\n logger.info(f\"Normalization is: \\n{pprint.pformat(normalization)}\")\n\n manager = model.value\n trainer = manager.build_trainer(\n use_gpu=use_gpu,\n normalization_data_map=normalization,\n )\n policy = manager.create_policy(trainer, serving=False)\n\n device = torch.device(\"cuda\") if use_gpu else torch.device(\"cpu\")\n\n agent = Agent.create_for_env(env, policy, device=device)\n\n pl_trainer = pl.Trainer(\n max_epochs=1,\n gpus=int(use_gpu),\n deterministic=True,\n default_root_dir=f\"lightning_log_{str(uuid.uuid4())}\",\n )\n dataset = EpisodicDataset(\n env=env, agent=agent, num_episodes=num_train_episodes, seed=SEED\n )\n data_loader = torch.utils.data.DataLoader(dataset, collate_fn=identity_collate)\n pl_trainer.fit(trainer, data_loader)\n\n eval_rewards = evaluate_for_n_episodes(\n n=num_eval_episodes,\n env=env,\n agent=agent,\n max_steps=env.max_steps,\n num_processes=1,\n ).squeeze(1)\n assert (\n eval_rewards.mean() >= passing_score_bar\n ), f\"Eval reward is {eval_rewards.mean()}, less than < {passing_score_bar}.\\n\"\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.max", "torch.device", "numpy.array", "numpy.mean", "torch.cuda.is_available", "torch.utils.data.DataLoader" ] ]
tianjuchen/neml
[ "61ca3dcefcfb20c3f4405ca0ca2117a5414ca933" ]
[ "examples/rate_independent.py" ]
[ "#!/usr/bin/env python3\n\nimport sys\nsys.path.append('..')\n\nfrom neml import solvers, models, elasticity, drivers, surfaces, hardening, ri_flow\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nif __name__ == \"__main__\":\n E = 200000.0\n nu = 0.27\n\n mu = E / (2 * (1.0 + nu))\n K = E / (3 * (1 - 2 * nu))\n\n s0 = 300.0\n Kp = 0.0\n c = [30000.0]\n r = [60.0]\n \n elastic = elasticity.IsotropicLinearElasticModel(mu, \"shear\", K, \"bulk\")\n\n surface = surfaces.IsoKinJ2()\n iso = hardening.LinearIsotropicHardeningRule(s0, Kp)\n gmodels = [hardening.ConstantGamma(g) for g in r]\n As = [0.0]\n ns = [1.0]\n hrule = hardening.Chaboche(iso, c, gmodels, As, ns)\n\n flow = ri_flow.RateIndependentNonAssociativeHardening(surface, hrule)\n model = models.SmallStrainRateIndependentPlasticity(elastic, flow)\n \n \n # Uniaxial stress/strain curves at decades of strain rates\n erates = np.logspace(-6,2,9)\n for rate in erates:\n res = drivers.uniaxial_test(model, rate)\n plt.plot(res['strain'], res['stress'])\n \n plt.xlabel(\"Strain (-/-)\")\n plt.ylabel(\"Stress (MPa)\")\n plt.show()\n \n # A strain-controlled cyclic test\n res = drivers.strain_cyclic(model, 0.01, -0.25, 1.0e-4, 50)\n plt.plot(res['strain'], res['stress'], 'k-')\n plt.xlabel(\"Strain (-/-)\")\n plt.ylabel(\"Stress (MPa)\")\n plt.show()\n\n plt.plot(res['cycles'], res['max'], 'k-')\n plt.plot(res['cycles'], res['min'], 'k-')\n plt.plot(res['cycles'], res['mean'], 'k-')\n plt.xlabel(\"Cycle\")\n plt.ylabel(\"Stress (MPa)\")\n plt.show()\n \n # A stress-controlled cyclic test\n res = drivers.stress_cyclic(model, 525.0, -1.0, 5.0, 50,\n hold_time = 100)\n plt.plot(res['strain'], res['stress'], 'k-')\n plt.xlabel(\"Strain (-/-)\")\n plt.ylabel(\"Stress (MPa)\")\n plt.show()\n\n plt.plot(res['cycles'], res['max'], 'k-')\n plt.plot(res['cycles'], res['min'], 'k-')\n plt.plot(res['cycles'], res['mean'], 'k-')\n plt.xlabel(\"Cycle\")\n plt.ylabel(\"Strain (-/-)\")\n plt.show()\n \n # Stress relaxation test\n res = drivers.stress_relaxation(model, 0.02, 1.0e-4, 2000.0)\n plt.plot(res['time'], res['stress'], 'k-')\n plt.xlabel('Time (s)')\n plt.ylabel('Stress (MPa)')\n plt.show()\n\n plt.plot(res['rtime'], res['rrate'], 'k-')\n plt.xlabel('Time (s)')\n plt.ylabel('Relaxation rate (MPa/s)')\n plt.show()\n\n # Creep test\n res = drivers.creep(model, 350.0, 10.0, 2000.0)\n plt.plot(res['time'], res['strain'], 'k-')\n plt.xlabel('Time (s)')\n plt.ylabel('Strain (-/-)')\n plt.show()\n\n plt.plot(res['rtime'], res['rrate'], 'k-')\n plt.xlabel('Time (s)')\n plt.ylabel('Creep rate (1/s)')\n plt.show()\n" ]
[ [ "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.show", "numpy.logspace" ] ]
packtprasadr/Machine-Learning-Algorithms
[ "06c1d79fd036f32d28261f9a792f6206767717a7" ]
[ "Chapter09/3spectral_clustering_2.py" ]
[ "from __future__ import print_function\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom sklearn.datasets import make_moons\r\nfrom sklearn.cluster import SpectralClustering\r\n\r\n\r\n# For reproducibility\r\nnp.random.seed(1000)\r\n\r\nnb_samples = 1000\r\n\r\n\r\nif __name__ == '__main__':\r\n # Create dataset\r\n X, Y = make_moons(n_samples=nb_samples, noise=0.05)\r\n\r\n # Try different gammas with a RBF affinity\r\n Yss = []\r\n gammas = np.linspace(0, 12, 4)\r\n\r\n for gamma in gammas:\r\n sc = SpectralClustering(n_clusters=2, affinity='rbf', gamma=gamma)\r\n Yss.append(sc.fit_predict(X))\r\n\r\n # Show data\r\n fig, ax = plt.subplots(1, 4, figsize=(30, 10), sharey=True)\r\n\r\n for x in range(4):\r\n ax[x].grid()\r\n ax[x].set_title('Gamma = %.0f' % gammas[x])\r\n\r\n for i in range(nb_samples):\r\n c = Yss[x][i]\r\n\r\n if c == 0:\r\n ax[x].scatter(X[i, 0], X[i, 1], marker='o', color='r')\r\n else:\r\n ax[x].scatter(X[i, 0], X[i, 1], marker='^', color='b')\r\n\r\n plt.show()" ]
[ [ "sklearn.cluster.SpectralClustering", "numpy.random.seed", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show", "numpy.linspace", "sklearn.datasets.make_moons" ] ]
Darkhunter9/EBSD_CVAE_GAN_Public
[ "58d77a9cf419d450203b5af30301330ce6534694" ]
[ "utils/data_generator_av.py" ]
[ "\"\"\"\nCopyright (c) 2019-2022, Zihao Ding/Carnegie Mellon University\nAll rights reserved.\n********************************************************************\n\nProject: data_generator_av.py\n\nMODULE: util\n\nAuthor: Zihao Ding, Carnegie Mellon University\n\nBrief:\n-------------\nData generator including multiple attributes (orientation + av)\nfor model training/testing, with choice of image processing\nInherited from DataGenerator\n\n\nDate:\n-------------\n2022/03/17 ZD 1.0 public version\n\"\"\"\n\nimport numpy as np\nimport h5py\nimport cv2\nfrom sklearn.utils import shuffle\n\nimport tensorflow as tf\n\nfrom .eu2qu import eu2qu\nfrom .imgprocess import *\nfrom .data_generator import DataGenerator\n\n# maximum accelerating voltage: 30kV\nAV_MAX = 30.\n\nclass DataGeneratorAV(DataGenerator):\n '''\n Data generator for model training/testing, including multiple attributes (orientation + av)\n with choice of image processing \\\\\n Inherited from DataGenerator class\n '''\n def __init__(self, data, batch_size=32, dim=(60,60), n_channels=1, shuffle=True, processing=None):\n '''\n Initialization of a data generator object\n\n Input:\n ------\n data: directory to h5 file, string, default: None\n\n batch_size: number of patterns in a batch sent, int, default: 32\n\n dim: dimension of patterns, (int, int), default: (60, 60)\n\n n_channels: number of channels of patterns, int, default: 1\n\n shuffle: whether to shuffle the order of patterns, bool, default: True\n\n processing: image processing recipe, string, default: None\n\n\n Output:\n ------\n None\n '''\n super().__init__(data, batch_size, dim, n_channels, shuffle, processing)\n self.av = self.f['EMData']['EBSD']['AcceleratingVoltage']\n\n\n def __getitem__(self, index):\n '''\n Generate one batch of data\n Required by Sequence class\n\n Input:\n ------\n index: index of batch, int\n\n\n Output:\n ------\n X: patterns after processing, 4darray, shape: (n,c,h,w)\n\n y: labels, 2darray, shape: (n, 5) (orientation + av)\n '''\n # Generate indexes of the batch\n indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]\n # To make sure indexing elements are in increasing order\n # Otherwise TypeError: Indexing elements must be in increasing order\n indexes = np.sort(indexes)\n\n # Generate data\n X = np.array(self.X[indexes,:,:])\n X = X.astype(float)\n\n # resize\n if not self.resize:\n X_new = np.zeros((len(X),self.dim[0],self.dim[1]))\n for i in range(len(X)):\n X_new[i] = cv2.resize(X[i],(self.dim[1],self.dim[0]),interpolation=cv2.INTER_LINEAR)\n else:\n X_new = X\n X_new = X_new.astype(np.uint8)\n\n # preprocessing\n if self.processing:\n # self.processing = ('clahe(10, (10, 10))','squaremask()')\n for i in self.processing:\n X_new = eval(i.replace('(','(X_new,',1))\n\n X_new = X_new.astype(float)\n X_new = np.clip(np.nan_to_num(X_new),0.,255.)\n X_new = X_new / 255.0\n X_new = X_new[:,:,:,np.newaxis]\n\n # orientation\n y = np.array(self.y[indexes,:])\n y = y.astype(float)\n temp_y = np.zeros((len(y),4))\n for i in range(len(y)):\n temp_y[i] = eu2qu(y[i])\n y = temp_y\n y = np.clip(np.nan_to_num(y),-1.,1.)\n \n\n # av\n av = np.array(self.av[indexes])\n av = av.astype(float) / AV_MAX\n av = av[:,np.newaxis]\n y = np.concatenate([y, av], axis=1)\n\n # shuffle inside the batch\n if self.shuffle:\n return shuffle(X_new, y)\n else:\n return X_new, y" ]
[ [ "numpy.concatenate", "numpy.array", "numpy.nan_to_num", "numpy.sort", "sklearn.utils.shuffle" ] ]
prasathlab/basenji
[ "d61389dc553aa610544503a3e937c1b53906fe35" ]
[ "bin/saluki_ism_tfr_folds.py" ]
[ "#!/usr/bin/env python\n# Copyright 2020 Calico LLC\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# https://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =========================================================================\n\nfrom optparse import OptionParser, OptionGroup\nimport glob\nimport os\nimport pickle\nimport pdb\nimport shutil\nimport subprocess\nimport sys\n\nimport h5py\nimport numpy as np\nimport pandas as pd\n\nimport slurm\n\n\"\"\"\nsaluki_ism_tfr_folds.py\n\nCompute ISM from sequences stored in TFRecords for an array\nof trained models on separate gene folds.\n\"\"\"\n\n################################################################################\n# main\n################################################################################\ndef main():\n usage = 'usage: %prog [options] <models_dir>'\n parser = OptionParser(usage)\n\n # ism-tfr\n ism_options = OptionGroup(parser, 'saluki_ism_tfr.py options')\n ism_options.add_option('-c', dest='coding_stop',\n default=False, action='store_true',\n help='Zero out coding track for stop codon mutations [Default: %default]')\n ism_options.add_option('-l', dest='mut_len',\n default=None, type='int',\n help='Length of 3\\' sequence to mutate [Default: %default]')\n ism_options.add_option('-o', dest='out_dir',\n default='ism',\n help='Output directory for ISM [Default: %default]')\n ism_options.add_option('--split', dest='split_label',\n default='test',\n help='Dataset split label for eg TFR pattern [Default: %default]')\n parser.add_option_group(ism_options)\n\n # multi\n fold_options = OptionGroup(parser, 'cross-fold options')\n fold_options.add_option('-d', dest='data_head',\n default=None, type='int',\n help='Index for dataset/head [Default: %default]')\n fold_options.add_option('--data', dest='data_dir',\n default=None,\n help='Data directory for processing TFRecords in proper order [Default: %default]')\n fold_options.add_option('-e', dest='conda_env',\n default='tf2.6-rna',\n help='Anaconda environment [Default: %default]')\n fold_options.add_option('--name', dest='name',\n default='ism', help='SLURM name prefix [Default: %default]')\n fold_options.add_option('--max_proc', dest='max_proc',\n default=None, type='int',\n help='Maximum concurrent processes [Default: %default]')\n fold_options.add_option('-p', dest='processes',\n default=None, type='int',\n help='Number of processes, passed by multi script. \\\n (Unused, but needs to appear as dummy.)')\n fold_options.add_option('-q', dest='queue',\n default='geforce',\n help='SLURM queue on which to run the jobs [Default: %default]')\n fold_options.add_option('-r', dest='restart',\n default=False, action='store_true',\n help='Restart a partially completed job [Default: %default]')\n parser.add_option_group(fold_options)\n\n (options, args) = parser.parse_args()\n\n if len(args) != 1:\n parser.error('Must provide cross-validation model directory')\n else:\n models_dir = args[0]\n\n #######################################################\n # prep work\n\n model_str = 'model_best.h5'\n if options.data_head is not None:\n model_str = 'model%d_best.h5' % options.data_head\n\n num_folds = len(glob.glob('%s/f*_c0/train/%s' % (models_dir,model_str)))\n num_crosses = len(glob.glob('%s/f0_c*/train/%s' % (models_dir,model_str)))\n print('Folds %d, Crosses %d' % (num_folds, num_crosses))\n\n #######################################################\n # predict\n\n params_file = '%s/params.json' % models_dir\n\n cmd_base = '. /home/drk/anaconda3/etc/profile.d/conda.sh;'\n cmd_base += ' conda activate %s;' % options.conda_env\n cmd_base += ' saluki_ism_tfr.py %s' % params_file\n\n jobs = []\n for fi in range(num_folds):\n for ci in range(num_crosses):\n fc = 'f%d_c%d' % (fi, ci)\n model_file = '%s/%s/train/%s' % (models_dir, fc, model_str)\n data_dir = '%s/%s/data0' % (models_dir, fc)\n out_dir = '%s/%s/%s' % (models_dir, fc, options.out_dir)\n\n if options.split_label == '*':\n data_dir = options.data_dir\n\n if not options.restart or not os.path.isfile('%s/scores.h5'%out_dir):\n cmd = '%s %s %s' % (cmd_base, model_file, data_dir)\n cmd += ' %s' % options_string(options, ism_options, out_dir)\n j = slurm.Job(cmd, '%s_%s' % (options.name, fc),\n '%s.out'%out_dir, '%s.err'%out_dir,\n queue=options.queue, gpu=1,\n mem=30000, time='2-0:0:0')\n jobs.append(j)\n\n slurm.multi_run(jobs, max_proc=options.max_proc, verbose=True,\n launch_sleep=10, update_sleep=60)\n\n #######################################################\n # ensemble\n\n ensemble_dir = '%s/ensemble' % models_dir\n os.makedirs(ensemble_dir, exist_ok=True)\n \n if options.split_label == '*':\n # collect scores files\n score_files = []\n for fi in range(num_folds):\n for ci in range(num_crosses):\n score_file = '%s/f%d_c%d/%s/scores.h5' % (models_dir,fi,ci,options.out_dir)\n score_files.append(score_file)\n\n # output file\n ensemble_out_dir = '%s/%s' % (ensemble_dir, options.out_dir)\n os.makedirs(ensemble_out_dir, exist_ok=True)\n ensemble_file = '%s/scores.h5' % ensemble_out_dir\n\n # make ensemble\n ensemble_scores(score_files, ensemble_file)\n\n else:\n for fi in range(num_folds):\n # collect scores files\n score_files = []\n for ci in range(num_crosses):\n score_file = '%s/f%d_c%d/%s/scores.h5' % (models_dir,fi,ci,options.out_dir)\n score_files.append(score_file)\n\n # output file\n ensemble_fold_dir = '%s/f%d' % (ensemble_dir, fi)\n os.makedirs(ensemble_fold_dir, exist_ok=True)\n ensemble_out_dir = '%s/%s' % (ensemble_fold_dir, options.out_dir)\n os.makedirs(ensemble_out_dir, exist_ok=True)\n ensemble_file = '%s/scores.h5' % ensemble_out_dir\n\n # make ensemble\n ensemble_scores(score_files, ensemble_file)\n\n\ndef ensemble_scores(scores_files, ensemble_file):\n # copy first\n shutil.copy(scores_files[0], ensemble_file)\n\n # read ism scores\n rep_ism = []\n for score_file in scores_files:\n with h5py.File(score_file, 'r') as score_h5:\n rep_ism.append(score_h5['ism'][:])\n\n # take average\n rep_ism = np.array(rep_ism, dtype='float32')\n avg_ism = rep_ism.mean(axis=0).astype('float16')\n\n # write to ensemble\n with h5py.File(ensemble_file, 'a') as ensemble_h5:\n ensemble_h5['ism'][:] = avg_ism\n\n'''\n# this is wrong because it writes one ensemble rather than one per fold.\ndef ensemble_folds(models_dir, out_dir, num_folds, num_crosses):\n for fi in range(num_folds):\n print('Ensembling fold %d' % fi)\n scores_c0_file = '%s/f%d_c0/%s/scores.h5' % (models_dir, fi, out_dir)\n scores_ens_dir = '%s/ensemble/%s' % (models_dir, out_dir)\n scores_ens_file = '%s/scores.h5' % scores_ens_dir\n\n # copy cross0\n os.makedirs(scores_ens_dir, exist_ok=True)\n shutil.copy(scores_c0_file, scores_ens_file)\n\n # read ism scores\n cross_ism = []\n for ci in range(num_crosses):\n scores_ci_file = '%s/f%d_c%d/%s/scores.h5' % (models_dir, fi, ci, out_dir)\n with h5py.File(scores_ci_file, 'r') as scores_ci_h5:\n cross_ism.append(scores_ci_h5['ism'][:])\n\n # take average\n cross_ism = np.array(cross_ism, dtype='float32')\n avg_ism = cross_ism.mean(axis=0).astype('float16')\n\n # write to ensemble\n with h5py.File(scores_ens_file, 'a') as scores_ens_h5:\n scores_ens_h5['ism'][:] = avg_ism\n'''\n\ndef options_string(options, ism_options, out_dir):\n options_str = ''\n\n for opt in ism_options.option_list:\n opt_str = opt.get_opt_string()\n opt_value = options.__dict__[opt.dest]\n\n # wrap askeriks in \"\"\n if type(opt_value) == str and opt_value.find('*') != -1:\n opt_value = '\"%s\"' % opt_value\n\n # no value for bools\n elif type(opt_value) == bool:\n if not opt_value:\n opt_str = ''\n opt_value = ''\n\n # skip Nones\n elif opt_value is None:\n opt_str = ''\n opt_value = ''\n\n # modify\n elif opt.dest == 'out_dir':\n opt_value = out_dir\n\n options_str += ' %s %s' % (opt_str, opt_value)\n\n return options_str\n\n################################################################################\n# __main__\n################################################################################\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.array" ] ]
SCGTall/CS6384ComputerVision
[ "f9b911d4230d65336555291a9d72f07f6aadcfe9" ]
[ "Codes/Project1/HandIn/lab_histeq.py" ]
[ "# -*- coding: utf-8 -*-\nimport cv2\nimport numpy as np\nimport sys\nfrom myModules import check_range\n\n# read arguments\nif(len(sys.argv) != 7) :\n print(sys.argv[0], \": takes 6 arguments. Not \", len(sys.argv)-1)\n print(\"Expecting arguments: w1 h1 w2 h2 ImageIn ImageOut.\")\n print(\"Example:\", sys.argv[0], \" 0.2 0.1 0.8 0.5 fruits.jpg out.png\")\n sys.exit()\n\nw1 = float(sys.argv[1])\nh1 = float(sys.argv[2])\nw2 = float(sys.argv[3])\nh2 = float(sys.argv[4])\nname_input = sys.argv[5]\nname_output = sys.argv[6]\n\n# check the correctness of the input parameters\nif(w1<0 or h1<0 or w2<=w1 or h2<=h1 or w2>1 or h2>1) :\n print(\" arguments must satisfy 0 <= w1 < w2 <= 1, 0 <= h1 < h2 <= 1\")\n sys.exit()\n\n# read image\nprint(\"Processing... Please wait until the image appears, then press any key to exit.\")\ninputImage = cv2.imread(name_input, cv2.IMREAD_COLOR)\nif(inputImage is None) :\n print(sys.argv[0], \": Failed to read image from: \", name_input)\n sys.exit()\n#cv2.imshow(\"input image: \" + name_input, inputImage)\n\n# check for color image and change w1, w2, h1, h2 to pixel locations\nrows, cols, bands = inputImage.shape\nif(bands != 3) :\n print(\"Input image is not a standard color image:\", inputImage)\n sys.exit()\n\nW1 = round(w1*(cols-1))\nH1 = round(h1*(rows-1))\nW2 = round(w2*(cols-1))\nH2 = round(h2*(rows-1))\n\n# Cut out target region\nimage1 = inputImage[H1:H2+1, W1:W2+1, :]\n# Change color space\nimage2 = cv2.cvtColor(image1, cv2.COLOR_BGR2Lab)\n# Illumination stretching\nimage3 = np.copy(image2)\nimage3[:, :, 0] = cv2.equalizeHist(image2[:, :, 0])# L\n# Convert back to BGR\ncheck_range(image3)# check range\nimage4 = cv2.cvtColor(image3, cv2.COLOR_Lab2BGR)\ncheck_range(image4)# check range\n# Copy back to outputImage\noutputImage = np.copy(inputImage)\nfor i in range(H1, H2+1):\n for j in range(W1, W2+1):\n outputImage[i, j] = image4[i - H1, j - W1]\n\n\n# Save image\ncv2.imwrite(name_output, outputImage)\n" ]
[ [ "numpy.copy" ] ]
r0cketr1kky/einsteinpy
[ "d86f412736a42e2cf688a1e21d7b553868a14bc4" ]
[ "src/einsteinpy/plotting/senile/geodesics_scatter.py" ]
[ "import astropy.units as u\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.animation import FuncAnimation\n\nfrom einsteinpy.bodies import Body\nfrom einsteinpy.geodesic import Geodesic\nfrom einsteinpy.metric import Schwarzschild\n\n\nclass ScatterGeodesicPlotter:\n \"\"\"\n Class for plotting static matplotlib plots.\n \"\"\"\n\n def __init__(self, time=0 * u.s, attractor_color=\"black\", cmap_color=\"Oranges\"):\n \"\"\"\n Constructor.\n\n Parameters\n ----------\n time : ~astropy.units.quantity.Quantity\n Time of start, defaults to 0 seconds.\n attractor_color : string, optional\n Color which is used to denote the attractor. Defaults to black.\n cmap_color : string, optional\n Color used in function plot.\n\n \"\"\"\n self.time = time\n self._attractor_present = False\n self.attractor_color = attractor_color\n self.cmap_color = cmap_color\n\n def _plot_attractor(self):\n self._attractor_present = True\n plt.scatter(0, 0, color=self.attractor_color)\n\n def plot(self, geodesic):\n \"\"\"\n\n Parameters\n ----------\n geodesic : ~einsteinpy.geodesic.Geodesic\n Geodesic of the body\n\n \"\"\"\n self.mass = geodesic.attractor.mass\n\n vals = geodesic.trajectory\n\n time = vals[:, 0]\n r = vals[:, 1]\n # Currently not being used (might be useful in future)\n # theta = vals[:, 2]\n phi = vals[:, 3]\n\n pos_x = r * np.cos(phi)\n pos_y = r * np.sin(phi)\n\n plt.scatter(pos_x, pos_y, s=1, c=time, cmap=self.cmap_color)\n\n if not self._attractor_present:\n self._plot_attractor()\n\n def animate(self, geodesic, interval=50):\n \"\"\"\n Function to generate animated plots of geodesics.\n\n Parameters\n ----------\n geodesic : ~einsteinpy.geodesic.Geodesic\n Geodesic of the body\n interval : int, optional\n Control the time between frames. Add time in milliseconds.\n\n \"\"\"\n\n vals = geodesic.trajectory\n\n time = vals[:, 0]\n r = vals[:, 1]\n # Currently not being used (might be useful in future)\n # theta = vals[:, 2]\n phi = vals[:, 3]\n\n pos_x = r * np.cos(phi)\n pos_y = r * np.sin(phi)\n frames = pos_x.shape[0]\n x_max, x_min = max(pos_x), min(pos_x)\n y_max, y_min = max(pos_y), min(pos_y)\n margin_x = (x_max - x_min) * 0.1\n margin_y = (y_max - y_min) * 0.1\n\n fig = plt.figure()\n\n plt.xlim(x_min - margin_x, x_max + margin_x)\n plt.ylim(y_min - margin_y, y_max + margin_y)\n pic = plt.scatter([], [], s=1, c=[])\n plt.scatter(0, 0, color=\"black\")\n\n def _update(frame):\n pic.set_offsets(np.vstack((pos_x[: frame + 1], pos_y[: frame + 1])).T)\n pic.set_array(time[: frame + 1])\n return (pic,)\n\n self.animated = FuncAnimation(fig, _update, frames=frames, interval=interval)\n\n def show(self):\n plt.show()\n\n def save(self, name=\"scatter_geodesic.png\"):\n plt.savefig(name)\n" ]
[ [ "numpy.sin", "matplotlib.pyplot.xlim", "matplotlib.animation.FuncAnimation", "matplotlib.pyplot.savefig", "matplotlib.pyplot.ylim", "matplotlib.pyplot.figure", "matplotlib.pyplot.show", "numpy.cos", "matplotlib.pyplot.scatter", "numpy.vstack" ] ]
bluemarlin2018/Kaggle_Challenges
[ "606a887754e8c50923aa3b117ae997bd74e99223" ]
[ "02_Cat_vs_Dog/test_utils.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport numpy as np\nimport pandas as pd\n\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras import layers,models\n\n\n#Load model from checkpoint in folder model/\ndef load_model(checkpoint):\n model = models.load_model(\"models/\"+ checkpoint)\n model.compile(loss='binary_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])\n return model\n \n# Load kaggle images from test folder \ndef load_images(test_folder, image_size):\n images = []\n for img in os.listdir(test_folder):\n img = os.path.join(test_folder, img)\n img = image.load_img(img, target_size=(image_size[0], image_size[1]))\n img = image.img_to_array(img)/255.0\n print(img)\n img = np.expand_dims(img, axis=0)\n images.append(img)\n \n images = np.vstack(images)\n return images\n\n# Use CNN model to predict on test images using batches \ndef predict(model, images):\n classes = model.predict_classes(images, batch_size=32)\n return classes\n\n# =============================================================================\n# Call this function first\n# Initiliaze model from saved checkpoint\n# Load images from test folder\n# Get predictions\n# =============================================================================\ndef init_test(test_folder, image_size, checkpoint): \n model = load_model(checkpoint)\n images = load_images(test_folder, image_size)\n classes = predict(model, images)\n return classes" ]
[ [ "tensorflow.keras.preprocessing.image.load_img", "tensorflow.keras.models.load_model", "tensorflow.keras.preprocessing.image.img_to_array", "numpy.vstack", "numpy.expand_dims" ] ]
tim885/DeepDepthRefiner
[ "055380e99f94206b5a098debca6c93aa274f9d29" ]
[ "testing.py" ]
[ "import argparse\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader\nimport torch.optim as optim\nimport os\nfrom tqdm import tqdm\nfrom PIL import Image\n\nimport matplotlib\nmatplotlib.use('agg') # use matplotlib without GUI support\nimport matplotlib.pyplot as plt\n\nfrom lib.models.unet import UNet\nfrom lib.datasets.ibims import Ibims\n\nfrom lib.utils.net_utils import load_checkpoint\nfrom lib.utils.evaluate_ibims_error_metrics import compute_global_errors, \\\n compute_depth_boundary_error, compute_directed_depth_error\n\n# =================PARAMETERS=============================== #\nparser = argparse.ArgumentParser()\n\n# network training procedure settings\nparser.add_argument('--use_normal', action='store_true', help='whether to use normal map as network input')\nparser.add_argument('--use_img', action='store_true', help='whether to use rgb image as network input')\nparser.add_argument('--use_occ', action='store_true', help='whether to use occlusion as network input')\nparser.add_argument('--no_contour', action='store_true', help='whether to remove the first channel of occlusion')\nparser.add_argument('--only_contour', action='store_true', help='whether to keep only the first channel of occlusion')\n\nparser.add_argument('--th', type=float, default=0.5)\nparser.add_argument('--lr', type=float, default=0.0001, help='learning rate of optimizer')\n\n# pth settings\nparser.add_argument('--checkpoint', type=str, default=None, help='optional reload model path')\nparser.add_argument('--result_dir', type=str, default='result', help='result folder')\n\n# dataset settings\nparser.add_argument('--val_dir', type=str, default='/space_sdd/ibims', help='testing dataset')\nparser.add_argument('--val_method', type=str, default='junli')\nparser.add_argument('--val_label_dir', type=str, default='contour_pred')\nparser.add_argument('--val_label_ext', type=str, default='-rgb-order-pix.npy')\n\nopt = parser.parse_args()\nprint(opt)\n# ========================================================== #\n\n\n# =================CREATE DATASET=========================== #\ndataset_val = Ibims(opt.val_dir, opt.val_method, th=opt.th, label_dir=opt.val_label_dir, label_ext=opt.val_label_ext)\nval_loader = DataLoader(dataset_val, batch_size=1, shuffle=False)\n\nwith open('/space_sdd/ibims/imagelist.txt') as f:\n image_names = f.readlines()\nimage_names = [x.strip() for x in image_names]\n# ========================================================== #\n\n\n# ================CREATE NETWORK AND OPTIMIZER============== #\nnet = UNet(use_occ=opt.use_occ, no_contour=opt.no_contour, only_contour=opt.only_contour,\n use_aux=(opt.use_normal or opt.use_img))\noptimizer = optim.Adam(net.parameters(), lr=opt.lr)\n\nload_checkpoint(net, optimizer, opt.checkpoint)\n\nnet.cuda()\n# ========================================================== #\n\n\n# ===================== DEFINE TEST ======================== #\ndef test(data_loader, net, result_dir):\n # Initialize global and geometric errors ...\n num_samples = len(data_loader)\n rms = np.zeros(num_samples, np.float32)\n log10 = np.zeros(num_samples, np.float32)\n abs_rel = np.zeros(num_samples, np.float32)\n sq_rel = np.zeros(num_samples, np.float32)\n thr1 = np.zeros(num_samples, np.float32)\n thr2 = np.zeros(num_samples, np.float32)\n thr3 = np.zeros(num_samples, np.float32)\n\n dbe_acc = np.zeros(num_samples, np.float32)\n dbe_com = np.zeros(num_samples, np.float32)\n\n dde_0 = np.zeros(num_samples, np.float32)\n dde_m = np.zeros(num_samples, np.float32)\n dde_p = np.zeros(num_samples, np.float32)\n\n net.eval()\n with torch.no_grad():\n for i, data in enumerate(tqdm(data_loader)):\n # load data and label\n depth_gt, depth_coarse, occlusion, edge, normal, img = data\n depth_gt, depth_coarse, occlusion, normal, img = \\\n depth_gt.cuda(), depth_coarse.cuda(), occlusion.cuda(), normal.cuda(), img.cuda()\n\n # forward pass\n if opt.use_normal:\n aux = normal\n elif opt.use_img:\n aux = img\n else:\n aux = None\n depth_pred = net(depth_coarse, occlusion, aux).clamp(1e-9)\n\n # mask out invalid depth values\n valid_mask = (depth_gt != 0).float()\n gt_valid = depth_gt * valid_mask\n pred_valid = depth_pred * valid_mask\n init_valid = depth_coarse * valid_mask\n\n # get numpy array from torch tensor\n gt = gt_valid.squeeze().cpu().numpy()\n pred = pred_valid.squeeze().cpu().numpy()\n init = init_valid.squeeze().cpu().numpy()\n edge = edge.numpy()\n\n # save npy files\n np.save(os.path.join(result_dir, '{}_init.npy'.format(image_names[i])), init)\n np.save(os.path.join(result_dir, '{}_refine.npy'.format(image_names[i])), pred)\n np.save(os.path.join(result_dir, '{}_gt.npy'.format(image_names[i])), gt)\n\n gt_name = os.path.join(result_dir, '{}_gt.png'.format(image_names[i]))\n pred_name = os.path.join(result_dir, '{}_refine.png'.format(image_names[i]))\n init_name = os.path.join(result_dir, '{}_init.png'.format(image_names[i]))\n max_value = max(gt.max(), pred.max(), init.max())\n plt.imsave(gt_name, gt, vmin=0, vmax=max_value)\n plt.imsave(pred_name, pred, vmin=0, vmax=max_value)\n plt.imsave(init_name, init, vmin=0, vmax=max_value)\n\n gt_mm = Image.fromarray((gt * 1000).astype('int32'))\n gt_mm.save(os.path.join(result_dir, '{}_gt_mm.png'.format(image_names[i])))\n refine_mm = Image.fromarray((pred * 1000).astype('int32'))\n refine_mm.save(os.path.join(result_dir, '{}_refine_mm.png'.format(image_names[i])))\n init_mm = Image.fromarray((init * 1000).astype('int32'))\n init_mm.save(os.path.join(result_dir, '{}_init_mm.png'.format(image_names[i])))\n\n\n gt_vec = gt.flatten()\n pred_vec = pred.flatten()\n\n abs_rel[i], sq_rel[i], rms[i], log10[i], thr1[i], thr2[i], thr3[i] = compute_global_errors(gt_vec, pred_vec)\n dbe_acc[i], dbe_com[i], est_edges = compute_depth_boundary_error(edge, pred)\n dde_0[i], dde_m[i], dde_p[i] = compute_directed_depth_error(gt_vec, pred_vec, 3.0)\n\n return abs_rel, sq_rel, rms, log10, thr1, thr2, thr3, dbe_acc, dbe_com, dde_0, dde_m, dde_p\n# ========================================================== #\n\n\n# save refined depth predictions\nsession_name = os.path.basename(os.path.dirname(opt.checkpoint))\ntesting_mode = 'gt' if opt.val_label_dir == 'label' else 'pred'\nresult_dir = os.path.join(opt.result_dir, session_name, opt.val_method, testing_mode)\nif not os.path.exists(result_dir):\n os.makedirs(result_dir)\n\nabs_rel, sq_rel, rms, log10, thr1, thr2, thr3, dbe_acc, dbe_com, dde_0, dde_m, dde_p = test(val_loader, net, result_dir)\nprint('############ Global Error Metrics #################')\nprint('rel = ', np.nanmean(abs_rel))\nprint('log10 = ', np.nanmean(log10))\nprint('rms = ', np.nanmean(rms))\nprint('thr1 = ', np.nanmean(thr1))\nprint('thr2 = ', np.nanmean(thr2))\nprint('thr3 = ', np.nanmean(thr3))\nprint('############ Depth Boundary Error Metrics #################')\nprint('dbe_acc = ', np.nanmean(dbe_acc))\nprint('dbe_com = ', np.nanmean(dbe_com))\nprint('############ Directed Depth Error Metrics #################')\nprint('dde_0 = ', np.nanmean(dde_0)*100.)\nprint('dde_m = ', np.nanmean(dde_m)*100.)\nprint('dde_p = ', np.nanmean(dde_p)*100.)\n\n\n# log testing reults\nlogname = os.path.join(result_dir, 'testing_{}.txt'.format(testing_mode))\nwith open(logname, 'w') as f:\n f.write('############ Global Error Metrics #################\\n')\n f.write('rel = {:.3f}\\n'.format(np.nanmean(abs_rel)))\n f.write('log10 = {:.3f}\\n'.format(np.nanmean(log10)))\n f.write('rms = {:.3f}\\n'.format(np.nanmean(rms)))\n f.write('thr1 = {:.3f}\\n'.format(np.nanmean(thr1)))\n f.write('thr2 = {:.3f}\\n'.format(np.nanmean(thr2)))\n f.write('thr3 = {:.3f}\\n'.format(np.nanmean(thr3)))\n f.write('############ Depth Boundary Error Metrics #################\\n')\n f.write('dbe_acc = {:.3f}\\n'.format(np.nanmean(dbe_acc)))\n f.write('dbe_com = {:.3f}\\n'.format(np.nanmean(dbe_com)))\n f.write('############ Directed Depth Error Metrics #################\\n')\n f.write('dde_0 = {:.3f}\\n'.format(np.nanmean(dde_0) * 100.))\n f.write('dde_m = {:.3f}\\n'.format(np.nanmean(dde_m) * 100.))\n f.write('dde_p = {:.3f}\\n\\n'.format(np.nanmean(dde_p) * 100.))\n" ]
[ [ "matplotlib.use", "numpy.zeros", "matplotlib.pyplot.imsave", "torch.no_grad", "numpy.nanmean", "torch.utils.data.DataLoader" ] ]
sybitetechnologies/c-bot
[ "1f759e346170e031fa4307307f089e26fd7dd7a4" ]
[ "bot/hardware/complex_hardware/generic_blocks.py" ]
[ "import cv2\nimport numpy as np\nimport sys\nimport os\nfrom math import sin,cos,pi,copysign,tan,sqrt,hypot\n\nAREA_THRESHOLD=500\n\nFOV=59\n\nBLOCK=1.5 \n\n\n#Finds the blocks\ndef internal_find_blocks(img):\n hsv = cv2.cvtColor(img, cv2.cv.CV_BGR2HSV)\n\n hsv[:,:,1] = 255\n hsv[:,:,2] = 255\n\n \n hsv=cv2.cvtColor(hsv, cv2.cv.CV_HSV2BGR)\n \n\n for i in range(5):\n hsv = cv2.GaussianBlur(hsv,(3,3),0)\n\n valid = hsv[:,:,0] >= 220\n hsv = np.zeros(np.shape(valid), dtype=np.uint8)\n hsv[valid] = 255\n\n #hsv = cv2.inRange(hsv, (220,0,0), (255,255,255))\n \n contours = cv2.findContours(hsv, cv2.cv.CV_RETR_LIST, cv2.cv.CV_CHAIN_APPROX_SIMPLE)\n \n result=[]\n\n \n\n for c in contours[0]:\n if cv2.contourArea(c)>AREA_THRESHOLD:\n epsilon = 0.01*cv2.arcLength(c,True)\n approx = cv2.approxPolyDP(c,epsilon,True)\n rect = cv2.minAreaRect(c)\n box = cv2.cv.BoxPoints(rect)\n box = np.int0(box)\n box = np.reshape(box, (4,1,2))\n ratio=cv2.contourArea(approx)/cv2.contourArea(box)\n if 1:#ratio>.75: #THIS IS TO FILTER OUT BAD PARTICLES Not in use.\n rect = cv2.minAreaRect(box)\n elif ratio>.25:\n continue\n\n\n \n result.append(rect)\n return result\n\n#Does math on the blocks\ndef block_math(rect, img, actual_dist=0, centered=False):\n cx=rect[0][0]\n cy=rect[0][1]\n thetad=rect[2]\n theta=thetad/360*2*pi\n w=rect[1][0]/2.0\n h=rect[1][1]/2.0\n if abs(thetad)>45:\n temp=h\n h=w\n w=temp\n theta-=pi/2\n thetad-=90\n thetad+=90\n thetad=copysign(90,thetad)-thetad\n imgh,imgw,_=np.shape(img)\n w*=2\n h*=2\n\n if cx-w/2<10 or cx+w/2>imgw-10:return None\n\n rpp = pi/180*FOV/imgw\n \n dist = 1.5/2/tan(w*FOV*pi/180/imgw/2)\n\n if centered:actual_dist=dist\n \n if cx < imgw/2:\n hoffset = actual_dist * tan((cx-w/2-imgw/2)*rpp) + BLOCK/2\n else:\n hoffset = actual_dist * tan((cx+w/2-imgw/2)*rpp) - BLOCK/2\n\n if cy < imgh/2:\n voffset = actual_dist * tan((cy-h/2-imgh/2)*rpp) + BLOCK/2\n else:\n voffset = actual_dist * tan((cy+h/2-imgh/2)*rpp) - BLOCK/2\n \n return hoffset,-voffset,dist\n\n\n#Returns a list of the lateral offsets for each block found. (inches)\n#You probably want the one closest to 0.\n#Call this first and then compensate\n#Assume distance should be what is reported by the IR/distance sensors in inches\ndef get_lateral_offset(img,assume_dist):\n blocks=internal_find_blocks(img)\n if len(blocks)==0:return -1\n\n results=[]\n \n for rect in blocks: \n coords=block_math(rect,img,assume_dist)\n if coords is not None:results.append(coords[0])\n #return x offset of blocks\n results=sorted(results, key=lambda x: abs(x))\n return results\n\n#Returns coordinates for each block found.\n#Again, probably want the one closest to 0.\n#Call get_lateral_offset first and center.\n# format (dx,dy,dz) in inches from where the arm is now.\ndef get_front_center(img):\n blocks=internal_find_blocks(img)\n if len(blocks)==0:return -1\n\n results=[]\n \n for rect in blocks:\n coords=block_math(rect,img,centered=True)\n if coords is not None:results.append(coords)\n\n results=sorted(results, key=lambda x: abs(x[0]))\n\n return results\n #return location vectors\n\n \n\n\n \n" ]
[ [ "numpy.int0", "numpy.reshape", "numpy.shape" ] ]
giulio93/NeuralNetwork-Viterbi
[ "45a20cc85ac600bac15c1e218c1b1bf474aaeb5f" ]
[ "utils/length_model.py" ]
[ "#!/usr/bin/python2.7\n\nimport numpy as np\n\n\nclass LengthModel(object):\n \n def n_classes(self):\n return 0\n\n def score(self, length, label):\n return 0.0\n\n def max_length(self):\n return np.inf\n\n\nclass PoissonModel(LengthModel):\n \n def __init__(self, model, max_length = 2000, renormalize = True):\n super(PoissonModel, self).__init__()\n if type(model) == str:\n self.mean_lengths = np.loadtxt(model)\n else:\n self.mean_lengths = model\n self.num_classes = self.mean_lengths.shape[0]\n self.max_len = max_length\n self.poisson = np.zeros((max_length, self.num_classes))\n\n # precompute normalizations for mean length model\n self.norms = np.zeros(self.mean_lengths.shape)\n if renormalize:\n self.norms = np.round(self.mean_lengths) * np.log(np.round(self.mean_lengths)) - np.round(self.mean_lengths)\n for c in range(len(self.mean_lengths)):\n logFak = 0\n for k in range(2, int(self.mean_lengths[c])+1):\n logFak += np.log(k)\n self.norms[c] = self.norms[c] - logFak\n # precompute Poisson distribution\n self.poisson[0, :] = -np.inf # length zero can not happen\n logFak = 0\n for l in range(1, self.max_len):\n logFak += np.log(l)\n self.poisson[l, :] = l * np.log(self.mean_lengths) - self.mean_lengths - logFak - self.norms\n\n def n_classes(self):\n return self.num_classes\n\n def score(self, length, label):\n if length >= self.max_len:\n return -np.inf\n else:\n return self.poisson[length, label]\n\n def max_lengths(self):\n return self.max_len\n\n" ]
[ [ "numpy.log", "numpy.loadtxt", "numpy.zeros", "numpy.round" ] ]
mcuntz/partialwrap
[ "e6536aef443f34e0bb62b1a4d73d00d0d8d73853" ]
[ "tests/rastrigin2.py" ]
[ "# Rastrigin function a=10, b=2*pi\nimport numpy as np\ndef rastrigin1(x):\n return 10.*len(x) + np.sum(x**2 - 10.*np.cos(2.*np.pi*x))\n\n# read parameters\nwith open('params.txt', 'r') as fi:\n pdict = {}\n for line in fi:\n ll = line.split()\n if (len(ll) == 0) or ll[0].startswith('#'):\n continue\n pdict[ll[0]] = float(ll[2])\nx = np.array([ pdict[kk] for kk in sorted(pdict.keys()) ])\n\n# calc function\ny = rastrigin1(x)\n\n# write output file\nwith open('out.txt', 'w') as ff:\n print(y, file=ff)\n" ]
[ [ "numpy.cos" ] ]
LWhite027/PaddleBox
[ "311b3b44fc7d51d4d66d90ab8a3fc0d42231afda" ]
[ "python/paddle/fluid/tests/unittests/test_fleet_base_single.py" ]
[ "# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nimport os\ncuda_visible_devices = os.getenv('CUDA_VISIBLE_DEVICES')\nif cuda_visible_devices is None or cuda_visible_devices == \"\":\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\nelse:\n os.environ['CUDA_VISIBLE_DEVICES'] = cuda_visible_devices.split(',')[0]\nimport paddle\nimport paddle.distributed.fleet as fleet\nimport paddle.distributed.fleet.base.role_maker as role_maker\nimport paddle.fluid as fluid\nimport unittest\nimport paddle.nn as nn\n\n\nclass LinearNet(nn.Layer):\n def __init__(self):\n super(LinearNet, self).__init__()\n self._linear1 = nn.Linear(10, 10)\n self._linear2 = nn.Linear(10, 1)\n\n def forward(self, x):\n return self._linear2(self._linear1(x))\n\n\nclass TestFleetDygraphSingle(unittest.TestCase):\n def setUp(self):\n os.environ[\"PADDLE_TRAINER_ENDPOINTS\"] = \"127.0.0.1:36213\"\n os.environ[\"PADDLE_CURRENT_ENDPOINTS\"] = \"127.0.0.1:36213\"\n os.environ[\"PADDLE_TRAINERS_NUM\"] = \"1\"\n os.environ[\"PADDLE_TRAINER_ID\"] = \"0\"\n\n def test_dygraph_single(self):\n paddle.disable_static()\n fleet.init(is_collective=True)\n\n layer = LinearNet()\n loss_fn = nn.MSELoss()\n adam = paddle.optimizer.Adam(\n learning_rate=0.001, parameters=layer.parameters())\n\n adam = fleet.distributed_optimizer(adam)\n dp_layer = fleet.distributed_model(layer)\n for step in range(2):\n inputs = paddle.randn([10, 10], 'float32')\n outputs = dp_layer(inputs)\n labels = paddle.randn([10, 1], 'float32')\n loss = loss_fn(outputs, labels)\n loss = dp_layer.scale_loss(loss)\n loss.backward()\n adam.step()\n adam.clear_grad()\n\n\nclass TestFleetBaseSingleRunCollective(unittest.TestCase):\n def setUp(self):\n pass\n\n def gen_data(self):\n return {\n \"x\": np.random.random(size=(128, 32)).astype('float32'),\n \"y\": np.random.randint(\n 2, size=(128, 1)).astype('int64')\n }\n\n def test_single_run_collective_minimize(self):\n input_x = paddle.static.data(name=\"x\", shape=[-1, 32], dtype='float32')\n input_y = paddle.static.data(name=\"y\", shape=[-1, 1], dtype='int64')\n\n fc_1 = fluid.layers.fc(input=input_x, size=64, act='tanh')\n prediction = fluid.layers.fc(input=fc_1, size=2, act='softmax')\n cost = fluid.layers.cross_entropy(input=prediction, label=input_y)\n avg_cost = paddle.mean(x=cost)\n\n fleet.init(is_collective=True)\n optimizer = fluid.optimizer.SGD(learning_rate=0.001)\n optimizer = fleet.distributed_optimizer(optimizer)\n optimizer.minimize(avg_cost)\n\n place = fluid.CUDAPlace(0) if paddle.fluid.is_compiled_with_cuda(\n ) else fluid.CPUPlace()\n\n exe = fluid.Executor(place)\n exe.run(paddle.static.default_startup_program())\n\n for i in range(10):\n cost_val = exe.run(feed=self.gen_data(), fetch_list=[avg_cost.name])\n print(\"cost of step[{}] = {}\".format(i, cost_val))\n\n\nclass TestFleetBaseSingleRunPS(unittest.TestCase):\n def setUp(self):\n pass\n\n def gen_data(self):\n return {\n \"x\": np.random.random(size=(128, 32)).astype('float32'),\n \"y\": np.random.randint(\n 2, size=(128, 1)).astype('int64')\n }\n\n def test_single_run_ps_minimize(self):\n input_x = paddle.static.data(name=\"x\", shape=[-1, 32], dtype='float32')\n input_y = paddle.static.data(name=\"y\", shape=[-1, 1], dtype='int64')\n\n fc_1 = fluid.layers.fc(input=input_x, size=64, act='tanh')\n prediction = fluid.layers.fc(input=fc_1, size=2, act='softmax')\n cost = fluid.layers.cross_entropy(input=prediction, label=input_y)\n avg_cost = paddle.mean(x=cost)\n\n fleet.init()\n strategy = paddle.distributed.fleet.DistributedStrategy()\n optimizer = fluid.optimizer.SGD(learning_rate=0.01)\n optimizer = fleet.distributed_optimizer(optimizer, strategy=strategy)\n optimizer.minimize(avg_cost)\n if fleet.is_server():\n fleet.init_server()\n fleet.run_server()\n elif fleet.is_worker():\n place = fluid.CPUPlace()\n exe = fluid.Executor(place)\n exe.run(paddle.static.default_startup_program())\n step = 10\n for i in range(step):\n cost_val = exe.run(program=fluid.default_main_program(),\n feed=self.gen_data(),\n fetch_list=[avg_cost.name])\n print(\"worker_index: %d, step%d cost = %f\" %\n (fleet.worker_index(), i, cost_val[0]))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.random.random", "numpy.random.randint" ] ]
nasa/pretrained-microscopy-models
[ "c64ada1332a6eec842246c9a0250e9e0136f3818" ]
[ "pretrained_microscopy_models/losses.py" ]
[ "import torch.nn as nn\nimport torch.nn.functional as F\n\nclass DiceBCELoss(nn.Module):\n def __init__(self, weight=None, size_average=True):\n super(DiceBCELoss, self).__init__()\n self.weight = weight\n self.__name__ = 'DiceBCELoss'\n\n def forward(self, inputs, targets, smooth=1):\n \n #comment out if your model contains a sigmoid or equivalent activation layer\n inputs = F.sigmoid(inputs) \n \n #flatten label and prediction tensors\n inputs = inputs.view(-1)\n targets = targets.view(-1)\n \n intersection = (inputs * targets).sum() \n dice_loss = 1 - (2.*intersection + smooth)/(inputs.sum() + targets.sum() + smooth) \n BCE = F.binary_cross_entropy(inputs, targets, reduction='mean')\n Dice_BCE = self.weight * BCE + (1-self.weight) * dice_loss\n \n return Dice_BCE" ]
[ [ "torch.nn.functional.sigmoid", "torch.nn.functional.binary_cross_entropy" ] ]
lily-x/PAWS-public
[ "32f79d10a1187686f301be447de9f4d0e83cf127" ]
[ "planning/planning/src/Cluster.py" ]
[ "# Author: Gael Varoquaux <[email protected]>, Brian Cheung\n# License: BSD 3 clause\n\nimport time\n\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nfrom sklearn.feature_extraction import image\nfrom sklearn.cluster import spectral_clustering\n\n\ndef cluster(face):\n # Convert the image into a graph with the value of the gradient on the\n # edges.\n graph = image.img_to_graph(face)\n \n # Take a decreasing function of the gradient: an exponential\n # The smaller beta is, the more independent the segmentation is of the\n # actual image. For beta=1, the segmentation is close to a voronoi\n beta = 5\n eps = 1e-6\n graph.data = np.exp(-beta * graph.data / graph.data.std()) + eps\n \n # Apply spectral clustering (this step goes much faster if you have pyamg\n # installed)\n N_REGIONS = 25\n \n for assign_labels in ('kmeans', 'discretize'):\n t0 = time.time()\n labels = spectral_clustering(graph, n_clusters=N_REGIONS,\n assign_labels=assign_labels, random_state=1)\n t1 = time.time()\n labels = labels.reshape(face.shape)\n \n plt.figure(figsize=(5, 5))\n plt.imshow(face)\n for l in range(N_REGIONS):\n plt.contour(labels == l, contours=1,\n )\n plt.xticks(())\n plt.yticks(())\n title = 'Spectral clustering: %s, %.2fs' % (assign_labels, (t1 - t0))\n print(title)\n plt.title(title)\n plt.show()" ]
[ [ "sklearn.cluster.spectral_clustering", "matplotlib.pyplot.title", "matplotlib.pyplot.yticks", "matplotlib.pyplot.figure", "matplotlib.pyplot.show", "sklearn.feature_extraction.image.img_to_graph", "matplotlib.pyplot.contour", "matplotlib.pyplot.xticks", "matplotlib.pyplot.imshow" ] ]
giacomov/astromodels
[ "bfad6993465df66d9c071c00d6e0c747266bd3a7" ]
[ "astromodels/tests/test_point_source.py" ]
[ "from __future__ import division, print_function\n\nimport astropy.units as u\nimport numpy as np\nimport numpy.testing as npt\nimport pytest\n\nfrom astromodels.core.spectral_component import SpectralComponent\nfrom astromodels.functions import (Band, Blackbody, Exponential_cutoff,\n Log_parabola, Powerlaw)\nfrom astromodels.functions.functions_1D.functions import _ComplexTestFunction\n\ntry:\n from astromodels.functions import PhAbs, TbAbs, WAbs\n\n has_abs_models = True\n\nexcept:\n\n has_abs_models = False\n\n \nfrom astromodels.core.model import Model\nfrom astromodels.core.model_parser import clone_model, load_model\nfrom astromodels.sources.particle_source import ParticleSource\nfrom astromodels.sources.point_source import PointSource\n\ntry:\n\n from astromodels.xspec import XS_phabs, XS_powerlaw\n\nexcept:\n\n has_xspec = False\n\nelse:\n\n has_xspec = True\n\ntry:\n\n from astromodels.functions import EBLattenuation\n\nexcept:\n\n has_ebl = False\n\nelse:\n\n has_ebl = True\n\nfrom astromodels.functions.function import _known_functions\nfrom astromodels.functions.priors import *\n\n__author__ = 'giacomov'\n\n\n\n_multiplicative_models = [\"PhAbs\", \"TbAbs\", \"WAbs\", \"EBLattenuation\", \"ZDust\"]\n\ndef test_constructor():\n\n # RA, Dec and L,B of the same point in the sky\n\n ra, dec = (125.6, -75.3)\n l, b = (288.44190139183564, -20.717313145391525)\n\n # This should throw as we are using Powerlaw instead of Powerlaw()\n with pytest.raises(TypeError):\n\n _ = PointSource(\"my_source\", ra, dec, Powerlaw)\n\n # Init with RA, Dec\n\n point_source1 = PointSource('my_source',ra, dec, Powerlaw())\n\n assert point_source1.position.get_ra() == ra\n assert point_source1.position.get_dec() == dec\n\n assert abs(point_source1.position.get_l() - l) < 1e-7\n assert abs(point_source1.position.get_b() - b) < 1e-7\n\n assert point_source1.position.ra.value == ra\n assert point_source1.position.dec.value == dec\n\n # Verify that the position is fixed by default\n assert point_source1.position.ra.fix\n assert point_source1.position.dec.fix\n\n # Init with l,b\n\n point_source2 = PointSource('my_source', l=l, b=b, spectral_shape=Powerlaw())\n\n assert point_source2.position.get_l() == l\n assert point_source2.position.get_b() == b\n\n assert abs(point_source2.position.get_ra() - ra) < 1e-7\n assert abs(point_source2.position.get_dec() - dec) < 1e-7\n\n assert point_source2.position.l.value == l\n assert point_source2.position.b.value == b\n\n # Verify that the position is fixed by default\n assert point_source2.position.l.fix\n assert point_source2.position.b.fix\n\n # Multi-component\n\n po1 = Powerlaw()\n po2 = Powerlaw()\n\n c1 = SpectralComponent(\"component1\", po1)\n c2 = SpectralComponent(\"component2\", po2)\n\n point_source3 = PointSource(\"test_source\", ra, dec, components=[c1, c2])\n\n assert np.all(point_source3.spectrum.component1([1,2,3]) == po1([1,2,3]))\n assert np.all(point_source3.spectrum.component2([1,2,3]) == po2([1,2,3]))\n\n with pytest.raises(AssertionError):\n\n # Illegal RA\n\n _ = PointSource(\"test\",720.0, -15.0, components=[c1,c2])\n\n with pytest.raises(AssertionError):\n # Illegal Dec\n\n _ = PointSource(\"test\", 120.0, 180.0, components=[c1, c2])\n\n with pytest.raises(AssertionError):\n # Illegal l\n\n _ = PointSource(\"test\", l=-195, b=-15.0, components=[c1, c2])\n\n with pytest.raises(AssertionError):\n # Illegal b\n\n _ = PointSource(\"test\", l=120.0, b=-180.0, components=[c1, c2])\n\n\ndef test_call():\n\n # Multi-component\n\n po1 = Powerlaw()\n po2 = Powerlaw()\n\n c1 = SpectralComponent(\"component1\", po1)\n c2 = SpectralComponent(\"component2\", po2)\n\n point_source = PointSource(\"test_source\", 125.4, -22.3, components=[c1, c2])\n\n assert np.all(point_source.spectrum.component1([1, 2, 3]) == po1([1, 2, 3]))\n assert np.all(point_source.spectrum.component2([1, 2, 3]) == po2([1, 2, 3]))\n\n one = point_source.spectrum.component1([1, 2, 3])\n two = point_source.spectrum.component2([1, 2, 3])\n\n assert np.all( np.abs(one + two - point_source([1,2,3])) == 0 )\n\n\ndef test_call_with_units():\n\n po = Powerlaw()\n\n result = po(1.0)\n\n assert result.ndim == 0\n\n with pytest.raises(AssertionError):\n\n # This raises because the units of the function have not been set up\n\n _ = po(1.0 * u.keV)\n\n # Use the function as a spectrum\n ps = PointSource(\"test\",0,0,po)\n\n result = po(1.0 * u.keV)\n\n assert isinstance(result, u.Quantity)\n\n result = po(np.array([1,2,3])* u.keV)\n\n assert isinstance(result, u.Quantity)\n\n # Now test all the functions\n def test_one(class_type):\n\n if class_type == _ComplexTestFunction:\n \n instance = class_type(file_name=\"test.txt\")\n \n else:\n\n instance = class_type()\n \n if not instance.is_prior:\n\n # if we have fixed x_units then we will use those\n # in the test\n\n if instance.has_fixed_units():\n\n x_unit_to_use = instance.fixed_units[0]\n\n else:\n\n x_unit_to_use = u.keV\n \n # Use the function as a spectrum\n ps = PointSource(\"test\", 0, 0, instance)\n\n if instance.name in [ \"Synchrotron\", \"_ComplexTestFunction\" ]:\n\n # we should not do it this way\n\n p = Powerlaw()\n\n particleSource = ParticleSource(\"particles\", p)\n\n \n\n instance.set_particle_distribution(p)\n\n\n # elif instance.name in [\"PhAbs\", \"TbAbs\"]:\n\n # instance\n \n\n result = ps(1.0)\n\n assert isinstance(result, float)\n\n result = ps(1.0 * x_unit_to_use)\n\n assert isinstance(result, u.Quantity)\n\n result = ps(np.array([1, 2, 3]) * x_unit_to_use)\n\n assert isinstance(result, u.Quantity)\n \n if instance.name in [ \"Synchrotron\", \"_ComplexTestFunction\" ]:\n model = Model( particleSource, ps)\n \n \n else:\n model = Model( ps )\n \n new_model = clone_model( model )\n \n new_result = new_model[\"test\"](np.array([1, 2, 3]) * x_unit_to_use)\n \n assert np.all(new_result==result)\n\n model.save(\"__test.yml\", overwrite=True)\n \n new_model = load_model(\"__test.yml\")\n\n new_result = new_model[\"test\"](np.array([1, 2, 3]) * x_unit_to_use)\n \n assert np.all(new_result==result)\n\n else:\n\n print ('Skipping prior function')\n\n\n\n for key in _known_functions:\n\n this_function = _known_functions[key]\n\n # Test only the power law of XSpec, which is the only one we know we can test at 1 keV\n\n if key.find(\"XS\")==0 and key != \"XS_powerlaw\" or (key in _multiplicative_models):\n\n # An XSpec model. Test it only if it's a power law (the others might need other parameters during\n # initialization)\n\n continue\n\n if key.find(\"TemplateModel\")==0:\n\n # The TemplateModel function has its own test\n\n continue\n\n if key.find(\"Synchrotron\")==0:\n\n # Naima Synchtron function should have its own test\n\n continue\n\n if this_function._n_dim == 1:\n\n print(\"testing %s ...\" % key)\n\n test_one(_known_functions[key])\n\n\ndef test_call_with_composite_function_with_units():\n\n def one_test(spectrum):\n\n print(\"Testing %s\" % spectrum.expression)\n\n # # if we have fixed x_units then we will use those\n # # in the test\n #\n # if spectrum.expression.has_fixed_units():\n #\n # x_unit_to_use, y_unit_to_use = spectrum.expression.fixed_units[0]\n #\n # else:\n\n x_unit_to_use = u.keV\n\n pts = PointSource(\"test\", ra=0, dec=0, spectral_shape=spectrum)\n\n res = pts(np.array([100., 200.]) * x_unit_to_use)\n\n # This will fail if the units are wrong\n res.to(old_div(1, (u.keV * u.cm**2 * u.s)))\n\n # Test a simple composition\n\n spectrum = Powerlaw() * Exponential_cutoff()\n\n one_test(spectrum)\n\n spectrum = Band() + Blackbody()\n\n one_test(spectrum)\n\n # Test a more complicate composition\n\n spectrum = Powerlaw() * Exponential_cutoff() + Blackbody()\n\n one_test(spectrum)\n\n spectrum = Powerlaw() * Exponential_cutoff() * Exponential_cutoff() + Blackbody()\n\n one_test(spectrum)\n\n # test the absorption models\n\n if has_abs_models:\n \n spectrum = PhAbs() * Powerlaw()\n\n\n one_test(spectrum)\n\n spectrum = TbAbs() * Powerlaw()\n\n one_test(spectrum)\n\n\n spectrum = WAbs() * Powerlaw()\n\n one_test(spectrum)\n\n \n if has_xspec:\n\n spectrum = XS_phabs() * Powerlaw()\n\n one_test(spectrum)\n\n spectrum = XS_phabs() * XS_powerlaw()\n\n one_test(spectrum)\n\n spectrum = XS_phabs() * XS_powerlaw() * XS_phabs()\n\n one_test(spectrum)\n\n spectrum = XS_phabs() * XS_powerlaw() * XS_phabs() + Blackbody()\n\n one_test(spectrum)\n\n spectrum = XS_phabs() * XS_powerlaw() * XS_phabs() + XS_powerlaw()\n\n one_test(spectrum)\n \n if has_ebl:\n \n spectrum = Powerlaw() * EBLattenuation()\n \n one_test(spectrum)\n\n\ndef test_free_param():\n\n spectrum = Log_parabola()\n source = PointSource(\"test_source\", ra=123.4, dec=56.7, spectral_shape=spectrum)\n\n parameters = [spectrum.alpha, spectrum.beta, spectrum.piv, spectrum.K, source.position.ra, source.position.dec]\n\n for param in parameters:\n param.free = False\n\n assert not source.has_free_parameters\n \n assert len(source.free_parameters) == 0\n\n assert len(source.parameters) > len(source.free_parameters)\n \n for i, param in enumerate(parameters):\n param.free = True\n assert len(source.free_parameters) == i+1\n\n\n assert source.has_free_parameters\n\n\ndef test_local_deriv():\n\n p = Powerlaw(index=-2.)\n\n\n npt.assert_allclose(-2., p.local_spectral_index(np.logspace(1,3,10)))\n \n\n \n" ]
[ [ "numpy.all", "numpy.array", "numpy.logspace" ] ]
soma2000-lang/tensorflow-image-models
[ "2e290cedb3ea944d0fa4ec0c77a3d7c72d8eaf6c" ]
[ "tests/test_architectures.py" ]
[ "import os\n\nimport numpy as np\nimport pytest\nimport tensorflow as tf\nimport timm\nimport torch\n\nfrom tfimm import create_model, list_models\nfrom tfimm.utils.timm import load_pytorch_weights_in_tf2_model\n\n# Exclude models that cause specific test failures\nif \"GITHUB_ACTIONS\" in os.environ: # and 'Linux' in platform.system():\n EXCLUDE_FILTERS = [\n \"cait_m*\",\n \"convnext_xlarge_*\",\n \"ig_resnext101_32x48d\",\n \"resnetv2_50x3_*\",\n \"resnetv2_101*\",\n \"resnetv2_152*\",\n \"vit_large_*\",\n \"vit_huge_*\",\n ]\nelse:\n EXCLUDE_FILTERS = [\"cait_m*\"]\n\nTIMM_ARCHITECTURES = list(\n set(list_models(exclude_filters=EXCLUDE_FILTERS)) & set(timm.list_models())\n)\n\n\[email protected]()\[email protected](\"model_name\", list_models(exclude_filters=EXCLUDE_FILTERS))\ndef test_mixed_precision(model_name: str):\n \"\"\"\n Test if we can run a forward pass with mixed precision.\n\n These tests are very slow on CPUs, so we skip them by default.\n \"\"\"\n tf.keras.backend.clear_session()\n tf.keras.mixed_precision.set_global_policy(\"mixed_float16\")\n model = create_model(model_name)\n img = tf.ones((1, *model.cfg.input_size, model.cfg.in_channels), dtype=\"float16\")\n res = model(img)\n assert res.dtype == \"float16\"\n\n\[email protected](\"model_name\", TIMM_ARCHITECTURES)\[email protected](60)\ndef test_load_timm_model(model_name: str):\n \"\"\"Test if we can load models from timm.\"\"\"\n # We don't need to load the pretrained weights from timm, we only need a PyTorch\n # model, that we then convert to tensorflow. This allows us to run these tests\n # in GitHub CI without data transfer issues.\n pt_model = timm.create_model(model_name, pretrained=False)\n pt_model.eval()\n\n tf_model = create_model(model_name, pretrained=False)\n load_pytorch_weights_in_tf2_model(tf_model, pt_model.state_dict())\n\n rng = np.random.default_rng(2021)\n img = rng.random(\n size=(1, *tf_model.cfg.input_size, tf_model.cfg.in_channels), dtype=\"float32\"\n )\n tf_res = tf_model(img, training=False).numpy()\n\n pt_img = torch.Tensor(img.transpose([0, 3, 1, 2]))\n pt_res = pt_model.forward(pt_img).detach().numpy()\n\n if model_name.startswith(\"deit_\") and \"distilled\" in model_name:\n # During inference timm distilled models return average of both heads, while\n # we return both heads\n tf_res = tf.reduce_mean(tf_res, axis=1)\n\n # The tests are flaky sometimes, so we use a quite high tolerance\n assert (np.max(np.abs(tf_res - pt_res))) / (np.max(np.abs(pt_res)) + 1e-6) < 1e-3\n\n\[email protected](\"model_name\", list_models(module=\"convnext\", exclude_filters=EXCLUDE_FILTERS))\[email protected](60)\ndef test_feature_extraction(model_name: str):\n \"\"\"\n Tests if we can create a model and run inference with `return_features` set to\n both `True` and `False.\n \"\"\"\n model = create_model(model_name, pretrained=False)\n\n inputs = model.dummy_inputs\n x1, features = model(inputs, return_features=True)\n x2 = model(inputs, return_features=False)\n\n # Check that return value doesn't change if we also want features\n x1, x2 = x1.numpy(), x2.numpy()\n assert np.max(np.abs(x1 - x2)) < 1e-6\n\n # Check that features dict contains exactly the expected keys\n assert set(features.keys()) == set(model.feature_names)\n" ]
[ [ "tensorflow.keras.mixed_precision.set_global_policy", "tensorflow.ones", "numpy.random.default_rng", "tensorflow.keras.backend.clear_session", "numpy.abs", "tensorflow.reduce_mean" ] ]
f-koehler/compsens
[ "1cdcc37ce63b3b242cfef4fd16e98f4464913dbc" ]
[ "compsens/common.py" ]
[ "import numpy\n\n\ndef check_sanity(t, w_min, w_max):\n dt = compute_dt(t)\n t_final = max(t)\n\n dt_required = 2 * numpy.pi / (3 * w_max)\n t_final_required = 2 * numpy.pi / w_min\n\n # check temporal resolution\n if dt >= dt_required:\n raise ValueError(\"temporal spacing too large: dt={}≮{}\".format(\n dt, dt_required))\n\n # check signal length\n if t_final <= t_final_required:\n raise ValueError(\"final time too small: t_final={}≯{}\".format(\n t_final, t_final_required))\n\n\ndef check_underdetermined(N_t, N_w):\n if N_t >= 2 * N_w:\n raise RuntimeError(\n \"only N_t={} time points allowed for these parameters\".format(\n 2 * N_w - 1))\n\n\ndef compute_A_matrix(N_t, N_w, dt, dw):\n eta = dt * dw\n index_products = numpy.outer(numpy.arange(0, N_t), numpy.arange(0, N_w))\n return numpy.block(\n [numpy.cos(eta * index_products),\n numpy.sin(eta * index_products)])\n\n\ndef compute_dt(t):\n dt = numpy.unique(numpy.around(numpy.diff(t), 10))\n if len(numpy.unique(dt)) > 1:\n raise ValueError(\"time points are not equidistant: \" + str(dt))\n return dt[0]\n\n\ndef get_method(method):\n # check for valid method\n method = method.upper()\n if method not in [\"BP\", \"QP\", \"LS\"]:\n raise ValueError(\n \"invalid method {}, choose from: BP, QP, and LS\".format(method))\n\n return method\n\n\ndef prepare_signal(t, signal):\n # create working copies\n t = numpy.copy(t)\n signal = numpy.copy(signal)\n\n # sort by time\n permutation = t.argsort()\n t = t[permutation]\n signal = signal[permutation]\n\n return t, signal\n" ]
[ [ "numpy.sin", "numpy.copy", "numpy.diff", "numpy.arange", "numpy.cos", "numpy.unique" ] ]
moonson619/AI4Water-1
[ "285d46824502b6a787e42570b72432f4f6acf45e" ]
[ "tests/test_postprocessing/test_SeqMetrics/test_regression.py" ]
[ "import os\nimport unittest\nimport site # so that ai4water directory is in path\n\nai4_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nprint('ai4w_dir', ai4_dir)\nsite.addsitedir(ai4_dir)\n\nimport numpy as np\n\nfrom ai4water.postprocessing.SeqMetrics import plot_metrics\nfrom ai4water.postprocessing.SeqMetrics.utils import list_subclass_methods\nfrom ai4water.postprocessing.SeqMetrics import RegressionMetrics\n\n\nt = np.random.random((20, 1))\np = np.random.random((20, 1))\n\ner = RegressionMetrics(t, p)\n\nall_errors = er.calculate_all()\n\nnot_metrics = ['calculate_all',\n 'stats',\n \"treat_arrays\",\n \"scale_free_metrics\",\n \"scale_dependent_metrics\",\n \"composite_metrics\",\n \"relative_metrics\",\n \"percentage_metrics\"]\n\n\nclass test_errors(unittest.TestCase):\n\n def test_radial_pots(self):\n plot_metrics(all_errors,\n plot_type='bar',\n max_metrics_per_fig=50,\n save_path=os.path.join(os.getcwd(), \"results\"),\n show=False)\n plot_metrics(all_errors,\n plot_type='radial',\n save_path=os.path.join(os.getcwd(), \"results\"),\n show=False)\n return\n\n def test_attrs(self):\n for _attr in not_metrics:\n assert _attr not in er.all_methods\n\n def test_calculate_all(self):\n assert len(all_errors) > 100\n for er_name, er_val in all_errors.items():\n if er_val is not None:\n er_val = getattr(er, er_name)()\n self.assertEqual(er_val.__class__.__name__, 'float', f'{er_name} is {er_val}')\n return\n\n def test_stats(self):\n s = er.stats()\n assert len(s) > 1.0\n return\n\n def test_mrae(self):\n assert er.mare() * 100.0 == er.mape()\n return\n\n def test_mare(self):\n # https://support.numxl.com/hc/en-us/articles/115001223363-MRAE-Mean-Relative-Absolute-Error\n data = np.array(\n [[-2.9, \t-2.95],\n [-2.83, \t-2.7],\n [-0.95, \t-1.00],\n [-0.88, \t-0.68],\n [1.21,\t1.50],\n [-1.67, \t-1.00],\n [0.83, \t0.90],\n [-0.27, \t-0.37],\n [1.36, \t1.26],\n [-0.34, \t-0.54],\n [0.48, \t0.58],\n [-2.83, \t-2.13],\n [-0.95, \t-0.75],\n [-0.88, \t-0.89],\n [1.21, \t1.25],\n [-1.67, \t-1.65],\n [-2.99, \t-3.20],\n [1.24, \t1.29],\n [0.64, \t0.60]]\n )\n errs = RegressionMetrics(data[:, 0], data[:, 1])\n np.testing.assert_almost_equal(0.348, errs.mrae(), 2)\n assert errs.mare() * 100.0 == errs.mape()\n return\n\n def test_hydro_metrics(self):\n hydr_metrics = er.calculate_hydro_metrics()\n assert len(hydr_metrics) == len(er._hydro_metrics())\n return\n\n def test_minimal(self):\n minimal_metrics = er.calculate_minimal()\n assert len(minimal_metrics) == len(er._minimal())\n return\n\n def test_scale_dependent(self):\n minimal_metrics = er.calculate_scale_dependent_metrics()\n assert len(minimal_metrics) == len(er._scale_dependent_metrics())\n return\n\n def test_scale_independent(self):\n minimal_metrics = er.calculate_scale_independent_metrics()\n assert len(minimal_metrics) == len(er._scale_independent_metrics())\n return\n\n def test_list_subclass_methods(self):\n class DP:\n def _pa(self): pass\n\n class D(DP):\n def a(self): pass\n def _a(self): pass\n def b(self): pass\n\n self.assertEqual(len(list_subclass_methods(D, True)), 2)\n self.assertEqual(len(list_subclass_methods(D, True, False)), 3)\n self.assertEqual(len(list_subclass_methods(D, True, False, ['b'])), 2)\n return\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.random.random", "numpy.array" ] ]
Ir1d/kornia
[ "0ed0099a84261a6421f98c65924c746fe933ad74" ]
[ "kornia/color/xyz.py" ]
[ "from typing import Union\n\nimport torch\nimport torch.nn as nn\n\n\nclass RgbToXyz(nn.Module):\n r\"\"\"Converts an image from RGB to XYZ\n\n The image data is assumed to be in the range of (0, 1).\n\n args:\n image (torch.Tensor): RGB image to be converted to XYZ.\n returns:\n torch.Tensor: XYZ version of the image.\n shape:\n - image: :math:`(*, 3, H, W)`\n - output: :math:`(*, 3, H, W)`\n Examples:\n >>> input = torch.rand(2, 3, 4, 5)\n >>> xyz = kornia.color.RgbToXyz()\n >>> output = xyz(input) # 2x3x4x5\n Reference:\n [1] https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html\n \"\"\"\n\n def __init__(self) -> None:\n super(RgbToXyz, self).__init__()\n\n def forward(self, image: torch.Tensor) -> torch.Tensor: # type: ignore\n return rgb_to_xyz(image)\n\n\nclass XyzToRgb(nn.Module):\n r\"\"\"Converts an image from XYZ to RGB\n\n args:\n image (torch.Tensor): XYZ image to be converted to RGB.\n returns:\n torch.Tensor: RGB version of the image.\n shape:\n - image: :math:`(*, 3, H, W)`\n - output: :math:`(*, 3, H, W)`\n Examples:\n >>> input = torch.rand(2, 3, 4, 5)\n >>> rgb = kornia.color.XyzToRgb()\n >>> output = rgb(input) # 2x3x4x5\n Reference:\n [1] https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html\n \"\"\"\n\n def __init__(self) -> None:\n super(XyzToRgb, self).__init__()\n\n def forward(self, image: torch.Tensor) -> torch.Tensor: # type: ignore\n return xyz_to_rgb(image)\n\n\ndef rgb_to_xyz(image: torch.Tensor) -> torch.Tensor:\n r\"\"\"Converts a RGB image to XYZ.\n\n See :class:`~kornia.color.RgbToXyz` for details.\n\n Args:\n image (torch.Tensor): RGB Image to be converted to XYZ.\n\n Returns:\n torch.Tensor: XYZ version of the image.\n \"\"\"\n\n if not torch.is_tensor(image):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(image)))\n\n if len(image.shape) < 3 or image.shape[-3] != 3:\n raise ValueError(\"Input size must have a shape of (*, 3, H, W). Got {}\"\n .format(image.shape))\n\n r: torch.Tensor = image[..., 0, :, :]\n g: torch.Tensor = image[..., 1, :, :]\n b: torch.Tensor = image[..., 2, :, :]\n\n x: torch.Tensor = 0.412453 * r + 0.357580 * g + 0.180423 * b\n y: torch.Tensor = 0.212671 * r + 0.715160 * g + 0.072169 * b\n z: torch.Tensor = 0.019334 * r + 0.119193 * g + 0.950227 * b\n\n out: torch.Tensor = torch.stack((x, y, z), -3)\n\n return out\n\n\ndef xyz_to_rgb(image: torch.Tensor) -> torch.Tensor:\n r\"\"\"Converts a XYZ image to RGB.\n\n See :class:`~kornia.color.XyzToRgb` for details.\n\n Args:\n image (torch.Tensor): XYZ Image to be converted to RGB.\n\n Returns:\n torch.Tensor: RGB version of the image.\n \"\"\"\n if not torch.is_tensor(image):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(image)))\n\n if len(image.shape) < 3 or image.shape[-3] != 3:\n raise ValueError(\"Input size must have a shape of (*, 3, H, W). Got {}\"\n .format(image.shape))\n\n x: torch.Tensor = image[..., 0, :, :]\n y: torch.Tensor = image[..., 1, :, :]\n z: torch.Tensor = image[..., 2, :, :]\n\n r: torch.Tensor = 3.2404813432005266 * x + -1.5371515162713185 * y + -0.4985363261688878 * z\n g: torch.Tensor = -0.9692549499965682 * x + 1.8759900014898907 * y + 0.0415559265582928 * z\n b: torch.Tensor = 0.0556466391351772 * x + -0.2040413383665112 * y + 1.0573110696453443 * z\n\n out: torch.Tensor = torch.stack((r, g, b), dim=-3)\n\n return out\n" ]
[ [ "torch.is_tensor", "torch.stack" ] ]
arthurwozniak/CaptchaBreaker
[ "697daa0bc592bf3ac7b4711d821c4387b129b334" ]
[ "captchabreaker/modifier.py" ]
[ "# coding=utf-8\nimport cv2\nimport numpy as np\nimport base64\n\n\ndef split_joined_boxes(image, boxes, count):\n number_of_splits = count - len(boxes)\n minimas = find_minimas(image)\n splits_values = sorted(calculate_boxes_splits(boxes, minimas), key=lambda box: box['cut_value'])\n return map(lambda box: box['minimum'], splits_values[0:number_of_splits + 1])\n\ndef calculate_boxes_splits(boxes, minimas):\n result = []\n for minimum in minimas:\n box = select_box(boxes, minimum['x'])\n if box is None:\n continue\n else:\n result.append({'box': box, 'minimum': minimum})\n\n return calculate_cut_values(result)\n\ndef calculate_cut_values(result):\n for box in result:\n box['cut_value'] = ((box['minimum']['x'] - box['box'][0]) - ((box['box'][0] + box['box'][2]) - box['minimum']['x'])) / 2\n return result\n\n\ndef select_box(boxes, x):\n for box in boxes:\n if (box[0] < x) and (x < (box[0] + box[2])):\n return box\n\n\n# returns list of tuples [x-position, projection-size]\ndef find_minimas(image):\n projection = np.sum(image, axis=0) / 255\n minimas = np.r_[True, projection[1:] < projection[:-1]] & np.r_[projection[:-1] < projection[1:], True]\n return [{'x': x, 'projection': projection[x]} for x in range(len(minimas)) if minimas[x] and (projection[x] < 10)]\n\n\n# Old code, should be reviewed\ndef split_joined_characters(image, boxes):\n projection = np.sum(image, axis=0) / 255\n minimas = np.r_[True, projection[1:] < projection[:-1]] & np.r_[projection[:-1] < projection[1:], True]\n return [[x, projection[x]] for x in range(len(minimas)) if minimas[x] and (projection[x] < 10)]\n\n\ndef intersection(a, b):\n x = max(a[0], b[0])\n y = max(a[1], b[1])\n w = min(a[0] + a[2], b[0] + b[2]) - x\n h = min(a[1] + a[3], b[1] + b[3]) - y\n if w < 0 or h < 0:\n return (0, 0, 0, 0) # or (0,0,0,0) ?\n return (x, y, w, h)\n\n\ndef get_letters(image, boxes):\n image = image.copy()\n # Z původního obrázku vyřežeme jednotlivé číslice\n letters = []\n for i in boxes:\n x, y, w, h = i\n # cv2.rectangle(im2, (x, y), (x + w, y + h), (0, 255, 0), 1)\n letters.append([x, cv2.resize(src=image[y:y + h, x:x + w], dsize=(20, 20), interpolation=cv2.INTER_NEAREST)])\n # Číslice seřadíme podle osy X\n letters = sorted(letters, key=lambda img: img[0])\n\n letters = list(map(lambda img: img[1], letters))\n return letters\n\n\ndef get_contours(image):\n # Najdeme obdélníky ohraničující spojité plochy v obrázku\n contours, hierarchy = cv2.findContours(\n image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n return contours\n\n\ndef contours_to_boxes(contours):\n return list(map(cv2.boundingRect, contours))\n\n\ndef remove_overlapping_boxes(boxes, count):\n while (len(boxes) > count):\n areas = [intersection(boxes[i], boxes[i + 1]) for i in range(len(boxes) - 1)]\n i = areas.index(max(areas, key=lambda x: x[2] * x[3]))\n r1 = boxes[i]\n r2 = boxes[i + 1]\n\n if r1[2] * r1[3] > r2[2] * r2[3]:\n boxes.pop(i + 1)\n else:\n boxes.pop(i)\n return boxes\n\n\n# box has structure (x-offset, y-offset, width, height)\ndef select_biggest_areas(boxes, count):\n return sorted(boxes, key=lambda box: box[2] * box[3])[-count:]\n\n\ndef blob_to_img(data):\n nparr = np.fromstring(base64.b64decode(data), np.uint8)\n img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n return img\n\n\ndef bin_to_img(data):\n nparr = np.fromstring(data, np.uint8)\n img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n return img\n\n\ndef find_contours(image, count):\n boxes = contours_to_boxes(get_contours(image))\n\n if len(boxes) < count:\n for minimum in split_joined_boxes(image, boxes, count):\n cv2.line(image, (minimum['x'], 0), (minimum['x'], image.shape[1]), (0, 0, 0), 1)\n boxes = contours_to_boxes(get_contours(image))\n boxes = select_biggest_areas(boxes, count)\n\n return sorted(boxes, key=lambda box: box[0])\n\n\ndef find_boxes(image, count):\n return find_contours(image, count)\n contours = get_contours(image)\n if len(contours) > count:\n contours = select_biggest_areas(contours, count)\n\n boxes = contours_to_boxes(contours)\n\n if len(boxes) < count:\n res = split_joined_characters(image, boxes)\n for i in res:\n cv2.line(image, (i[0], 0), (i[0], image.shape[1]), (0, 0, 0), 1)\n contours = get_contours(image.copy())\n boxes = contours_to_boxes(contours)\n\n return boxes\n\n\ndef find_boxes_old(image, lettersCount):\n contours = get_contours(image)\n\n if len(contours) > lettersCount:\n select_biggest_areas(contours, lettersCount)\n\n boxes = contours_to_boxes(contours)\n\n if len(boxes) > lettersCount:\n boxes = remove_overlapping_boxes(boxes, lettersCount)\n\n if len(boxes) < lettersCount:\n res = split_joined_characters(image, boxes)\n for i in res:\n cv2.line(image, (i[0], 0), (i[0], image.shape[1]), (0, 0, 0), 1)\n contours = get_contours(image.copy())\n boxes = contours_to_boxes(contours)\n\n return boxes\n\n\ndef draw_boxes(image, boxes):\n image = cv2.cvtColor(image.copy(), cv2.COLOR_GRAY2RGB)\n for i in boxes:\n x, y, w, h = i\n cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 1)\n return image\n\n\ndef img_to_base64(image):\n img_bytes = cv2.imencode('.png', image)[1].tobytes()\n return base64.b64encode(img_bytes).decode('utf-8')\n" ]
[ [ "numpy.sum", "numpy.fromstring" ] ]
draxtic/2048-api
[ "70f42a232fd8617b471cfce802d9135dc1ec2bb3" ]
[ "train.py" ]
[ "from game2048.agents import ExpectiMaxAgent as TestAgent\r\nfrom game2048.expectimax import board_to_move\r\nimport numpy as np\r\nimport math\r\nimport keras\r\nimport random\r\nfrom game2048.game import Game\r\nfrom keras.models import Sequential, Model\r\nfrom keras.layers import Dense, Dropout, Flatten,BatchNormalization,Input\r\nfrom keras.layers import Conv2D, MaxPooling2D,concatenate,Activation\r\nfrom keras.optimizers import SGD,Adam\r\nfrom keras.utils import to_categorical\r\nfrom keras.models import load_model\r\nfrom keras import regularizers\r\nfrom keras.utils import plot_model\r\nfrom collections import namedtuple\r\n\r\ntest_size=1000\r\nDEEP=128\r\nflag=5000\r\nepoch_size=20000000\r\nbatch_size=64\r\ncapacity=40000\r\n\r\nmodelpath='model.h5'\r\nGuide = namedtuple('Guide',('state','action'))\r\nmax_d=16\r\n\r\nclass Guides:\r\n\r\n\tdef __init__(self,capacity):\r\n\t\tself.capacity=capacity\r\n\t\tself.memory=[]\r\n\t\tself.position=0\r\n\tdef push(self,*args):\r\n\t\tif len(self.memory)<self.capacity:\r\n\t\t\tself.memory.append(None)\r\n\t\tself.memory[self.position]=Guide(*args)\r\n\t\tself.position=(self.position+1)%self.capacity\r\n\tdef sample(self,batch_size):\r\n\t\treturn random.sample(self.memory,batch_size)\r\n\tdef ready(self,batch_size):\r\n\t\treturn len(self.memory)>batch_size\r\n\tdef _len_(self):\r\n\t\treturn len(self.memory)\r\n\r\nclass ModelWrapper:\r\n\tdef __init__(self,model,capacity):\r\n\t\tself.model=model\r\n\t\tself.memory=Guides(capacity)\r\n\t\tself.capacity=capacity\r\n\t\tself.training_step=0\r\n\t\tself.refresh=0\r\n\tdef predict(self,board):\r\n\t\tp=board.reshape(-1)\r\n\t\tdata_1=np.zeros((len(p)))\r\n\t\tfor i in range(len(p)):\r\n\t\t\tif p[i]!=0:\r\n\t\t\t\ttmp=int(math.log(p[i],2))\r\n\t\t\t\tdata_1[i]=tmp\r\n\t\tboard=np.reshape(data_1,(4,4))\r\n\t\tboard = to_categorical(board,max_d)\r\n\t\treturn self.model.predict(np.expand_dims(board,axis=0))\r\n\r\n\tdef move(self,game):\r\n\t\tohe_board=game.board\r\n\t\tsuggest=board_to_move(game.board)\r\n\t\tdirection=self.predict(game.board).argmax()\r\n\t\tgame.move(direction)\r\n\t\ta=random.randint(0,9)\r\n\t\tself.memory.push(ohe_board,suggest)\r\n\t\treturn game\r\n\tdef onehot(self,x,shape):\r\n\t\tp=x.reshape(-1)\r\n\t\tdata_1=np.zeros((len(p)))\r\n\t\tfor i in range(len(p)):\r\n\t\t\tif p[i]!=0:\r\n\t\t\t\ttmp=int(math.log(p[i],2))\r\n\t\t\t\tdata_1[i]=tmp\r\n\t\tdata=np.reshape(data_1,shape)\r\n\t\tdata=to_categorical(data,max_d)\r\n\t\treturn data\r\n\r\n\r\n\tdef train(self,batch,game):\r\n\t\tfrom game2048.game import Game\r\n\t\tif self.memory.ready(test_size) and self.refresh%batch_size==1:\t\r\n\t\t\tguides=self.memory.sample(batch)\r\n\t\t\tX=[]\r\n\t\t\tY=[]\r\n\t\t\tfor guide in guides:\r\n\t\t\t\tX.append(guide.state)\r\n\t\t\t\tohe_action=[0]*4\r\n\t\t\t\tohe_action[guide.action]=1\r\n\t\t\t\tY.append(ohe_action)\r\n\t\t\tX=self.onehot(np.array(X),(batch_size,4,4))\r\n\t\t\tloss,acc=self.model.train_on_batch(np.array(X), np.array(Y))\r\n\t\t\tif(self.training_step%500==1):\r\n\t\t\t\tguides=self.memory.sample(test_size)\r\n\t\t\t\tx_test=[]\r\n\t\t\t\ty_test=[]\r\n\t\t\t\tfor guide in guides:\r\n\t\t\t\t\tx_test.append(guide.state)\r\n\t\t\t\t\tohe_action=[0]*4\r\n\t\t\t\t\tohe_action[guide.action]=1\r\n\t\t\t\t\ty_test.append(ohe_action)\r\n\t\t\t\tx_test=self.onehot(np.array(x_test),(test_size,4,4))\r\n\t\t\t\tprint(type(x_test))\r\n\t\t\t\tscore= model.evaluate(x_test, y_test, verbose=1)\r\n\t\t\t\twith open('oldtrainvalue.txt','a') as f:\r\n\t\t\t\t\tf.write(\"\\nmyagent\")\r\n\t\t\t\t\tf.write(\"loss\"+str(score[0]))\r\n\t\t\t\t\tf.write(\"accuracy\"+str(score[1]))\r\n\t\t\tself.training_step+=1\r\n\t\t\tgame=self.move(game)\r\n\t\t\tself.refresh+=1\r\n\t\t\treturn game\r\n\t\telse:\r\n\t\t\tgame=self.move(game)\r\n\t\t\tself.refresh+=1\r\n\t\t\treturn game\r\n\r\ninputs=Input((4,4,max_d))\r\nconv=inputs\r\nconv21=(Conv2D(DEEP, (2, 1), kernel_initializer='he_uniform')(conv))\r\nconv12=(Conv2D(DEEP, (1, 2), kernel_initializer='he_uniform')(conv))\r\nconv22=(Conv2D(DEEP, (2, 2), kernel_initializer='he_uniform')(conv))\r\nconv33=(Conv2D(DEEP, (3, 3), kernel_initializer='he_uniform')(conv))\r\nconv44=(Conv2D(DEEP, (4, 4), kernel_initializer='he_uniform')(conv))\r\nhidden=concatenate([Flatten()(conv21), Flatten()(conv12), Flatten()(conv22), Flatten()(conv33), Flatten()(conv44)])\r\nx = BatchNormalization()(hidden)\r\nx = Activation('relu')(x)\r\nprint(type(x))\r\nx=Dense(1024, kernel_initializer='he_uniform',activation='relu')(x)\r\nx=BatchNormalization()(x)\r\nx=Dense(128, kernel_initializer='he_uniform',activation='relu')(x)\r\nx=BatchNormalization()(x)\r\noutputs=Dense(4,activation='softmax',kernel_regularizer=regularizers.l2(0.01),activity_regularizer=regularizers.l1(0.001))(x)\r\nmodel=Model(inputs,outputs)\r\nmodel.summary()\r\n\r\nmodel.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])\r\nM1=ModelWrapper(model,capacity)\r\n\r\ngame = Game(4, 2048)\r\nwhile M1.training_step<epoch_size:\r\n\tif(game.board.max()<=2048 and game.board.min()==0):\r\n\t\tgame=M1.train(batch_size,game)\r\n\telse:\r\n\t\tgame = Game(4, 2048)\r\n\t\tgame=M1.train(batch_size,game)\r\n\t\tprint(\"new game\",str(game.board.max()))\r\n\tif(M1.training_step==flag):\r\n\t\tmodel.save(\"./k_model/CNN\"+str(round(M1.training_step/10000)+200)+\".h5\")\r\n\t\tflag+=5000\r\n\t\twith open('oldtrainvalue.txt','a') as f:\r\n\t\t\tf.write(\"\\nnewmodel\")\r\n\t\t\tf.write(\"\\n./k_model/CNN\"+str(round(M1.training_step/10000)+200)+\".h5\")\r\n\r\n" ]
[ [ "numpy.array", "numpy.reshape", "numpy.expand_dims" ] ]
m-zayan/notebooks
[ "999fdeb4a11a6b673cacb153238ed259608709d4" ]
[ "utils/test_utils/test_plots.py" ]
[ "import numpy as np\nimport tensorflow as tf\n\nfrom ..random import random_indices\nfrom ..plot_utils import grid_plot\n\n__all__ = ['test_grid_plot_mnist']\n\n\ndef test_grid_plot_mnist():\n\n (_, _), (x_test, y_test) = tf.keras.datasets.mnist.load_data()\n\n x_test = x_test[..., None].astype('float32')\n m_test = len(x_test)\n\n random_state = 42\n\n nrows = 16\n ncols = 12\n\n label = np.random.randint(0, 11)\n\n sample_size = nrows * ncols\n indices = random_indices(n=sample_size, start=0, end=m_test, step=1, replace=False, random_state=random_state)\n\n images = x_test[indices]\n\n true_i = np.where(y_test == label)[0]\n ground_truth = x_test[true_i][:nrows]\n\n grid_plot(images=images, nrows=nrows, ncols=ncols, ground_truth=ground_truth)\n" ]
[ [ "numpy.where", "tensorflow.keras.datasets.mnist.load_data", "numpy.random.randint" ] ]
njucjc/machine-learning
[ "1adcbad8d1e9f9a187036bec01d1a5ce798e44e0" ]
[ "Assignment1/main.py" ]
[ "import numpy as np\nimport argparse, os\nfrom utils import load_data, make_path\nfrom pca import pca_train, pca_test\nfrom svd import svd_train, svd_test\nfrom isomap import isomap\nfrom knn import knn\n\nparser = argparse.ArgumentParser(description='Dimensionality Reduction')\n\nparser.add_argument('--mode', type=str, default='train', help='train/test')\nparser.add_argument('--train_data', type=str, default='sonar', help='train data source')\nparser.add_argument('--test_data', type=str, default='sonar', help='test data source')\nparser.add_argument('--alg', type=str, default='pca', help='pca/svd/isomap')\nparser.add_argument('--output', type=str, default='output', help='result output dir')\nparser.add_argument('--dim', type=int, default= 10, help='target dim')\n\nargs = parser.parse_args()\nmake_path(args.output)\n\ntrain_data_path = os.path.join('data', args.train_data + '-train.txt')\ntest_data_path = os.path.join('data', args.test_data + '-test.txt')\n\ndef train():\n train_data, _ = load_data(train_data_path)\n if args.alg == 'pca':\n mean_vecs, eig_vecs = pca_train(np.array(train_data), args.dim)\n np.savez(os.path.join(args.output, 'pca' + str(args.dim) + '.npz'), mean_vecs=mean_vecs, eig_vecs=eig_vecs)\n elif args.alg == 'svd':\n v = svd_train(np.array(train_data), args.dim)\n np.savez(os.path.join(args.output, 'svd' + str(args.dim) + '.npz'), v=v)\n else:\n pass\n\n\ndef test():\n test_data, test_labels = load_data(test_data_path)\n train_data, train_labels = load_data(train_data_path)\n\n if args.alg == 'pca':\n saved_data = np.load(os.path.join(args.output, args.alg + str(args.dim) + '.npz'))\n mean_vecs = saved_data['mean_vecs']\n eig_vecs = saved_data['eig_vecs']\n\n reduction_test_data = pca_test(np.array(test_data), mean_vecs, eig_vecs)\n reduction_train_data = pca_test(np.array(train_data), mean_vecs, eig_vecs)\n elif args.alg == 'svd':\n saved_data = np.load(os.path.join(args.output, args.alg + str(args.dim) + '.npz'))\n v = saved_data['v']\n\n reduction_test_data = svd_test(np.array(test_data), v)\n reduction_train_data = svd_test(np.array(train_data), v)\n else:\n merge_data = train_data + test_data\n result = isomap(np.array(merge_data), n=args.dim)\n reduction_test_data = result[len(train_data):]\n reduction_train_data = result[:len(train_data)]\n\n acc = eval(reduction_test_data, test_labels, reduction_train_data, train_labels)\n print('ACC = ' + str(acc))\n\n \ndef eval(test_data, test_data_label, train_data, train_data_label):\n predict_label = []\n for x in test_data:\n label = knn(x, train_data, train_data_label, 1)\n predict_label.append(label)\n\n right = 0\n size = len(test_data_label)\n for i in range(size):\n if predict_label[i] == test_data_label[i]:\n right = right + 1\n return right / size\n\n\n\n\n\nif args.mode == 'train':\n train()\nelif args.mode == 'test':\n test()\n\n\n\n" ]
[ [ "numpy.array" ] ]
npaj/SilentCities
[ "3526d1716d4d7fa970a692bb8370f7d134fbd09c", "e68735d7a04a101aae2fb8fccac8b5b96c686585" ]
[ "audioset_tagging_cnn/models.py", "analysis.py" ]
[ "### modified from https://github.com/qiuqiangkong/audioset_tagging_cnn\nimport os\nimport sys\nimport math\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.checkpoint as cp\nfrom torch.nn.parameter import Parameter\n\nfrom .stft import Spectrogram, LogmelFilterBank\nfrom .augmentation import SpecAugmentation\nfrom .pytorch_utils import do_mixup, interpolate, pad_framewise_output\n \n\n\ndef init_layer(layer):\n \"\"\"Initialize a Linear or Convolutional layer. \"\"\"\n nn.init.xavier_uniform_(layer.weight)\n \n if hasattr(layer, 'bias'):\n if layer.bias is not None:\n layer.bias.data.fill_(0.)\n \n \ndef init_bn(bn):\n \"\"\"Initialize a Batchnorm layer. \"\"\"\n bn.bias.data.fill_(0.)\n bn.weight.data.fill_(1.)\n\n\nclass ConvBlock(nn.Module):\n def __init__(self, in_channels, out_channels):\n \n super(ConvBlock, self).__init__()\n \n self.conv1 = nn.Conv2d(in_channels=in_channels, \n out_channels=out_channels,\n kernel_size=(3, 3), stride=(1, 1),\n padding=(1, 1), bias=False)\n \n self.conv2 = nn.Conv2d(in_channels=out_channels, \n out_channels=out_channels,\n kernel_size=(3, 3), stride=(1, 1),\n padding=(1, 1), bias=False)\n \n self.bn1 = nn.BatchNorm2d(out_channels)\n self.bn2 = nn.BatchNorm2d(out_channels)\n\n self.init_weight()\n \n def init_weight(self):\n init_layer(self.conv1)\n init_layer(self.conv2)\n init_bn(self.bn1)\n init_bn(self.bn2)\n\n \n def forward(self, input, pool_size=(2, 2), pool_type='avg'):\n \n x = input\n x = F.relu_(self.bn1(self.conv1(x)))\n x = F.relu_(self.bn2(self.conv2(x)))\n if pool_type == 'max':\n x = F.max_pool2d(x, kernel_size=pool_size)\n elif pool_type == 'avg':\n x = F.avg_pool2d(x, kernel_size=pool_size)\n elif pool_type == 'avg+max':\n x1 = F.avg_pool2d(x, kernel_size=pool_size)\n x2 = F.max_pool2d(x, kernel_size=pool_size)\n x = x1 + x2\n else:\n raise Exception('Incorrect argument!')\n \n return x\n\n\nclass ConvBlock5x5(nn.Module):\n def __init__(self, in_channels, out_channels):\n \n super(ConvBlock5x5, self).__init__()\n \n self.conv1 = nn.Conv2d(in_channels=in_channels, \n out_channels=out_channels,\n kernel_size=(5, 5), stride=(1, 1),\n padding=(2, 2), bias=False)\n \n self.bn1 = nn.BatchNorm2d(out_channels)\n\n self.init_weight()\n \n def init_weight(self):\n init_layer(self.conv1)\n init_bn(self.bn1)\n\n \n def forward(self, input, pool_size=(2, 2), pool_type='avg'):\n \n x = input\n x = F.relu_(self.bn1(self.conv1(x)))\n if pool_type == 'max':\n x = F.max_pool2d(x, kernel_size=pool_size)\n elif pool_type == 'avg':\n x = F.avg_pool2d(x, kernel_size=pool_size)\n elif pool_type == 'avg+max':\n x1 = F.avg_pool2d(x, kernel_size=pool_size)\n x2 = F.max_pool2d(x, kernel_size=pool_size)\n x = x1 + x2\n else:\n raise Exception('Incorrect argument!')\n \n return x\n\n\nclass AttBlock(nn.Module):\n def __init__(self, n_in, n_out, activation='linear', temperature=1.):\n super(AttBlock, self).__init__()\n \n self.activation = activation\n self.temperature = temperature\n self.att = nn.Conv1d(in_channels=n_in, out_channels=n_out, kernel_size=1, stride=1, padding=0, bias=True)\n self.cla = nn.Conv1d(in_channels=n_in, out_channels=n_out, kernel_size=1, stride=1, padding=0, bias=True)\n \n self.bn_att = nn.BatchNorm1d(n_out)\n self.init_weights()\n \n def init_weights(self):\n init_layer(self.att)\n init_layer(self.cla)\n init_bn(self.bn_att)\n \n def forward(self, x):\n # x: (n_samples, n_in, n_time)\n norm_att = torch.softmax(torch.clamp(self.att(x), -10, 10), dim=-1)\n cla = self.nonlinear_transform(self.cla(x))\n x = torch.sum(norm_att * cla, dim=2)\n return x, norm_att, cla\n\n def nonlinear_transform(self, x):\n if self.activation == 'linear':\n return x\n elif self.activation == 'sigmoid':\n return torch.sigmoid(x)\n\n\nclass Cnn14(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(Cnn14, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n self.conv_block2 = ConvBlock(in_channels=64, out_channels=128)\n self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)\n self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)\n self.conv_block5 = ConvBlock(in_channels=512, out_channels=1024)\n self.conv_block6 = ConvBlock(in_channels=1024, out_channels=2048)\n\n self.fc1 = nn.Linear(2048, 2048, bias=True)\n self.fc_audioset = nn.Linear(2048, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block5(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block6(x, pool_size=(1, 1), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = torch.mean(x, dim=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass Cnn14_no_specaug(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(Cnn14_no_specaug, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n self.conv_block2 = ConvBlock(in_channels=64, out_channels=128)\n self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)\n self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)\n self.conv_block5 = ConvBlock(in_channels=512, out_channels=1024)\n self.conv_block6 = ConvBlock(in_channels=1024, out_channels=2048)\n\n self.fc1 = nn.Linear(2048, 2048, bias=True)\n self.fc_audioset = nn.Linear(2048, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block5(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block6(x, pool_size=(1, 1), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = torch.mean(x, dim=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass Cnn14_no_dropout(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(Cnn14_no_dropout, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n self.conv_block2 = ConvBlock(in_channels=64, out_channels=128)\n self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)\n self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)\n self.conv_block5 = ConvBlock(in_channels=512, out_channels=1024)\n self.conv_block6 = ConvBlock(in_channels=1024, out_channels=2048)\n\n self.fc1 = nn.Linear(2048, 2048, bias=True)\n self.fc_audioset = nn.Linear(2048, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')\n x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')\n x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')\n x = self.conv_block5(x, pool_size=(2, 2), pool_type='avg')\n x = self.conv_block6(x, pool_size=(1, 1), pool_type='avg')\n x = torch.mean(x, dim=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass Cnn6(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(Cnn6, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock5x5(in_channels=1, out_channels=64)\n self.conv_block2 = ConvBlock5x5(in_channels=64, out_channels=128)\n self.conv_block3 = ConvBlock5x5(in_channels=128, out_channels=256)\n self.conv_block4 = ConvBlock5x5(in_channels=256, out_channels=512)\n\n self.fc1 = nn.Linear(512, 512, bias=True)\n self.fc_audioset = nn.Linear(512, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = torch.mean(x, dim=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass Cnn10(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(Cnn10, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n self.conv_block2 = ConvBlock(in_channels=64, out_channels=128)\n self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)\n self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)\n\n self.fc1 = nn.Linear(512, 512, bias=True)\n self.fc_audioset = nn.Linear(512, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = torch.mean(x, dim=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\ndef _resnet_conv3x3(in_planes, out_planes):\n #3x3 convolution with padding\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=1,\n padding=1, groups=1, bias=False, dilation=1)\n\n\ndef _resnet_conv1x1(in_planes, out_planes):\n #1x1 convolution\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=1, bias=False)\n\n\nclass _ResnetBasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,\n base_width=64, dilation=1, norm_layer=None):\n super(_ResnetBasicBlock, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n if groups != 1 or base_width != 64:\n raise ValueError('_ResnetBasicBlock only supports groups=1 and base_width=64')\n if dilation > 1:\n raise NotImplementedError(\"Dilation > 1 not supported in _ResnetBasicBlock\")\n # Both self.conv1 and self.downsample layers downsample the input when stride != 1\n\n self.stride = stride\n\n self.conv1 = _resnet_conv3x3(inplanes, planes)\n self.bn1 = norm_layer(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = _resnet_conv3x3(planes, planes)\n self.bn2 = norm_layer(planes)\n self.downsample = downsample\n self.stride = stride\n\n self.init_weights()\n\n def init_weights(self):\n init_layer(self.conv1)\n init_bn(self.bn1)\n init_layer(self.conv2)\n init_bn(self.bn2)\n nn.init.constant_(self.bn2.weight, 0)\n\n def forward(self, x):\n identity = x\n\n if self.stride == 2:\n out = F.avg_pool2d(x, kernel_size=(2, 2))\n else:\n out = x\n\n out = self.conv1(out)\n out = self.bn1(out)\n out = self.relu(out)\n out = F.dropout(out, p=0.1, training=self.training)\n\n out = self.conv2(out)\n out = self.bn2(out)\n \n if self.downsample is not None:\n identity = self.downsample(identity)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass _ResnetBottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,\n base_width=64, dilation=1, norm_layer=None):\n super(_ResnetBottleneck, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n width = int(planes * (base_width / 64.)) * groups\n self.stride = stride\n # Both self.conv2 and self.downsample layers downsample the input when stride != 1\n self.conv1 = _resnet_conv1x1(inplanes, width)\n self.bn1 = norm_layer(width)\n self.conv2 = _resnet_conv3x3(width, width)\n self.bn2 = norm_layer(width)\n self.conv3 = _resnet_conv1x1(width, planes * self.expansion)\n self.bn3 = norm_layer(planes * self.expansion)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n self.init_weights()\n\n def init_weights(self):\n init_layer(self.conv1)\n init_bn(self.bn1)\n init_layer(self.conv2)\n init_bn(self.bn2)\n init_layer(self.conv3)\n init_bn(self.bn3)\n nn.init.constant_(self.bn3.weight, 0)\n\n def forward(self, x):\n identity = x\n\n if self.stride == 2:\n x = F.avg_pool2d(x, kernel_size=(2, 2))\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n out = F.dropout(out, p=0.1, training=self.training)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n identity = self.downsample(identity)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass _ResNet(nn.Module):\n def __init__(self, block, layers, zero_init_residual=False,\n groups=1, width_per_group=64, replace_stride_with_dilation=None,\n norm_layer=None):\n super(_ResNet, self).__init__()\n\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n self._norm_layer = norm_layer\n\n self.inplanes = 64\n self.dilation = 1\n if replace_stride_with_dilation is None:\n # each element in the tuple indicates if we should replace\n # the 2x2 stride with a dilated convolution instead\n replace_stride_with_dilation = [False, False, False]\n if len(replace_stride_with_dilation) != 3:\n raise ValueError(\"replace_stride_with_dilation should be None \"\n \"or a 3-element tuple, got {}\".format(replace_stride_with_dilation))\n self.groups = groups\n self.base_width = width_per_group\n\n self.layer1 = self._make_layer(block, 64, layers[0], stride=1)\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2,\n dilate=replace_stride_with_dilation[0])\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2,\n dilate=replace_stride_with_dilation[1])\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2,\n dilate=replace_stride_with_dilation[2])\n\n def _make_layer(self, block, planes, blocks, stride=1, dilate=False):\n norm_layer = self._norm_layer\n downsample = None\n previous_dilation = self.dilation\n if dilate:\n self.dilation *= stride\n stride = 1\n if stride != 1 or self.inplanes != planes * block.expansion:\n if stride == 1:\n downsample = nn.Sequential(\n _resnet_conv1x1(self.inplanes, planes * block.expansion),\n norm_layer(planes * block.expansion),\n )\n init_layer(downsample[0])\n init_bn(downsample[1])\n elif stride == 2:\n downsample = nn.Sequential(\n nn.AvgPool2d(kernel_size=2), \n _resnet_conv1x1(self.inplanes, planes * block.expansion),\n norm_layer(planes * block.expansion),\n )\n init_layer(downsample[1])\n init_bn(downsample[2])\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample, self.groups,\n self.base_width, previous_dilation, norm_layer))\n self.inplanes = planes * block.expansion\n for _ in range(1, blocks):\n layers.append(block(self.inplanes, planes, groups=self.groups,\n base_width=self.base_width, dilation=self.dilation,\n norm_layer=norm_layer))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n return x\n\n\nclass ResNet22(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(ResNet22, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n # self.conv_block2 = ConvBlock(in_channels=64, out_channels=64)\n\n self.resnet = _ResNet(block=_ResnetBasicBlock, layers=[2, 2, 2, 2], zero_init_residual=True)\n\n self.conv_block_after1 = ConvBlock(in_channels=512, out_channels=2048)\n\n self.fc1 = nn.Linear(2048, 2048)\n self.fc_audioset = nn.Linear(2048, classes_num, bias=True)\n\n self.init_weights()\n\n def init_weights(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n\n\n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training, inplace=True)\n x = self.resnet(x)\n x = F.avg_pool2d(x, kernel_size=(2, 2))\n x = F.dropout(x, p=0.2, training=self.training, inplace=True)\n x = self.conv_block_after1(x, pool_size=(1, 1), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training, inplace=True)\n x = torch.mean(x, dim=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass ResNet38(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(ResNet38, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n # self.conv_block2 = ConvBlock(in_channels=64, out_channels=64)\n\n self.resnet = _ResNet(block=_ResnetBasicBlock, layers=[3, 4, 6, 3], zero_init_residual=True)\n\n self.conv_block_after1 = ConvBlock(in_channels=512, out_channels=2048)\n\n self.fc1 = nn.Linear(2048, 2048)\n self.fc_audioset = nn.Linear(2048, classes_num, bias=True)\n\n self.init_weights()\n\n def init_weights(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n\n\n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training, inplace=True)\n x = self.resnet(x)\n x = F.avg_pool2d(x, kernel_size=(2, 2))\n x = F.dropout(x, p=0.2, training=self.training, inplace=True)\n x = self.conv_block_after1(x, pool_size=(1, 1), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training, inplace=True)\n x = torch.mean(x, dim=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass ResNet54(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(ResNet54, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n # self.conv_block2 = ConvBlock(in_channels=64, out_channels=64)\n\n self.resnet = _ResNet(block=_ResnetBottleneck, layers=[3, 4, 6, 3], zero_init_residual=True)\n\n self.conv_block_after1 = ConvBlock(in_channels=2048, out_channels=2048)\n\n self.fc1 = nn.Linear(2048, 2048)\n self.fc_audioset = nn.Linear(2048, classes_num, bias=True)\n\n self.init_weights()\n\n def init_weights(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n\n\n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training, inplace=True)\n x = self.resnet(x)\n x = F.avg_pool2d(x, kernel_size=(2, 2))\n x = F.dropout(x, p=0.2, training=self.training, inplace=True)\n x = self.conv_block_after1(x, pool_size=(1, 1), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training, inplace=True)\n x = torch.mean(x, dim=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass Cnn14_emb512(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(Cnn14_emb512, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n self.conv_block2 = ConvBlock(in_channels=64, out_channels=128)\n self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)\n self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)\n self.conv_block5 = ConvBlock(in_channels=512, out_channels=1024)\n self.conv_block6 = ConvBlock(in_channels=1024, out_channels=2048)\n\n self.fc1 = nn.Linear(2048, 512, bias=True)\n self.fc_audioset = nn.Linear(512, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block5(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block6(x, pool_size=(1, 1), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = torch.mean(x, dim=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass Cnn14_emb128(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(Cnn14_emb128, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n self.conv_block2 = ConvBlock(in_channels=64, out_channels=128)\n self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)\n self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)\n self.conv_block5 = ConvBlock(in_channels=512, out_channels=1024)\n self.conv_block6 = ConvBlock(in_channels=1024, out_channels=2048)\n\n self.fc1 = nn.Linear(2048, 128, bias=True)\n self.fc_audioset = nn.Linear(128, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block5(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block6(x, pool_size=(1, 1), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = torch.mean(x, dim=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass Cnn14_emb32(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(Cnn14_emb32, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n self.conv_block2 = ConvBlock(in_channels=64, out_channels=128)\n self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)\n self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)\n self.conv_block5 = ConvBlock(in_channels=512, out_channels=1024)\n self.conv_block6 = ConvBlock(in_channels=1024, out_channels=2048)\n\n self.fc1 = nn.Linear(2048, 32, bias=True)\n self.fc_audioset = nn.Linear(32, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block5(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block6(x, pool_size=(1, 1), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = torch.mean(x, dim=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass MobileNetV1(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(MobileNetV1, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n def conv_bn(inp, oup, stride):\n _layers = [\n nn.Conv2d(inp, oup, 3, 1, 1, bias=False), \n nn.AvgPool2d(stride), \n nn.BatchNorm2d(oup), \n nn.ReLU(inplace=True)\n ]\n _layers = nn.Sequential(*_layers)\n init_layer(_layers[0])\n init_bn(_layers[2])\n return _layers\n\n def conv_dw(inp, oup, stride):\n _layers = [\n nn.Conv2d(inp, inp, 3, 1, 1, groups=inp, bias=False), \n nn.AvgPool2d(stride), \n nn.BatchNorm2d(inp), \n nn.ReLU(inplace=True), \n nn.Conv2d(inp, oup, 1, 1, 0, bias=False), \n nn.BatchNorm2d(oup), \n nn.ReLU(inplace=True)\n ]\n _layers = nn.Sequential(*_layers)\n init_layer(_layers[0])\n init_bn(_layers[2])\n init_layer(_layers[4])\n init_bn(_layers[5])\n return _layers\n\n self.features = nn.Sequential(\n conv_bn( 1, 32, 2), \n conv_dw( 32, 64, 1),\n conv_dw( 64, 128, 2),\n conv_dw(128, 128, 1),\n conv_dw(128, 256, 2),\n conv_dw(256, 256, 1),\n conv_dw(256, 512, 2),\n conv_dw(512, 512, 1),\n conv_dw(512, 512, 1),\n conv_dw(512, 512, 1),\n conv_dw(512, 512, 1),\n conv_dw(512, 512, 1),\n conv_dw(512, 1024, 2),\n conv_dw(1024, 1024, 1))\n\n self.fc1 = nn.Linear(1024, 1024, bias=True)\n self.fc_audioset = nn.Linear(1024, classes_num, bias=True)\n\n self.init_weights()\n\n def init_weights(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.features(x)\n x = torch.mean(x, dim=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass InvertedResidual(nn.Module):\n def __init__(self, inp, oup, stride, expand_ratio):\n super(InvertedResidual, self).__init__()\n self.stride = stride\n assert stride in [1, 2]\n\n hidden_dim = round(inp * expand_ratio)\n self.use_res_connect = self.stride == 1 and inp == oup\n\n if expand_ratio == 1:\n _layers = [\n nn.Conv2d(hidden_dim, hidden_dim, 3, 1, 1, groups=hidden_dim, bias=False), \n nn.AvgPool2d(stride), \n nn.BatchNorm2d(hidden_dim), \n nn.ReLU6(inplace=True), \n nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), \n nn.BatchNorm2d(oup)\n ]\n _layers = nn.Sequential(*_layers)\n init_layer(_layers[0])\n init_bn(_layers[2])\n init_layer(_layers[4])\n init_bn(_layers[5])\n self.conv = _layers\n else:\n _layers = [\n nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False), \n nn.BatchNorm2d(hidden_dim), \n nn.ReLU6(inplace=True), \n nn.Conv2d(hidden_dim, hidden_dim, 3, 1, 1, groups=hidden_dim, bias=False), \n nn.AvgPool2d(stride), \n nn.BatchNorm2d(hidden_dim), \n nn.ReLU6(inplace=True), \n nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), \n nn.BatchNorm2d(oup)\n ]\n _layers = nn.Sequential(*_layers)\n init_layer(_layers[0])\n init_bn(_layers[1])\n init_layer(_layers[3])\n init_bn(_layers[5])\n init_layer(_layers[7])\n init_bn(_layers[8])\n self.conv = _layers\n\n def forward(self, x):\n if self.use_res_connect:\n return x + self.conv(x)\n else:\n return self.conv(x)\n\n\nclass MobileNetV2(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(MobileNetV2, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n \n width_mult=1.\n block = InvertedResidual\n input_channel = 32\n last_channel = 1280\n interverted_residual_setting = [\n # t, c, n, s\n [1, 16, 1, 1],\n [6, 24, 2, 2],\n [6, 32, 3, 2],\n [6, 64, 4, 2],\n [6, 96, 3, 2],\n [6, 160, 3, 1],\n [6, 320, 1, 1],\n ]\n\n def conv_bn(inp, oup, stride):\n _layers = [\n nn.Conv2d(inp, oup, 3, 1, 1, bias=False), \n nn.AvgPool2d(stride), \n nn.BatchNorm2d(oup), \n nn.ReLU6(inplace=True)\n ]\n _layers = nn.Sequential(*_layers)\n init_layer(_layers[0])\n init_bn(_layers[2])\n return _layers\n\n\n def conv_1x1_bn(inp, oup):\n _layers = nn.Sequential(\n nn.Conv2d(inp, oup, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup),\n nn.ReLU6(inplace=True)\n )\n init_layer(_layers[0])\n init_bn(_layers[1])\n return _layers\n\n # building first layer\n input_channel = int(input_channel * width_mult)\n self.last_channel = int(last_channel * width_mult) if width_mult > 1.0 else last_channel\n self.features = [conv_bn(1, input_channel, 2)]\n # building inverted residual blocks\n for t, c, n, s in interverted_residual_setting:\n output_channel = int(c * width_mult)\n for i in range(n):\n if i == 0:\n self.features.append(block(input_channel, output_channel, s, expand_ratio=t))\n else:\n self.features.append(block(input_channel, output_channel, 1, expand_ratio=t))\n input_channel = output_channel\n # building last several layers\n self.features.append(conv_1x1_bn(input_channel, self.last_channel))\n # make it nn.Sequential\n self.features = nn.Sequential(*self.features)\n\n self.fc1 = nn.Linear(1280, 1024, bias=True)\n self.fc_audioset = nn.Linear(1024, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.features(x)\n \n x = torch.mean(x, dim=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n # x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass LeeNetConvBlock(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride):\n \n super(LeeNetConvBlock, self).__init__()\n \n self.conv1 = nn.Conv1d(in_channels=in_channels, \n out_channels=out_channels,\n kernel_size=kernel_size, stride=stride,\n padding=kernel_size // 2, bias=False)\n \n self.bn1 = nn.BatchNorm1d(out_channels)\n\n self.init_weight()\n \n def init_weight(self):\n init_layer(self.conv1)\n init_bn(self.bn1)\n\n def forward(self, x, pool_size=1):\n x = F.relu_(self.bn1(self.conv1(x)))\n if pool_size != 1:\n x = F.max_pool1d(x, kernel_size=pool_size, padding=pool_size // 2)\n return x\n\n\nclass LeeNet11(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(LeeNet11, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n self.conv_block1 = LeeNetConvBlock(1, 64, 3, 3)\n self.conv_block2 = LeeNetConvBlock(64, 64, 3, 1)\n self.conv_block3 = LeeNetConvBlock(64, 64, 3, 1)\n self.conv_block4 = LeeNetConvBlock(64, 128, 3, 1)\n self.conv_block5 = LeeNetConvBlock(128, 128, 3, 1)\n self.conv_block6 = LeeNetConvBlock(128, 128, 3, 1)\n self.conv_block7 = LeeNetConvBlock(128, 128, 3, 1)\n self.conv_block8 = LeeNetConvBlock(128, 128, 3, 1)\n self.conv_block9 = LeeNetConvBlock(128, 256, 3, 1)\n \n\n self.fc1 = nn.Linear(256, 512, bias=True)\n self.fc_audioset = nn.Linear(512, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = input[:, None, :]\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.conv_block1(x)\n x = self.conv_block2(x, pool_size=3)\n x = self.conv_block3(x, pool_size=3)\n x = self.conv_block4(x, pool_size=3)\n x = self.conv_block5(x, pool_size=3)\n x = self.conv_block6(x, pool_size=3)\n x = self.conv_block7(x, pool_size=3)\n x = self.conv_block8(x, pool_size=3)\n x = self.conv_block9(x, pool_size=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass LeeNetConvBlock2(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride):\n \n super(LeeNetConvBlock2, self).__init__()\n \n self.conv1 = nn.Conv1d(in_channels=in_channels, \n out_channels=out_channels,\n kernel_size=kernel_size, stride=stride,\n padding=kernel_size // 2, bias=False)\n \n self.conv2 = nn.Conv1d(in_channels=out_channels, \n out_channels=out_channels,\n kernel_size=kernel_size, stride=1,\n padding=kernel_size // 2, bias=False)\n\n self.bn1 = nn.BatchNorm1d(out_channels)\n self.bn2 = nn.BatchNorm1d(out_channels)\n\n self.init_weight()\n \n def init_weight(self):\n init_layer(self.conv1)\n init_layer(self.conv2)\n init_bn(self.bn1)\n init_bn(self.bn2)\n\n def forward(self, x, pool_size=1):\n x = F.relu_(self.bn1(self.conv1(x)))\n x = F.relu_(self.bn2(self.conv2(x)))\n if pool_size != 1:\n x = F.max_pool1d(x, kernel_size=pool_size, padding=pool_size // 2)\n return x\n\n\nclass LeeNet24(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(LeeNet24, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n self.conv_block1 = LeeNetConvBlock2(1, 64, 3, 3)\n self.conv_block2 = LeeNetConvBlock2(64, 96, 3, 1)\n self.conv_block3 = LeeNetConvBlock2(96, 128, 3, 1)\n self.conv_block4 = LeeNetConvBlock2(128, 128, 3, 1)\n self.conv_block5 = LeeNetConvBlock2(128, 256, 3, 1)\n self.conv_block6 = LeeNetConvBlock2(256, 256, 3, 1)\n self.conv_block7 = LeeNetConvBlock2(256, 512, 3, 1)\n self.conv_block8 = LeeNetConvBlock2(512, 512, 3, 1)\n self.conv_block9 = LeeNetConvBlock2(512, 1024, 3, 1)\n\n self.fc1 = nn.Linear(1024, 1024, bias=True)\n self.fc_audioset = nn.Linear(1024, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = input[:, None, :]\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.conv_block1(x)\n x = F.dropout(x, p=0.1, training=self.training)\n x = self.conv_block2(x, pool_size=3)\n x = F.dropout(x, p=0.1, training=self.training)\n x = self.conv_block3(x, pool_size=3)\n x = F.dropout(x, p=0.1, training=self.training)\n x = self.conv_block4(x, pool_size=3)\n x = F.dropout(x, p=0.1, training=self.training)\n x = self.conv_block5(x, pool_size=3)\n x = F.dropout(x, p=0.1, training=self.training)\n x = self.conv_block6(x, pool_size=3)\n x = F.dropout(x, p=0.1, training=self.training)\n x = self.conv_block7(x, pool_size=3)\n x = F.dropout(x, p=0.1, training=self.training)\n x = self.conv_block8(x, pool_size=3)\n x = F.dropout(x, p=0.1, training=self.training)\n x = self.conv_block9(x, pool_size=1)\n\n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass DaiNetResBlock(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size):\n \n super(DaiNetResBlock, self).__init__()\n \n self.conv1 = nn.Conv1d(in_channels=in_channels, \n out_channels=out_channels,\n kernel_size=kernel_size, stride=1,\n padding=kernel_size // 2, bias=False)\n\n self.conv2 = nn.Conv1d(in_channels=out_channels, \n out_channels=out_channels,\n kernel_size=kernel_size, stride=1,\n padding=kernel_size // 2, bias=False)\n\n self.conv3 = nn.Conv1d(in_channels=out_channels, \n out_channels=out_channels,\n kernel_size=kernel_size, stride=1,\n padding=kernel_size // 2, bias=False)\n\n self.conv4 = nn.Conv1d(in_channels=out_channels, \n out_channels=out_channels,\n kernel_size=kernel_size, stride=1,\n padding=kernel_size // 2, bias=False)\n\n self.downsample = nn.Conv1d(in_channels=in_channels, \n out_channels=out_channels,\n kernel_size=1, stride=1,\n padding=0, bias=False)\n\n self.bn1 = nn.BatchNorm1d(out_channels)\n self.bn2 = nn.BatchNorm1d(out_channels)\n self.bn3 = nn.BatchNorm1d(out_channels)\n self.bn4 = nn.BatchNorm1d(out_channels)\n self.bn_downsample = nn.BatchNorm1d(out_channels)\n\n self.init_weight()\n \n def init_weight(self):\n init_layer(self.conv1)\n init_layer(self.conv2)\n init_layer(self.conv3)\n init_layer(self.conv4)\n init_layer(self.downsample)\n init_bn(self.bn1)\n init_bn(self.bn2)\n init_bn(self.bn3)\n init_bn(self.bn4)\n nn.init.constant_(self.bn4.weight, 0)\n init_bn(self.bn_downsample)\n\n def forward(self, input, pool_size=1):\n x = F.relu_(self.bn1(self.conv1(input)))\n x = F.relu_(self.bn2(self.conv2(x)))\n x = F.relu_(self.bn3(self.conv3(x)))\n x = self.bn4(self.conv4(x))\n if input.shape == x.shape:\n x = F.relu_(x + input)\n else:\n x = F.relu(x + self.bn_downsample(self.downsample(input)))\n\n if pool_size != 1:\n x = F.max_pool1d(x, kernel_size=pool_size, padding=pool_size // 2)\n return x\n\n\nclass DaiNet19(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(DaiNet19, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n self.conv0 = nn.Conv1d(in_channels=1, out_channels=64, kernel_size=80, stride=4, padding=0, bias=False)\n self.bn0 = nn.BatchNorm1d(64)\n self.conv_block1 = DaiNetResBlock(64, 64, 3)\n self.conv_block2 = DaiNetResBlock(64, 128, 3)\n self.conv_block3 = DaiNetResBlock(128, 256, 3)\n self.conv_block4 = DaiNetResBlock(256, 512, 3)\n\n self.fc1 = nn.Linear(512, 512, bias=True)\n self.fc_audioset = nn.Linear(512, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_layer(self.conv0)\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = input[:, None, :]\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n\n x = self.bn0(self.conv0(x))\n x = self.conv_block1(x)\n x = F.max_pool1d(x, kernel_size=4)\n x = self.conv_block2(x)\n x = F.max_pool1d(x, kernel_size=4)\n x = self.conv_block3(x)\n x = F.max_pool1d(x, kernel_size=4)\n x = self.conv_block4(x)\n\n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\ndef _resnet_conv3x1_wav1d(in_planes, out_planes, dilation):\n #3x3 convolution with padding\n return nn.Conv1d(in_planes, out_planes, kernel_size=3, stride=1,\n padding=dilation, groups=1, bias=False, dilation=dilation)\n\n\ndef _resnet_conv1x1_wav1d(in_planes, out_planes):\n #1x1 convolution\n return nn.Conv1d(in_planes, out_planes, kernel_size=1, stride=1, bias=False)\n\n\nclass _ResnetBasicBlockWav1d(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,\n base_width=64, dilation=1, norm_layer=None):\n super(_ResnetBasicBlockWav1d, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm1d\n if groups != 1 or base_width != 64:\n raise ValueError('_ResnetBasicBlock only supports groups=1 and base_width=64')\n if dilation > 1:\n raise NotImplementedError(\"Dilation > 1 not supported in _ResnetBasicBlock\")\n # Both self.conv1 and self.downsample layers downsample the input when stride != 1\n\n self.stride = stride\n\n self.conv1 = _resnet_conv3x1_wav1d(inplanes, planes, dilation=1)\n self.bn1 = norm_layer(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = _resnet_conv3x1_wav1d(planes, planes, dilation=2)\n self.bn2 = norm_layer(planes)\n self.downsample = downsample\n self.stride = stride\n\n self.init_weights()\n\n def init_weights(self):\n init_layer(self.conv1)\n init_bn(self.bn1)\n init_layer(self.conv2)\n init_bn(self.bn2)\n nn.init.constant_(self.bn2.weight, 0)\n\n def forward(self, x):\n identity = x\n\n if self.stride != 1:\n out = F.max_pool1d(x, kernel_size=self.stride)\n else:\n out = x\n\n out = self.conv1(out)\n out = self.bn1(out)\n out = self.relu(out)\n out = F.dropout(out, p=0.1, training=self.training)\n\n out = self.conv2(out)\n out = self.bn2(out)\n \n if self.downsample is not None:\n identity = self.downsample(identity)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass _ResNetWav1d(nn.Module):\n def __init__(self, block, layers, zero_init_residual=False,\n groups=1, width_per_group=64, replace_stride_with_dilation=None,\n norm_layer=None):\n super(_ResNetWav1d, self).__init__()\n\n if norm_layer is None:\n norm_layer = nn.BatchNorm1d\n self._norm_layer = norm_layer\n\n self.inplanes = 64\n self.dilation = 1\n if replace_stride_with_dilation is None:\n # each element in the tuple indicates if we should replace\n # the 2x2 stride with a dilated convolution instead\n replace_stride_with_dilation = [False, False, False]\n if len(replace_stride_with_dilation) != 3:\n raise ValueError(\"replace_stride_with_dilation should be None \"\n \"or a 3-element tuple, got {}\".format(replace_stride_with_dilation))\n self.groups = groups\n self.base_width = width_per_group\n\n self.layer1 = self._make_layer(block, 64, layers[0], stride=1)\n self.layer2 = self._make_layer(block, 128, layers[1], stride=4)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=4)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=4)\n self.layer5 = self._make_layer(block, 1024, layers[4], stride=4)\n self.layer6 = self._make_layer(block, 1024, layers[5], stride=4)\n self.layer7 = self._make_layer(block, 2048, layers[6], stride=4)\n\n def _make_layer(self, block, planes, blocks, stride=1, dilate=False):\n norm_layer = self._norm_layer\n downsample = None\n previous_dilation = self.dilation\n if dilate:\n self.dilation *= stride\n stride = 1\n if stride != 1 or self.inplanes != planes * block.expansion:\n if stride == 1:\n downsample = nn.Sequential(\n _resnet_conv1x1_wav1d(self.inplanes, planes * block.expansion),\n norm_layer(planes * block.expansion),\n )\n init_layer(downsample[0])\n init_bn(downsample[1])\n else:\n downsample = nn.Sequential(\n nn.AvgPool1d(kernel_size=stride), \n _resnet_conv1x1_wav1d(self.inplanes, planes * block.expansion),\n norm_layer(planes * block.expansion),\n )\n init_layer(downsample[1])\n init_bn(downsample[2])\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample, self.groups,\n self.base_width, previous_dilation, norm_layer))\n self.inplanes = planes * block.expansion\n for _ in range(1, blocks):\n layers.append(block(self.inplanes, planes, groups=self.groups,\n base_width=self.base_width, dilation=self.dilation,\n norm_layer=norm_layer))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n \n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n x = self.layer5(x)\n x = self.layer6(x)\n x = self.layer7(x)\n\n return x\n\n\nclass Res1dNet31(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(Res1dNet31, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n self.conv0 = nn.Conv1d(in_channels=1, out_channels=64, kernel_size=11, stride=5, padding=5, bias=False)\n self.bn0 = nn.BatchNorm1d(64)\n\n self.resnet = _ResNetWav1d(_ResnetBasicBlockWav1d, [2, 2, 2, 2, 2, 2, 2])\n\n self.fc1 = nn.Linear(2048, 2048, bias=True)\n self.fc_audioset = nn.Linear(2048, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_layer(self.conv0)\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = input[:, None, :]\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n\n x = self.bn0(self.conv0(x))\n x = self.resnet(x)\n\n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass Res1dNet51(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(Res1dNet51, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n self.conv0 = nn.Conv1d(in_channels=1, out_channels=64, kernel_size=11, stride=5, padding=5, bias=False)\n self.bn0 = nn.BatchNorm1d(64)\n\n self.resnet = _ResNetWav1d(_ResnetBasicBlockWav1d, [2, 3, 4, 6, 4, 3, 2])\n\n self.fc1 = nn.Linear(2048, 2048, bias=True)\n self.fc_audioset = nn.Linear(2048, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_layer(self.conv0)\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = input[:, None, :]\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n\n x = self.bn0(self.conv0(x))\n x = self.resnet(x)\n\n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass ConvPreWavBlock(nn.Module):\n def __init__(self, in_channels, out_channels):\n \n super(ConvPreWavBlock, self).__init__()\n \n self.conv1 = nn.Conv1d(in_channels=in_channels, \n out_channels=out_channels,\n kernel_size=3, stride=1,\n padding=1, bias=False)\n \n self.conv2 = nn.Conv1d(in_channels=out_channels, \n out_channels=out_channels,\n kernel_size=3, stride=1, dilation=2, \n padding=2, bias=False)\n \n self.bn1 = nn.BatchNorm1d(out_channels)\n self.bn2 = nn.BatchNorm1d(out_channels)\n\n self.init_weight()\n \n def init_weight(self):\n init_layer(self.conv1)\n init_layer(self.conv2)\n init_bn(self.bn1)\n init_bn(self.bn2)\n\n \n def forward(self, input, pool_size):\n \n x = input\n x = F.relu_(self.bn1(self.conv1(x)))\n x = F.relu_(self.bn2(self.conv2(x)))\n x = F.max_pool1d(x, kernel_size=pool_size)\n \n return x\n\n\nclass Wavegram_Cnn14(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(Wavegram_Cnn14, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n self.pre_conv0 = nn.Conv1d(in_channels=1, out_channels=64, kernel_size=11, stride=5, padding=5, bias=False)\n self.pre_bn0 = nn.BatchNorm1d(64)\n self.pre_block1 = ConvPreWavBlock(64, 64)\n self.pre_block2 = ConvPreWavBlock(64, 128)\n self.pre_block3 = ConvPreWavBlock(128, 128)\n self.pre_block4 = ConvBlock(in_channels=4, out_channels=64)\n\n self.bn0 = nn.BatchNorm1d(64)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n self.conv_block2 = ConvBlock(in_channels=64, out_channels=128)\n self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)\n self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)\n self.conv_block5 = ConvBlock(in_channels=512, out_channels=1024)\n self.conv_block6 = ConvBlock(in_channels=1024, out_channels=2048)\n\n self.fc1 = nn.Linear(2048, 2048, bias=True)\n self.fc_audioset = nn.Linear(2048, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_layer(self.pre_conv0)\n init_bn(self.pre_bn0)\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n a1 = F.relu_(self.pre_bn0(self.pre_conv0(input[:, None, :])))\n a1 = self.pre_block1(a1, pool_size=4)\n a1 = self.pre_block2(a1, pool_size=4)\n a1 = self.pre_block3(a1, pool_size=4)\n a1 = a1.reshape((a1.shape[0], -1, 32, a1.shape[-1])).transpose(2, 3)\n a1 = self.pre_block4(a1, pool_size=(2, 1))\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n a1 = do_mixup(a1, mixup_lambda)\n \n x = a1\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block5(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block6(x, pool_size=(1, 1), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = torch.mean(x, dim=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass Wavegram_Logmel_Cnn14(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(Wavegram_Logmel_Cnn14, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n\n self.pre_conv0 = nn.Conv1d(in_channels=1, out_channels=64, kernel_size=11, stride=5, padding=5, bias=False)\n self.pre_bn0 = nn.BatchNorm1d(64)\n self.pre_block1 = ConvPreWavBlock(64, 64)\n self.pre_block2 = ConvPreWavBlock(64, 128)\n self.pre_block3 = ConvPreWavBlock(128, 128)\n self.pre_block4 = ConvBlock(in_channels=4, out_channels=64)\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n self.bn0 = nn.BatchNorm1d(64)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n self.conv_block2 = ConvBlock(in_channels=128, out_channels=128)\n self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)\n self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)\n self.conv_block5 = ConvBlock(in_channels=512, out_channels=1024)\n self.conv_block6 = ConvBlock(in_channels=1024, out_channels=2048)\n\n self.fc1 = nn.Linear(2048, 2048, bias=True)\n self.fc_audioset = nn.Linear(2048, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_layer(self.pre_conv0)\n init_bn(self.pre_bn0)\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n a1 = F.relu_(self.pre_bn0(self.pre_conv0(input[:, None, :])))\n a1 = self.pre_block1(a1, pool_size=4)\n a1 = self.pre_block2(a1, pool_size=4)\n a1 = self.pre_block3(a1, pool_size=4)\n a1 = a1.reshape((a1.shape[0], -1, 32, a1.shape[-1])).transpose(2, 3)\n a1 = self.pre_block4(a1, pool_size=(2, 1))\n\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n\n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n a1 = do_mixup(a1, mixup_lambda)\n \n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = torch.cat((x, a1), dim=1)\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block5(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block6(x, pool_size=(1, 1), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = torch.mean(x, dim=3)\n \n (x1, _) = torch.max(x, dim=2)\n x2 = torch.mean(x, dim=2)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = F.relu_(self.fc1(x))\n embedding = F.dropout(x, p=0.5, training=self.training)\n clipwise_output = torch.sigmoid(self.fc_audioset(x))\n \n output_dict = {'clipwise_output': clipwise_output, 'embedding': embedding}\n\n return output_dict\n\n\nclass Cnn14_DecisionLevelMax(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(Cnn14_DecisionLevelMax, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n self.interpolate_ratio = 32 # Downsampled ratio\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n self.conv_block2 = ConvBlock(in_channels=64, out_channels=128)\n self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)\n self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)\n self.conv_block5 = ConvBlock(in_channels=512, out_channels=1024)\n self.conv_block6 = ConvBlock(in_channels=1024, out_channels=2048)\n\n self.fc1 = nn.Linear(2048, 2048, bias=True)\n self.fc_audioset = nn.Linear(2048, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n\n frames_num = x.shape[2]\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n\n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block5(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block6(x, pool_size=(1, 1), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = torch.mean(x, dim=3)\n \n x1 = F.max_pool1d(x, kernel_size=3, stride=1, padding=1)\n x2 = F.avg_pool1d(x, kernel_size=3, stride=1, padding=1)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = x.transpose(1, 2)\n x = F.relu_(self.fc1(x))\n x = F.dropout(x, p=0.5, training=self.training)\n segmentwise_output = torch.sigmoid(self.fc_audioset(x))\n (clipwise_output, _) = torch.max(segmentwise_output, dim=1)\n\n # Get framewise output\n framewise_output = interpolate(segmentwise_output, self.interpolate_ratio)\n framewise_output = pad_framewise_output(framewise_output, frames_num)\n\n output_dict = {'framewise_output': framewise_output, \n 'clipwise_output': clipwise_output}\n\n return output_dict\n\n\nclass Cnn14_DecisionLevelAvg(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(Cnn14_DecisionLevelAvg, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n self.interpolate_ratio = 32 # Downsampled ratio\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n self.conv_block2 = ConvBlock(in_channels=64, out_channels=128)\n self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)\n self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)\n self.conv_block5 = ConvBlock(in_channels=512, out_channels=1024)\n self.conv_block6 = ConvBlock(in_channels=1024, out_channels=2048)\n\n self.fc1 = nn.Linear(2048, 2048, bias=True)\n self.fc_audioset = nn.Linear(2048, classes_num, bias=True)\n \n self.init_weight()\n\n def init_weight(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n init_layer(self.fc_audioset)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n # t1 = time.time()\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n\n frames_num = x.shape[2]\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block5(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block6(x, pool_size=(1, 1), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = torch.mean(x, dim=3)\n \n x1 = F.max_pool1d(x, kernel_size=3, stride=1, padding=1)\n x2 = F.avg_pool1d(x, kernel_size=3, stride=1, padding=1)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = x.transpose(1, 2)\n x = F.relu_(self.fc1(x))\n x = F.dropout(x, p=0.5, training=self.training)\n segmentwise_output = torch.sigmoid(self.fc_audioset(x))\n clipwise_output = torch.mean(segmentwise_output, dim=1)\n\n # Get framewise output\n framewise_output = interpolate(segmentwise_output, self.interpolate_ratio)\n framewise_output = pad_framewise_output(framewise_output, frames_num)\n\n # Get framewise output\n framewise_output = interpolate(segmentwise_output, self.interpolate_ratio)\n framewise_output = pad_framewise_output(framewise_output, frames_num)\n\n output_dict = {'framewise_output': framewise_output, \n 'clipwise_output': clipwise_output}\n\n return output_dict\n\n\nclass Cnn14_DecisionLevelAtt(nn.Module):\n def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, \n fmax, classes_num):\n \n super(Cnn14_DecisionLevelAtt, self).__init__()\n\n window = 'hann'\n center = True\n pad_mode = 'reflect'\n ref = 1.0\n amin = 1e-10\n top_db = None\n self.interpolate_ratio = 32 # Downsampled ratio\n\n # Spectrogram extractor\n self.spectrogram_extractor = Spectrogram(n_fft=window_size, hop_length=hop_size, \n win_length=window_size, window=window, center=center, pad_mode=pad_mode, \n freeze_parameters=True)\n\n # Logmel feature extractor\n self.logmel_extractor = LogmelFilterBank(sr=sample_rate, n_fft=window_size, \n n_mels=mel_bins, fmin=fmin, fmax=fmax, ref=ref, amin=amin, top_db=top_db, \n freeze_parameters=True)\n\n # Spec augmenter\n self.spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2, \n freq_drop_width=8, freq_stripes_num=2)\n\n self.bn0 = nn.BatchNorm2d(64)\n\n self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)\n self.conv_block2 = ConvBlock(in_channels=64, out_channels=128)\n self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)\n self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)\n self.conv_block5 = ConvBlock(in_channels=512, out_channels=1024)\n self.conv_block6 = ConvBlock(in_channels=1024, out_channels=2048)\n\n self.fc1 = nn.Linear(2048, 2048, bias=True)\n self.att_block = AttBlock(2048, classes_num, activation='sigmoid')\n \n self.init_weight()\n\n def init_weight(self):\n init_bn(self.bn0)\n init_layer(self.fc1)\n \n def forward(self, input, mixup_lambda=None):\n \"\"\"\n Input: (batch_size, data_length)\"\"\"\n\n # t1 = time.time()\n x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)\n x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)\n\n frames_num = x.shape[2]\n \n x = x.transpose(1, 3)\n x = self.bn0(x)\n x = x.transpose(1, 3)\n \n if self.training:\n x = self.spec_augmenter(x)\n\n # Mixup on spectrogram\n if self.training and mixup_lambda is not None:\n x = do_mixup(x, mixup_lambda)\n \n x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block5(x, pool_size=(2, 2), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = self.conv_block6(x, pool_size=(1, 1), pool_type='avg')\n x = F.dropout(x, p=0.2, training=self.training)\n x = torch.mean(x, dim=3)\n \n x1 = F.max_pool1d(x, kernel_size=3, stride=1, padding=1)\n x2 = F.avg_pool1d(x, kernel_size=3, stride=1, padding=1)\n x = x1 + x2\n x = F.dropout(x, p=0.5, training=self.training)\n x = x.transpose(1, 2)\n x = F.relu_(self.fc1(x))\n x = x.transpose(1, 2)\n x = F.dropout(x, p=0.5, training=self.training)\n (clipwise_output, _, segmentwise_output) = self.att_block(x)\n segmentwise_output = segmentwise_output.transpose(1, 2)\n\n # Get framewise output\n framewise_output = interpolate(segmentwise_output, self.interpolate_ratio)\n framewise_output = pad_framewise_output(framewise_output, frames_num)\n\n output_dict = {'framewise_output': framewise_output, \n 'clipwise_output': clipwise_output}\n\n return output_dict\n", "import pandas as pd\nimport numpy as np\nfrom audioset_tagging_cnn.config import labels\nimport datetime\nfrom matplotlib import pyplot as plt \n\nfrom sklearn.manifold import TSNE\nfrom umap import UMAP\nimport datetime\n\ndef extract_subject(Df,partID):\n return Df[Df['id']==partID]\n\ndef return_preprocessed(Df,confin_day=datetime.date(2020,3,16)):\n # data\n allprobas = np.stack(Df['probas'])\n labelmax = np.argmax(allprobas,axis=1)\n allembed = np.stack(Df['embedding'])\n allndsi = np.stack(Df['ndsi'])\n allpeaks = np.stack(Df['nbpeaks'])\n\n\n # times in seconds after the first acquisition\n listtimes = list(Df['datetime'])\n listdates = list(Df['date'])\n\n t0 = listtimes[0]\n seconds_after = [(t-t0).total_seconds() for t in listtimes]\n\n days_after = [(t-confin_day).days for t in listdates]\n \n times = np.stack(Df['time'])\n night_day = np.stack([(curtime.hour < 19) & (curtime.hour > 4) for curtime in times]).astype(int)\n \n\n return seconds_after,allprobas,allembed,allndsi,night_day,labelmax,allpeaks,days_after\n\n\ndef process_tsne(Df,confin_day=datetime.date(2020,3,16)):\n secs,allprobas,allembed,allndsi,night_day,labelmax,allpeaks,days_after = return_preprocessed(Df,confin_day)\n mytsne = TSNE(n_components=2)\n embed_tsne = mytsne.fit_transform(allembed)\n return embed_tsne,secs,allprobas,allembed,allndsi,night_day,labelmax,allpeaks,days_after\n\n\n\ndef process_umap(Df,confin_day=datetime.date(2020,3,16)):\n secs,allprobas,allembed,allndsi,night_day,labelmax,allpeaks,days_after = return_preprocessed(Df,confin_day)\n myproj = UMAP(n_components=2,metric='cosine')\n embed_low = myproj.fit_transform(allembed)\n return embed_low,secs,allprobas,allembed,allndsi,night_day,labelmax,allpeaks,days_after\n\n\n\ndef keep_array_thresh(probasarray,threshold=0.1):\n array_max = np.max(probasarray,axis=0)\n ind_max = np.argwhere(array_max>threshold)\n\n return ind_max,array_max[ind_max]\n\n\n\n\ndef subset_probas(Df,search_labels):\n _,allprobas,_,_,_,_,_,_ = return_preprocessed(Df)\n\n ind_list = []\n for curlabel in search_labels:\n ind_list.append(int(np.argwhere([c==curlabel for c in labels])))\n\n return allprobas[:,ind_list]\n\n\ndef inverse_search(Df,label,thr):\n \n probas = subset_probas(Df,[label])\n\n ind_max = np.argwhere(probas>thr)[:,0]\n\n files = list(Df.file)\n\n datetime = list(Df.datetime)\n\n return [files[i] for i in ind_max],[datetime[i] for i in ind_max]\n \nfrom postprocess import fewlabels\ndef heatmap_probas(Df,search_labels=fewlabels,nbannot = 30):\n \n prob = subset_probas(Df,search_labels)\n nbobs = prob.shape[0]\n\n\n skiptime = nbobs//nbannot ### this is necessary to annotate the x axis, change this value to print more or less date / time labels\n\n timelabels = [''] * len(Df.datetime)\n\n origtimes = list(Df.datetime)\n\n for i in np.arange(0,len(origtimes),skiptime):\n timelabels[i] = origtimes[i]\n\n\n fig = plt.figure(figsize=(20,10))\n ax=plt.subplot(111)\n curac=ax.matshow(prob.T,vmin=0,aspect='auto',cmap=plt.cm.Reds)\n plt.yticks(ticks = range(len(search_labels)),labels=search_labels)\n plt.xticks(ticks = range(len(timelabels)),labels = timelabels,rotation=90)\n plt.colorbar(curac)\n return fig\n\ndef figure_embedding(Df,confin_day=datetime.date(2020,3,16)):\n\n embed_low,seconds_after,allprobas,allembed,allndsi,night_day,labelmax,allpeaks,days_after = process_umap(Df,confin_day)\n \n fig = plt.figure(figsize=(10,10))\n\n ax = plt.subplot(221)\n\n scatter = ax.scatter(embed_low[:,0],embed_low[:,1],c=labelmax,alpha=0.7,cmap=plt.cm.tab20)\n ind,indlabels = scatter.legend_elements(num=None)\n\n whichlabels = np.argwhere(np.bincount(labelmax)).ravel()\n\n labels_final = [labels[i] for i in whichlabels]\n\n # produce a legend with the unique colors from the scatter\n legend1 = ax.legend(ind,labels_final,\n loc=\"lower left\", title=\"Classes\",ncol=3,bbox_to_anchor=(0,1.1))\n plt.title('Colored by Label')\n\n ax = plt.subplot(222)\n\n scatter = ax.scatter(embed_low[:,0],embed_low[:,1],c=night_day,alpha=0.8)\n ind,indlabels = scatter.legend_elements(num=None)\n\n\n # produce a legend with the unique colors from the scatter\n legend1 = ax.legend(ind,['night','day'],\n loc=\"best\", title=\"Classes\",ncol=2)\n plt.title('Colored by Night / Day')\n\n #ax = plt.subplot(223)\n\n #scatter = ax.scatter(embed_umap[:,0],embed_umap[:,1],c=allndsi,alpha=0.6,cmap=plt.cm.RdBu_r)\n #fig.colorbar(scatter, ax=ax)\n #plt.title('Colored by NDSI')\n\n\n\n\n ax = plt.subplot(223)\n\n\n scatter = ax.scatter(embed_low[:,0],embed_low[:,1],c=allpeaks,alpha=0.6,cmap=plt.cm.hot)\n fig.colorbar(scatter, ax=ax,orientation='horizontal',fraction=0.042)\n plt.title('Only Nb Peaks')\n\n\n \"\"\" ax = plt.subplot(223)\n\n allndsi_neg = (allndsi < 0 )\n\n scatter = ax.scatter(embed_low[allndsi_neg,0],embed_low[allndsi_neg,1],c=allndsi[allndsi_neg],alpha=0.6,cmap=plt.cm.Blues_r)\n fig.colorbar(scatter, ax=ax)\n plt.title('Only negative NDSI') \"\"\"\n\n\n \"\"\" \n ax = plt.subplot(224)\n\n allndsi_pos = (allndsi > 0 )\n\n scatter = ax.scatter(embed_low[allndsi_pos,0],embed_low[allndsi_pos,1],c=allndsi[allndsi_pos],alpha=0.6,cmap=plt.cm.spring)\n fig.colorbar(scatter, ax=ax)\n plt.title('Only positive NDSI')\n \"\"\"\n\n\n ax = plt.subplot(224)\n\n\n scatter = ax.scatter(embed_low[:,0],embed_low[:,1],c=days_after,alpha=0.1,cmap=plt.cm.hot,vmin=-2)\n fig.colorbar(scatter, ax=ax,orientation='horizontal',fraction=0.042)\n plt.title('Colored by day after confinement')\n \n \n \n return fig" ]
[ [ "torch.nn.Linear", "torch.cat", "torch.nn.BatchNorm2d", "torch.sum", "torch.sigmoid", "torch.nn.functional.avg_pool2d", "torch.nn.AvgPool1d", "torch.nn.Conv1d", "torch.nn.init.constant_", "torch.nn.AvgPool2d", "torch.max", "torch.nn.Sequential", "torch.nn.functional.dropout", "torch.nn.ReLU", "torch.nn.Conv2d", "torch.nn.functional.max_pool1d", "torch.nn.functional.relu_", "torch.nn.init.xavier_uniform_", "torch.nn.functional.avg_pool1d", "torch.nn.ReLU6", "torch.nn.BatchNorm1d", "torch.nn.functional.max_pool2d", "torch.mean" ], [ "numpy.max", "numpy.bincount", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.title", "sklearn.manifold.TSNE", "matplotlib.pyplot.figure", "numpy.stack", "numpy.argmax", "numpy.argwhere", "matplotlib.pyplot.subplot" ] ]
madsbk/veros
[ "00d2c33e28f0bd098a81bd6ac48436067e7eb8f5" ]
[ "veros/setup/wave_propagation/wave_propagation.py" ]
[ "#!/usr/bin/env python\n\nimport os\nimport logging\n\nimport numpy as np\nfrom netCDF4 import Dataset\nfrom PIL import Image\nimport scipy.ndimage\n\nimport veros\nimport veros.tools\nimport veros.core.cyclic\n\nBASE_PATH = os.path.dirname(os.path.realpath(__file__))\nDATA_FILES = veros.tools.get_assets(\"wave_propagation\", os.path.join(BASE_PATH, \"assets.yml\"))\nTOPO_MASK_FILE = os.path.join(BASE_PATH, \"topography_idealized.png\")\nNA_MASK_FILE = os.path.join(BASE_PATH, \"na_mask.png\")\n\n\nclass WavePropagation(veros.Veros):\n \"\"\"\n Global model with flexible resolution and idealized geometry in the\n Atlantic to examine coastal wave propagation.\n \"\"\"\n # settings for north atlantic\n na_shelf_depth = 250\n na_shelf_distance = 0\n na_slope_length = 600e3\n na_max_depth = 4000\n\n # global settings\n max_depth = 5600.\n equatorial_grid_spacing = 0.5\n polar_grid_spacing = None\n\n # southern ocean wind modifier\n so_wind_interval = (-69., -27.)\n so_wind_factor = 1.\n\n @veros.veros_method\n def set_parameter(self):\n self.identifier = \"wp\"\n\n self.nx = 180\n self.ny = 180\n self.nz = 60\n self.dt_mom = self.dt_tracer = 0\n self.runlen = 86400 * 10\n\n self.coord_degree = True\n self.enable_cyclic_x = True\n\n # streamfunction\n self.congr_epsilon = 1e-6\n self.congr_max_iterations = 10000\n\n # friction\n self.enable_hor_friction = True\n self.A_h = 5e4\n self.enable_hor_friction_cos_scaling = True\n self.hor_friction_cosPower = 1\n self.enable_tempsalt_sources = True\n self.enable_implicit_vert_friction = True\n\n self.eq_of_state_type = 5\n\n # isoneutral\n self.enable_neutral_diffusion = True\n self.K_iso_0 = 1000.0\n self.K_iso_steep = 50.0\n self.iso_dslope = 0.005\n self.iso_slopec = 0.005\n self.enable_skew_diffusion = True\n\n # tke\n self.enable_tke = True\n self.c_k = 0.1\n self.c_eps = 0.7\n self.alpha_tke = 30.0\n self.mxl_min = 1e-8\n self.tke_mxl_choice = 2\n self.enable_tke_superbee_advection = True\n\n # eke\n self.enable_eke = True\n self.eke_k_max = 1e4\n self.eke_c_k = 0.4\n self.eke_c_eps = 0.5\n self.eke_cross = 2.\n self.eke_crhin = 1.0\n self.eke_lmin = 100.0\n self.enable_eke_superbee_advection = True\n self.enable_eke_isopycnal_diffusion = True\n\n # idemix\n self.enable_idemix = False\n self.enable_eke_diss_surfbot = True\n self.eke_diss_surfbot_frac = 0.2\n self.enable_idemix_superbee_advection = True\n self.enable_idemix_hor_diffusion = True\n\n def _get_data(self, var):\n with Dataset(DATA_FILES[\"forcing\"], \"r\") as forcing_file:\n return forcing_file.variables[var][...].T\n\n @veros.veros_method\n def set_grid(self):\n if self.ny % 2:\n raise ValueError(\"ny has to be an even number of grid cells\")\n self.dxt[...] = 360. / self.nx\n self.dyt[2:-2] = veros.tools.get_vinokur_grid_steps(\n self.ny, 160., self.equatorial_grid_spacing, upper_stepsize=self.polar_grid_spacing, two_sided_grid=True\n )\n self.dzt[...] = veros.tools.get_vinokur_grid_steps(self.nz, self.max_depth, 10., refine_towards=\"lower\")\n self.y_origin = -80.\n self.x_origin = 90.\n\n @veros.veros_method\n def set_coriolis(self):\n self.coriolis_t[...] = 2 * self.omega * np.sin(self.yt[np.newaxis, :] / 180. * self.pi)\n\n @veros.veros_method\n def _shift_longitude_array(self, lon, arr):\n wrap_i = np.where((lon[:-1] < self.xt.min()) & (lon[1:] >= self.xt.min()))[0][0]\n new_lon = np.concatenate((lon[wrap_i:-1], lon[:wrap_i] + 360.))\n new_arr = np.concatenate((arr[wrap_i:-1, ...], arr[:wrap_i, ...]))\n return new_lon, new_arr\n\n @veros.veros_method\n def set_topography(self):\n with Dataset(DATA_FILES[\"topography\"], \"r\") as topography_file:\n topo_x, topo_y, topo_z = (topography_file.variables[k][...].T.astype(np.float) for k in (\"x\", \"y\", \"z\"))\n topo_z[topo_z > 0] = 0.\n topo_mask = (np.flipud(Image.open(TOPO_MASK_FILE)).T / 255).astype(np.bool)\n gaussian_sigma = (0.5 * len(topo_x) / self.nx, 0.5 * len(topo_y) / self.ny)\n topo_z_smoothed = scipy.ndimage.gaussian_filter(topo_z, sigma=gaussian_sigma)\n topo_z_smoothed[~topo_mask & (topo_z_smoothed >= 0.)] = -100.\n topo_masked = np.where(topo_mask, 0., topo_z_smoothed)\n\n na_mask_image = np.flipud(Image.open(NA_MASK_FILE)).T / 255.\n topo_x_shifted, na_mask_shifted = self._shift_longitude_array(topo_x, na_mask_image)\n coords = (self.xt[2:-2], self.yt[2:-2])\n self.na_mask = np.zeros((self.nx + 4, self.ny + 4), dtype=np.bool)\n self.na_mask[2:-2, 2:-2] = np.logical_not(veros.tools.interpolate(\n (topo_x_shifted, topo_y), na_mask_shifted, coords, kind=\"nearest\", fill=False\n ).astype(np.bool))\n\n topo_x_shifted, topo_masked_shifted = self._shift_longitude_array(topo_x, topo_masked)\n z_interp = veros.tools.interpolate(\n (topo_x_shifted, topo_y), topo_masked_shifted, coords, kind=\"nearest\", fill=False\n )\n z_interp[self.na_mask[2:-2, 2:-2]] = -self.na_max_depth\n\n grid_coords = np.meshgrid(*coords, indexing=\"ij\")\n coastline_distance = veros.tools.get_coastline_distance(\n grid_coords, z_interp >= 0, spherical=True, radius=self.radius\n )\n if self.na_slope_length:\n slope_distance = coastline_distance - self.na_shelf_distance\n slope_mask = np.logical_and(self.na_mask[2:-2, 2:-2], slope_distance < self.na_slope_length)\n z_interp[slope_mask] = -(self.na_shelf_depth + slope_distance[slope_mask] / self.na_slope_length \\\n * (self.na_max_depth - self.na_shelf_depth))\n if self.na_shelf_distance:\n shelf_mask = np.logical_and(self.na_mask[2:-2, 2:-2], coastline_distance < self.na_shelf_distance)\n z_interp[shelf_mask] = -self.na_shelf_depth\n\n depth_levels = 1 + np.argmin(np.abs(z_interp[:, :, np.newaxis] - self.zt[np.newaxis, np.newaxis, :]), axis=2)\n self.kbot[2:-2, 2:-2] = np.where(z_interp < 0., depth_levels, 0)\n self.kbot *= self.kbot < self.nz\n\n @veros.veros_method\n def _fix_north_atlantic(self, arr):\n \"\"\"Calculate zonal mean forcing over masked area (na_mask).\"\"\"\n newaxes = (slice(2, -2), slice(2, -2)) + (np.newaxis,) * (arr.ndim - 2)\n arr_masked = np.ma.masked_where(np.logical_or(~self.na_mask[newaxes], arr == 0.), arr)\n zonal_mean_na = arr_masked.mean(axis=0)\n return np.where(~arr_masked.mask, zonal_mean_na[np.newaxis, ...], arr)\n\n @veros.veros_method\n def set_initial_conditions(self):\n self._t_star = np.zeros((self.nx + 4, self.ny + 4, 12), dtype=self.default_float_type)\n self._s_star = np.zeros((self.nx + 4, self.ny + 4, 12), dtype=self.default_float_type)\n self._qnec = np.zeros((self.nx + 4, self.ny + 4, 12), dtype=self.default_float_type)\n self._qnet = np.zeros((self.nx + 4, self.ny + 4, 12), dtype=self.default_float_type)\n self._qsol = np.zeros((self.nx + 4, self.ny + 4, 12), dtype=self.default_float_type)\n self._divpen_shortwave = np.zeros(self.nz, dtype=self.default_float_type)\n self._taux = np.zeros((self.nx + 4, self.ny + 4, 12), dtype=self.default_float_type)\n self._tauy = np.zeros((self.nx + 4, self.ny + 4, 12), dtype=self.default_float_type)\n\n rpart_shortwave = 0.58\n efold1_shortwave = 0.35\n efold2_shortwave = 23.0\n\n t_grid = (self.xt[2:-2], self.yt[2:-2], self.zt)\n xt_forc, yt_forc, zt_forc = (self._get_data(k) for k in (\"xt\", \"yt\", \"zt\"))\n zt_forc = zt_forc[::-1]\n\n # initial conditions\n temp_data = veros.tools.interpolate((xt_forc, yt_forc, zt_forc), self._get_data(\"temperature\")[:, :, ::-1],\n t_grid, missing_value=0.)\n self.temp[2:-2, 2:-2, :, 0] = temp_data * self.maskT[2:-2, 2:-2, :]\n self.temp[2:-2, 2:-2, :, 1] = temp_data * self.maskT[2:-2, 2:-2, :]\n\n salt_data = veros.tools.interpolate((xt_forc, yt_forc, zt_forc), self._get_data(\"salinity\")[:, :, ::-1],\n t_grid, missing_value=0.)\n self.salt[2:-2, 2:-2, :, 0] = salt_data * self.maskT[2:-2, 2:-2, :]\n self.salt[2:-2, 2:-2, :, 1] = salt_data * self.maskT[2:-2, 2:-2, :]\n\n # wind stress on MIT grid\n time_grid = (self.xt[2:-2], self.yt[2:-2], np.arange(12))\n taux_data = veros.tools.interpolate((xt_forc, yt_forc, np.arange(12)),\n self._get_data(\"tau_x\"), time_grid,\n missing_value=0.)\n self._taux[2:-2, 2:-2, :] = taux_data / self.rho_0\n mask = np.logical_and(self.yt > self.so_wind_interval[0], self.yt < self.so_wind_interval[1])[..., np.newaxis]\n self._taux *= 1. + mask * (self.so_wind_factor - 1.) * np.sin(np.pi * (self.yt[np.newaxis, :, np.newaxis] - self.so_wind_interval[0]) \\\n / (self.so_wind_interval[1] - self.so_wind_interval[0]))\n\n tauy_data = veros.tools.interpolate((xt_forc, yt_forc, np.arange(12)),\n self._get_data(\"tau_y\"), time_grid,\n missing_value=0.)\n self._tauy[2:-2, 2:-2, :] = tauy_data / self.rho_0\n\n if self.enable_cyclic_x:\n veros.core.cyclic.setcyclic_x(self._taux)\n veros.core.cyclic.setcyclic_x(self._tauy)\n\n # Qnet and dQ/dT and Qsol\n qnet_data = veros.tools.interpolate((xt_forc, yt_forc, np.arange(12)),\n self._get_data(\"q_net\"), time_grid, missing_value=0.)\n self._qnet[2:-2, 2:-2, :] = -qnet_data * self.maskT[2:-2, 2:-2, -1, np.newaxis]\n\n qnec_data = veros.tools.interpolate((xt_forc, yt_forc, np.arange(12)),\n self._get_data(\"dqdt\"), time_grid, missing_value=0.)\n self._qnec[2:-2, 2:-2, :] = qnec_data * self.maskT[2:-2, 2:-2, -1, np.newaxis]\n\n qsol_data = veros.tools.interpolate((xt_forc, yt_forc, np.arange(12)),\n self._get_data(\"swf\"), time_grid, missing_value=0.)\n self._qsol[2:-2, 2:-2, :] = -qsol_data * self.maskT[2:-2, 2:-2, -1, np.newaxis]\n\n # SST and SSS\n sst_data = veros.tools.interpolate((xt_forc, yt_forc, np.arange(12)),\n self._get_data(\"sst\"), time_grid, missing_value=0.)\n self._t_star[2:-2, 2:-2, :] = sst_data * self.maskT[2:-2, 2:-2, -1, np.newaxis]\n\n sss_data = veros.tools.interpolate((xt_forc, yt_forc, np.arange(12)),\n self._get_data(\"sss\"), time_grid, missing_value=0.)\n self._s_star[2:-2, 2:-2, :] = sss_data * self.maskT[2:-2, 2:-2, -1, np.newaxis]\n\n if self.enable_idemix:\n tidal_energy_data = veros.tools.interpolate(\n (xt_forc, yt_forc), self._get_data(\"tidal_energy\"), t_grid[:-1], missing_value=0.\n )\n mask_x, mask_y = (i + 2 for i in np.indices((self.nx, self.ny)))\n mask_z = np.maximum(0, self.kbot[2:-2, 2:-2] - 1)\n tidal_energy_data[:, :] *= self.maskW[mask_x, mask_y, mask_z] / self.rho_0\n self.forc_iw_bottom[2:-2, 2:-2] = tidal_energy_data\n\n # average variables in North Atlantic\n na_average_vars = [self._taux, self._tauy, self._qnet, self._qnec, self._qsol,\n self._t_star, self._s_star, self.salt, self.temp]\n if self.enable_idemix:\n na_average_vars += [self.forc_iw_bottom]\n for k in na_average_vars:\n k[2:-2, 2:-2, ...] = self._fix_north_atlantic(k[2:-2, 2:-2, ...])\n\n \"\"\"\n Initialize penetration profile for solar radiation and store divergence in divpen\n note that pen is set to 0.0 at the surface instead of 1.0 to compensate for the\n shortwave part of the total surface flux\n \"\"\"\n swarg1 = self.zw / efold1_shortwave\n swarg2 = self.zw / efold2_shortwave\n pen = rpart_shortwave * np.exp(swarg1) + (1.0 - rpart_shortwave) * np.exp(swarg2)\n pen[-1] = 0.\n self._divpen_shortwave[1:] = (pen[1:] - pen[:-1]) / self.dzt[1:]\n self._divpen_shortwave[0] = pen[0] / self.dzt[0]\n\n @veros.veros_method\n def set_forcing(self):\n self.set_timestep()\n\n t_rest = 30. * 86400.\n cp_0 = 3991.86795711963 # J/kg /K\n\n year_in_seconds = 360 * 86400.\n (n1, f1), (n2, f2) = veros.tools.get_periodic_interval(\n self.time, year_in_seconds, year_in_seconds / 12., 12\n )\n\n self.surface_taux[...] = f1 * self._taux[:, :, n1] + f2 * self._taux[:, :, n2]\n self.surface_tauy[...] = f1 * self._tauy[:, :, n1] + f2 * self._tauy[:, :, n2]\n\n if self.enable_tke:\n self.forc_tke_surface[1:-1, 1:-1] = np.sqrt((0.5 * (self.surface_taux[1:-1, 1:-1] + self.surface_taux[:-2, 1:-1])) ** 2\n + (0.5 * (self.surface_tauy[1:-1, 1:-1] + self.surface_tauy[1:-1, :-2])) ** 2) ** (3. / 2.)\n\n # W/m^2 K kg/J m^3/kg = K m/s\n fxa = f1 * self._t_star[..., n1] + f2 * self._t_star[..., n2]\n self._qqnec = f1 * self._qnec[..., n1] + f2 * self._qnec[..., n2]\n self._qqnet = f1 * self._qnet[..., n1] + f2 * self._qnet[..., n2]\n self.forc_temp_surface[...] = (self._qqnet + self._qqnec * (fxa - self.temp[..., -1, self.tau])) \\\n * self.maskT[..., -1] / cp_0 / self.rho_0\n fxa = f1 * self._s_star[..., n1] + f2 * self._s_star[..., n2]\n self.forc_salt_surface[...] = 1. / t_rest * \\\n (fxa - self.salt[..., -1, self.tau]) * self.maskT[..., -1] * self.dzt[-1]\n\n # apply simple ice mask\n mask1 = self.temp[:, :, -1, self.tau] * self.maskT[:, :, -1] <= -1.8\n mask2 = self.forc_temp_surface <= 0\n ice = ~(mask1 & mask2)\n self.forc_temp_surface[...] *= ice\n self.forc_salt_surface[...] *= ice\n\n # solar radiation\n if self.enable_tempsalt_sources:\n self.temp_source[..., :] = (f1 * self._qsol[..., n1, None] + f2 * self._qsol[..., n2, None]) \\\n * self._divpen_shortwave[None, None, :] * ice[..., None] \\\n * self.maskT[..., :] / cp_0 / self.rho_0\n\n @veros.veros_method\n def set_diagnostics(self):\n self.diagnostics[\"cfl_monitor\"].output_frequency = 86400.\n self.diagnostics[\"tracer_monitor\"].output_frequency = 86400.\n self.diagnostics[\"snapshot\"].output_frequency = 10 * 86400.\n self.diagnostics[\"overturning\"].output_frequency = 360 * 86400\n self.diagnostics[\"overturning\"].sampling_frequency = 10 * 86400\n self.diagnostics[\"energy\"].output_frequency = 360 * 86400\n self.diagnostics[\"energy\"].sampling_frequency = 86400.\n self.diagnostics[\"averages\"].output_frequency = 360 * 86400\n self.diagnostics[\"averages\"].sampling_frequency = 86400.\n\n average_vars = [\"surface_taux\", \"surface_tauy\", \"forc_temp_surface\", \"forc_salt_surface\",\n \"psi\", \"temp\", \"salt\", \"u\", \"v\", \"w\", \"Nsqr\", \"Hd\", \"rho\",\n \"K_diss_v\", \"P_diss_v\", \"P_diss_nonlin\", \"P_diss_iso\", \"kappaH\"]\n if self.enable_skew_diffusion:\n average_vars += [\"B1_gm\", \"B2_gm\"]\n if self.enable_TEM_friction:\n average_vars += [\"kappa_gm\", \"K_diss_gm\"]\n if self.enable_tke:\n average_vars += [\"tke\", \"Prandtlnumber\", \"mxl\", \"tke_diss\",\n \"forc_tke_surface\", \"tke_surf_corr\"]\n if self.enable_idemix:\n average_vars += [\"E_iw\", \"forc_iw_surface\", \"forc_iw_bottom\", \"iw_diss\",\n \"c0\", \"v0\"]\n if self.enable_eke:\n average_vars += [\"eke\", \"K_gm\", \"L_rossby\", \"L_rhines\"]\n self.diagnostics[\"averages\"].output_variables = average_vars\n\n self.variables[\"na_mask\"] = veros.variables.Variable(\n \"Mask for North Atlantic\", (\"xt\", \"yt\"), \"\", \"Mask for North Atlantic\",\n dtype=\"int\", time_dependent=False, output=True\n )\n self.diagnostics[\"snapshot\"].output_variables.append(\"na_mask\")\n\n @veros.veros_method\n def set_timestep(self):\n if self.time < 90 * 86400:\n if self.dt_tracer != 1800.:\n self.dt_tracer = self.dt_mom = 1800.\n logging.info(\"Setting time step to 30m\")\n else:\n if self.dt_tracer != 3600.:\n self.dt_tracer = self.dt_mom = 3600.\n logging.info(\"Setting time step to 1h\")\n\n def after_timestep(self):\n pass\n\n\[email protected]\ndef run(*args, **kwargs):\n simulation = WavePropagation(*args, **kwargs)\n simulation.setup()\n simulation.run()\n\n\nif __name__ == \"__main__\":\n run()\n" ]
[ [ "numpy.concatenate", "numpy.logical_or", "numpy.sin", "numpy.zeros", "numpy.exp", "numpy.logical_and", "numpy.where", "numpy.arange", "numpy.abs", "numpy.sqrt", "numpy.indices", "numpy.meshgrid", "numpy.maximum" ] ]
JPHaus/finding-donors
[ "acc13d3708b70f698d0f288d86a5c31026754f5a" ]
[ "visuals.py" ]
[ "###########################################\n# Suppress matplotlib user warnings\n# Necessary for newer version of matplotlib\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n#\n# Display inline matplotlib plots with IPython\nfrom IPython import get_ipython\nget_ipython().run_line_magic('matplotlib', 'inline')\n###########################################\n\nimport matplotlib.pyplot as pl\nimport matplotlib.patches as mpatches\nimport numpy as np\nimport pandas as pd\nfrom time import time\nfrom sklearn.metrics import f1_score, accuracy_score\n\n\ndef distribution(data, transformed = False):\n \"\"\"\n Visualization code for displaying skewed distributions of features\n \"\"\"\n \n # Create figure\n fig = pl.figure(figsize = (11,5));\n\n # Skewed feature plotting\n for i, feature in enumerate(['capital-gain','capital-loss']):\n ax = fig.add_subplot(1, 2, i+1)\n ax.hist(data[feature], bins = 25, color = '#00A0A0')\n ax.set_title(\"'%s' Feature Distribution\"%(feature), fontsize = 14)\n ax.set_xlabel(\"Value\")\n ax.set_ylabel(\"Number of Records\")\n ax.set_ylim((0, 2000))\n ax.set_yticks([0, 500, 1000, 1500, 2000])\n ax.set_yticklabels([0, 500, 1000, 1500, \">2000\"])\n\n # Plot aesthetics\n if transformed:\n fig.suptitle(\"Log-transformed Distributions of Continuous Census Data Features\", \\\n fontsize = 16, y = 1.03)\n else:\n fig.suptitle(\"Skewed Distributions of Continuous Census Data Features\", \\\n fontsize = 16, y = 1.03)\n\n fig.tight_layout()\n fig.show()\n\n\ndef evaluate(results, accuracy, f1):\n \"\"\"\n Visualization code to display results of various learners.\n \n inputs:\n - learners: a list of supervised learners\n - stats: a list of dictionaries of the statistic results from 'train_predict()'\n - accuracy: The score for the naive predictor\n - f1: The score for the naive predictor\n \"\"\"\n \n # Create figure\n fig, ax = pl.subplots(2, 3, figsize = (11,7))\n\n # Constants\n bar_width = 0.3\n colors = ['#A00000','#00A0A0','#00A000']\n \n # Super loop to plot four panels of data\n for k, learner in enumerate(results.keys()):\n for j, metric in enumerate(['train_time', 'acc_train', 'f_train', 'pred_time', 'acc_test', 'f_test']):\n for i in np.arange(3):\n \n # Creative plot code\n ax[int(j/3), j%3].bar(i+k*bar_width, results[learner][i][metric], width = bar_width, color = colors[k])\n ax[int(j/3), j%3].set_xticks([0.45, 1.45, 2.45])\n ax[int(j/3), j%3].set_xticklabels([\"1%\", \"10%\", \"100%\"])\n ax[int(j/3), j%3].set_xlabel(\"Training Set Size\")\n ax[int(j/3), j%3].set_xlim((-0.1, 3.0))\n \n # Add unique y-labels\n ax[0, 0].set_ylabel(\"Time (in seconds)\")\n ax[0, 1].set_ylabel(\"Accuracy Score\")\n ax[0, 2].set_ylabel(\"F-score\")\n ax[1, 0].set_ylabel(\"Time (in seconds)\")\n ax[1, 1].set_ylabel(\"Accuracy Score\")\n ax[1, 2].set_ylabel(\"F-score\")\n \n # Add titles\n ax[0, 0].set_title(\"Model Training\")\n ax[0, 1].set_title(\"Accuracy Score on Training Subset\")\n ax[0, 2].set_title(\"F-score on Training Subset\")\n ax[1, 0].set_title(\"Model Predicting\")\n ax[1, 1].set_title(\"Accuracy Score on Testing Set\")\n ax[1, 2].set_title(\"F-score on Testing Set\")\n \n # Add horizontal lines for naive predictors\n ax[0, 1].axhline(y = accuracy, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')\n ax[1, 1].axhline(y = accuracy, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')\n ax[0, 2].axhline(y = f1, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')\n ax[1, 2].axhline(y = f1, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')\n \n # Set y-limits for score panels\n ax[0, 1].set_ylim((0, 1))\n ax[0, 2].set_ylim((0, 1))\n ax[1, 1].set_ylim((0, 1))\n ax[1, 2].set_ylim((0, 1))\n\n # Create patches for the legend\n patches = []\n for i, learner in enumerate(results.keys()):\n patches.append(mpatches.Patch(color = colors[i], label = learner))\n pl.legend(handles = patches, bbox_to_anchor = (-.80, 2.53), \\\n loc = 'upper center', borderaxespad = 0., ncol = 3, fontsize = 'x-large')\n \n # Aesthetics\n pl.suptitle(\"Performance Metrics for Three Supervised Learning Models\", fontsize = 16, y = 1.10)\n pl.tight_layout()\n pl.show()\n \n\ndef feature_plot(importances, X_train, y_train):\n \n # Display the five most important features\n indices = np.argsort(importances)[::-1]\n columns = X_train.columns.values[indices[:5]]\n values = importances[indices][:5]\n\n # Creat the plot\n fig = pl.figure(figsize = (9,5))\n pl.title(\"Normalized Weights for First Five Most Predictive Features\", fontsize = 16)\n pl.bar(np.arange(5), values, width = 0.6, align=\"center\", color = '#00A000', \\\n label = \"Feature Weight\")\n pl.bar(np.arange(5) - 0.3, np.cumsum(values), width = 0.2, align = \"center\", color = '#00A0A0', \\\n label = \"Cumulative Feature Weight\")\n pl.xticks(np.arange(5), columns)\n pl.xlim((-0.5, 4.5))\n pl.ylabel(\"Weight\", fontsize = 12)\n pl.xlabel(\"Feature\", fontsize = 12)\n \n pl.legend(loc = 'upper center')\n pl.tight_layout()\n pl.show() \n" ]
[ [ "matplotlib.pyplot.xlim", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.suptitle", "matplotlib.pyplot.legend", "matplotlib.pyplot.title", "matplotlib.pyplot.subplots", "matplotlib.pyplot.figure", "matplotlib.patches.Patch", "numpy.arange", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.ylabel", "numpy.argsort", "numpy.cumsum", "matplotlib.pyplot.show" ] ]
facebookresearch/multimodal
[ "13e60d9b4e421d1d5304e861cf4e54c3e376c7f1" ]
[ "torchmultimodal/transforms/text_transforms.py" ]
[ "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom typing import List, Union\n\nimport torch\nimport torch.nn.functional as F\n\n\nclass PadTransform:\n def __init__(self, max_length: int):\n self.max_length = max_length\n\n def __call__(self, texts: torch.Tensor) -> torch.Tensor:\n max_encoded_length = texts.size(-1)\n if max_encoded_length < self.max_length:\n pad_amount = self.max_length - max_encoded_length\n texts = F.pad(texts, (0, pad_amount))\n return texts\n\n\nclass StrToIntTransform:\n def __init__(self):\n pass\n\n def __call__(\n self, l: Union[List[str], List[List[str]]]\n ) -> Union[List[int], List[List[int]]]:\n if isinstance(l[0], str):\n return [int(x) for x in l] # type: ignore\n if isinstance(l[0], List) and isinstance(l[0][0], str):\n return [[int(x) for x in ll] for ll in l]\n else:\n raise TypeError(\"Input type not supported\")\n" ]
[ [ "torch.nn.functional.pad" ] ]
ishikei14k/atma11_1st_solution
[ "91d29eb83f3e5470f82470f0434ad0fc75a90c61" ]
[ "src/factory.py" ]
[ "#!/usr/bin/env python\n# coding: utf-8\n\nimport numpy as np\nimport torch\nfrom torch import nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nimport albumentations as A\nfrom albumentations.pytorch.transforms import ToTensorV2\nfrom dataset.custom_dataset import *\nfrom models.custom_model import *\nfrom loss.custom_loss import *\n\n\ndef get_imgs(input_npy_dir):\n imgs = np.load(input_npy_dir / 'train_imgs_numpy_array_200840x128x128_just_resize_wo_maximize.npy')\n imgs = np.reshape(imgs, (-1, 128, 128)).astype(np.uint8)\n return imgs\n\n\ndef get_transforms(cfg):\n def get_object(transform):\n if hasattr(A, transform.name):\n return getattr(A, transform.name)\n else:\n return eval(transform.name)\n transforms = [get_object(transform)(**transform.params) for transform in cfg.transforms]\n return A.Compose(transforms)\n\n\ndef get_dataset(cfg, folds, transforms):\n return eval(cfg.dataset_name)(cfg, folds, transforms)\n\n\ndef get_dataset_loader(cfg, folds):\n transforms = get_transforms(cfg)\n dataset = get_dataset(cfg, folds, transforms)\n loader = DataLoader(dataset, **cfg.loader)\n return dataset, loader\n\n\ndef get_model(cfg):\n return eval(cfg.name)(cfg.architecture, **cfg.params)\n\n\ndef get_device(device_no=0):\n return torch.device(f\"cuda:{device_no}\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef get_optimizer(cfg):\n if hasattr(optim, cfg.name):\n optimizer = getattr(optim, cfg.name)\n else:\n optimizer = eval(cfg.name)\n return optimizer\n\n\ndef get_loss(cfg):\n if hasattr(nn, cfg.name):\n loss = getattr(nn, cfg.name)(**cfg.params)\n else:\n loss = eval(cfg.name)(**cfg.params)\n return loss\n\n\ndef get_scheduler(cfg, optimizer):\n if hasattr(optim.lr_scheduler, cfg.name):\n scheduler = getattr(optim.lr_scheduler, cfg.name)(optimizer, **cfg.params)\n else:\n scheduler = eval(cfg.name)(optimizer, **cfg.params)\n return scheduler\n\n" ]
[ [ "numpy.reshape", "torch.cuda.is_available", "numpy.load", "torch.utils.data.DataLoader" ] ]
ShintaroMinami/PDBBasic
[ "979a6d150d202a24113c60409b717f2417ae9291" ]
[ "pdbbasic/utils.py" ]
[ "import numpy as np\nimport torch\n\ndef unsqueeze(data, dim=0):\n return data.unsqueeze(dim) if torch.is_tensor(data) else np.expand_dims(np.array(data), dim)\n" ]
[ [ "torch.is_tensor", "numpy.array" ] ]
LukasNickel/cta_preprocessing
[ "0db9673a8a08739f70fb370d0f6ed8daa86b26fb" ]
[ "cta_preprocessing/file_processing.py" ]
[ "from .event_processing import event_information\nfrom .event_processing import process_event\nfrom .event_processing import number_of_valid_triggerd_cameras\nfrom ctapipe.io.eventsourcefactory import EventSourceFactory\nfrom ctapipe.io.lsteventsource import LSTEventSource\nfrom ctapipe.calib import CameraCalibrator\nfrom ctapipe.reco.HillasReconstructor import TooFewTelescopesException\nfrom ctapipe.io import SimTelEventSource\nimport pandas as pd\nimport fact.io\nimport eventio\nfrom tqdm import tqdm\nfrom pathlib import Path\n\n\ndef process_data(input_file,\n config,\n return_input_file=False):\n\n event_source = EventSourceFactory.produce(\n input_url=input_file.as_posix(),\n max_events=config.n_events if config.n_events > 1 else None,\n product='LSTEventSource',\n )\n calibrator = CameraCalibrator(\n eventsource=event_source,\n r1_product='NullR1Calibrator', ## needs to be replaced?\n extractor_product=config.integrator,\n )\n \n df_runs = pd.DataFrame()\n array_events = pd.DataFrame()\n telescope_events = pd.DataFrame()\n if return_input_file:\n return df_runs, array_events, telescope_events, input_file\n return df_runs, array_events, telescope_events\n\n\ndef process_file(input_file,\n config,\n return_input_file=False,\n product='SimTelEventSource'):\n\n event_source = EventSourceFactory.produce(\n input_url=input_file.as_posix(),\n max_events=config.n_events if config.n_events > 1 else None,\n product=product,\n )\n\n #event_source.allowed_tels = config.allowed_telescope_ids # if we only want one telescope later\n\n calibrator = CameraCalibrator(\n eventsource=event_source,\n r1_product='HESSIOR1Calibrator',\n extractor_product=config.integrator,\n )\n\n telescope_event_information = []\n array_event_information = []\n for event in tqdm(event_source, disable=config.silent):\n if number_of_valid_triggerd_cameras(event, config) < config.min_number_of_valid_triggered_cameras:\n continue\n\n calibrator.calibrate(event)\n try:\n image_features, reconstruction, _ = process_event(event,\n config\n )\n event_features = event_information(event, \n image_features,\n reconstruction,\n config\n )\n array_event_information.append(event_features)\n telescope_event_information.append(image_features)\n except TooFewTelescopesException:\n continue\n\n telescope_events = pd.concat(telescope_event_information)\n if not telescope_events.empty:\n telescope_events.set_index(['run_id',\n 'array_event_id',\n 'telescope_id'],\n drop=True,\n verify_integrity=True,\n inplace=True\n )\n\n array_events = pd.DataFrame(array_event_information)\n if not array_events.empty:\n array_events.set_index(['run_id',\n 'array_event_id'],\n drop=True,\n verify_integrity=True,\n inplace=True\n )\n\n run_information = read_simtel_mc_information(input_file) ### TODO: adapt to real data\n df_runs = pd.DataFrame([run_information])\n if not df_runs.empty:\n df_runs.set_index('run_id',\n drop=True,\n verify_integrity=True,\n inplace=True)\n\n if return_input_file:\n return df_runs, array_events, telescope_events, input_file\n return df_runs, array_events, telescope_events\n\n\ndef verify_file(input_file_path):\n runs = fact.io.read_data(input_file_path.as_posix(), key='runs') ## same thing with real data\n runs.set_index('run_id', drop=True, verify_integrity=True, inplace=True)\n\n telescope_events = fact.io.read_data(input_file_path.as_posix(),\n key='telescope_events'\n )\n telescope_events.set_index(['run_id', 'array_event_id', 'telescope_id'],\n drop=True,\n verify_integrity=True,\n inplace=True\n )\n\n array_events = fact.io.read_data(input_file_path.as_posix(),\n key='array_events'\n )\n array_events.set_index(['run_id', 'array_event_id'],\n drop=True,\n verify_integrity=True,\n inplace=True\n )\n\n print('''Processed {} runs,\n {} single telescope events\n and {} array events.'''.format(len(runs),\n len(telescope_events),\n len(array_events)))\n\n\ndef read_simtel_mc_information(simtel_file):\n with eventio.SimTelFile(simtel_file.as_posix()) as f:\n header = f.mc_run_headers[-1] # these should all be the same, this is whats suggested by MaxNoe\n d = {\n 'mc_spectral_index': header['spectral_index'],\n 'mc_num_reuse': header['num_use'],\n 'mc_num_showers': header['num_showers'],\n 'mc_max_energy': header['E_range'][1],\n 'mc_min_energy': header['E_range'][0],\n 'mc_max_scatter_range': header['core_range'][1], # range_X is always 0 in simtel files\n 'mc_max_viewcone_radius': header['viewcone'][1],\n 'mc_min_viewcone_radius': header['viewcone'][0],\n 'run_id': f.header['run'],\n 'mc_max_altitude': header['alt_range'][1],\n 'mc_max_azimuth': header['az_range'][1],\n 'mc_min_altitude': header['alt_range'][0],\n 'mc_min_azimuth': header['az_range'][0],\n }\n\n return d\n\n\ndef write_output(runs, array_events, telescope_events, output_file):\n fact.io.write_data(runs,\n output_file.as_posix(),\n key='runs',\n mode='w'\n )\n fact.io.write_data(array_events,\n output_file.as_posix(),\n key='array_events',\n mode='a'\n )\n fact.io.write_data(telescope_events,\n output_file.as_posix(),\n key='telescope_events',\n mode='a'\n )\n\n\ndef output_file_for_input_file(input_file):\n raw_name = Path(input_file.name)\n while raw_name.suffixes:\n raw_name_stem = raw_name.stem\n raw_name = Path(raw_name_stem)\n return(raw_name.with_suffix('.hdf5'))\n" ]
[ [ "pandas.DataFrame", "pandas.concat" ] ]
srio/propagation-free-space
[ "7d6a9c9a3ea50a907ac627a45088004b5a618a28" ]
[ "examples/fresnel_number.py" ]
[ "import numpy\nimport scipy.constants as codata\nfrom srxraylib.plot.gol import plot\nimport matplotlib.pylab as plt\n\n\nenergy = 10000.0\nwavelength = ( codata.h*codata.c/codata.e*1e9 /energy)*10**(-9)\nwindow_size = 5e-6\naperture_diameter = 1.25e-06\npropagation_distance = 75e-6\nN = 2048\n\ndelta = window_size/N\npropagation_distance = numpy.linspace(0,500e-6,100)\n#\n# info\n#\n# print(\"Dz <? N d^2 / lambda; %g < %g \" %(propagation_distance, window_size*0.5 * delta/wavelength))\n# print(\"Fresnel number: xmaxD / (lambda Dz) = %g \" %(0.5*window_size /(propagation_distance * wavelength)))\n\nvalidity2048 = window_size * (window_size/2048) / wavelength\nvalidity4096 = window_size * (window_size/4096) / wavelength\n# fresnel = 0.5*window_size /(propagation_distance * wavelength)\n\nplot(1e6*propagation_distance,propagation_distance,\n 1e6*propagation_distance,propagation_distance*0 + validity2048,\n 1e6*propagation_distance,propagation_distance*0 + validity4096,\n xtitle=\"propagation distance [um]\",\n legend=[\"propagation distance [m]\",\"limiting condition N=2048 [m]\",\"limiting condition N=4096 [m]\"],show=False)\n\nplt.savefig(\"fresnel_propagator_validity.png\")\nprint(\"File written to disk: fresnel_propagator_validity.png\" )\nplt.show()\n\nprint(\"validity 2048: %f um \"%(1e6*validity2048))\nprint(\"validity 4096: %f um \"%(1e6*validity4096))\n\nvalidity_favre_512 = window_size * (window_size/2048) / wavelength\nvalidity_favre_512 = window_size * (window_size/4096) / wavelength\n\n# plot(propagation_distance,fresnel,title=\"Fresnel number\")" ]
[ [ "numpy.linspace", "matplotlib.pylab.savefig", "matplotlib.pylab.show" ] ]
sangminwoo/evo_ai
[ "509b7113e54424773002067404548b536568cce0" ]
[ "4bit_deceptive/4bit_deceptive.py" ]
[ "import argparse\nimport logging\nimport os\nimport sys\nimport time\nfrom datetime import datetime, timedelta\n\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\n\nclass Fourbit:\n\t# Order-4 deceptive problem\n\tdef __init__(self, crossover_algorithm, crossover_prob, crossover_points, mutation_prob,\n\t\t\t\t population_size, individual_len, num_generations, selection_algorithm):\n\t\tself.crossover_algorithm = crossover_algorithm\n\t\tself.crossover_prob = crossover_prob\n\t\tself.crossover_points = crossover_points\n\t\tself.mutation_prob = mutation_prob\n\t\tself.population_size = population_size\n\t\tself.individual_len = individual_len\n\t\tself.num_generations = num_generations\n\t\tself.selection_algorithm = selection_algorithm\n\n\tdef init_population(self):\n\t\treturn np.stack([np.random.choice(2, self.individual_len, replace=True) for _ in range(self.population_size*2)]) # 300*2x100\n\n\tdef fitness(self, string):\n\t\tif len(string) != 100:\n\t\t\traise Exception(\"Error: The length of every chromosome must be 100\")\n\t\tfitness = 0\n\t\tfor i in range(0, 99, 4):\n\t\t\tif sum(string[i:i+4]) == 4:\n\t\t\t\tfitness += 4\n\t\t\telse:\n\t\t\t\tfitness += 3 - sum(string[i:i+4])\n\t\treturn fitness\n\n\tdef selection_rws(self, fitness, population):\n\t\t# Roulette wheel selection\n\t\tprobability = np.array(fitness) / np.sum(fitness)\n\t\tselected = np.random.choice(population.shape[0], self.population_size, p=probability)\n\t\treturn population[selected]\n\n\tdef selection_pwts(self, fitness, population):\n\t\t# Pair-wise tournament selection\n\t\tselected = []\n\t\tfor i in range(0, population.shape[0], 2):\n\t\t\tif fitness[i] > fitness[i+1]:\n\t\t\t\tselected.append(i)\n\t\t\telse:\n\t\t\t\tselected.append(i+1)\n\t\treturn population[selected]\n\n\tdef selection_rank(self, fitness, population):\n\t\t# Rank-based selection\n\t\tselected = np.argsort(fitness)[:self.population_size]\n\t\treturn population[selected]\n\n\tdef uniform_crossover(self, parents):\n\t\t# Uniform crossover\n\t\tchildren = np.zeros((parents.shape[0]*2, parents.shape[1]), dtype=int)\n\t\t\n\t\tfor i in range(0, children.shape[0], 2):\n\t\t\tidx = np.random.choice(parents.shape[0], 2, replace=False)\n\n\t\t\tif random.random() < self.crossover_prob:\n\t\t\t\tmask1 = np.random.choice(2, parents.shape[1], replace=True)\n\t\t\t\tmask2 = 1-mask1\n\n\t\t\t\tchildren[i, mask1 > 0] = parents[idx[0], mask1 > 0]\n\t\t\t\tchildren[i+1, mask2 > 0] = parents[idx[1], mask2 > 0]\n\t\t\telse:\n\t\t\t\tchildren[i, :] = parents[idx[0], :]\n\t\t\t\tchildren[i+1, :] = parents[idx[1], :]\n\n\t\treturn children\n\n\tdef pointwise_crossover(self, parents):\n\t\t# Pointwise crossover\n\t\tchildren = np.zeros((parents.shape[0]*2, parents.shape[1]), dtype=int)\n\t\t\n\t\tfor i in range(0, children.shape[0], 2):\n\t\t\tidx = np.random.choice(parents.shape[0], 2, replace=False)\n\n\t\t\tif random.random() < self.crossover_prob:\n\t\t\t\tcrossover_points = sorted(np.random.choice(parents.shape[1], self.crossover_points, replace=False))\n\t\t\t\tcrossover_points = [0] + crossover_points + [parents.shape[1]]\n\t\t\t\tfor j in range(0, len(crossover_points)-1, 2):\n\t\t\t\t\tchildren[i, crossover_points[j]:crossover_points[j+1]] = parents[idx[0], crossover_points[j]:crossover_points[j+1]]\n\t\t\t\t\tchildren[i, crossover_points[j+1]:crossover_points[j+2]] = parents[idx[1], crossover_points[j+1]:crossover_points[j+2]]\n\n\t\t\t\tfor j in range(0, len(crossover_points)-1, 2):\n\t\t\t\t\tchildren[i+1, crossover_points[j]:crossover_points[j+1]] = parents[idx[1], crossover_points[j]:crossover_points[j+1]]\n\t\t\t\t\tchildren[i+1, crossover_points[j+1]:crossover_points[j+2]] = parents[idx[0], crossover_points[j+1]:crossover_points[j+2]]\n\n\t\t\t\t# children[i, :crossover_points[0]] = parents[idx[0], :crossover_points[0]]\n\t\t\t\t# children[i, crossover_points[0]:crossover_points[1]] = parents[idx[1], crossover_points[0]:crossover_points[1]]\n\t\t\t\t# children[i, crossover_points[1]:crossover_points[2]] = parents[idx[0], crossover_points[1]:crossover_points[2]]\n\t\t\t\t# children[i, crossover_points[2]:] = parents[idx[1], crossover_points[2]:]\n\n\t\t\t\t# children[i+1, :crossover_points[0]] = parents[idx[1], :crossover_points[0]]\n\t\t\t\t# children[i+1, crossover_points[0]:crossover_points[1]] = parents[idx[0], crossover_points[0]:crossover_points[1]]\n\t\t\t\t# children[i+1, crossover_points[1]:crossover_points[2]] = parents[idx[1], crossover_points[1]:crossover_points[2]]\n\t\t\t\t# children[i+1, crossover_points[2]:] = parents[idx[0], crossover_points[2]:]\n\n\t\t\t\t# handle duplicate\n\t\t\t\tfor j in [i, i+1]:\n\t\t\t\t\tflag = {}\n\t\t\t\t\tfor idx in range(children.shape[1]):\n\t\t\t\t\t\tflag[idx] = []\n\t\t\t\t\t\n\t\t\t\t\tfor idx, val in enumerate(children[j]):\n\t\t\t\t\t\tflag[val].append(idx)\n\n\t\t\t\t\tmissing = [key for key in flag if len(flag[key])==0]\n\t\t\t\t\tduplicate = [key for key in flag if len(flag[key])==2]\n\n\t\t\t\t\tfor (m, d) in zip(missing, duplicate):\n\t\t\t\t\t\tchildren[j, flag[d][-1]] = m\n\t\t\telse:\n\t\t\t\tchildren[i, :] = parents[idx[0], :]\n\t\t\t\tchildren[i+1, :] = parents[idx[1], :]\n\n\t\treturn children\n\n\tdef bbwise_crossover(self, parents):\n\t\tdef linkage_identification(population, threshold):\n\t\t\tdef mutual_info(genes1, genes2):\n\t\t\t\teps = 1e-10 # to avoid devision by zero\n\t\t\t\tpopulation = len(genes1)\n\t\t\t\tg1_0 = np.sum(genes1==0)/population\n\t\t\t\tg1_1 = np.sum(genes1==1)/population\n\t\t\t\tg2_0 = np.sum(genes2==0)/population\n\t\t\t\tg2_1 = np.sum(genes2==1)/population\n\t\t\t\tg1_0_g2_0 = np.sum(np.logical_and(genes1==0, genes2==0))/population + eps\n\t\t\t\tg1_0_g2_1 = np.sum(np.logical_and(genes1==0, genes2==1))/population + eps\n\t\t\t\tg1_1_g2_0 = np.sum(np.logical_and(genes1==1, genes2==0))/population + eps\n\t\t\t\tg1_1_g2_1 = np.sum(np.logical_and(genes1==1, genes2==1))/population + eps\n\n\t\t\t\tinfo = g1_0_g2_0*np.log(g1_0_g2_0 / (g1_0*g2_0+eps)) + \\\n\t\t\t\t\t g1_0_g2_1*np.log(g1_0_g2_1 / (g1_0*g2_1+eps)) + \\\n\t\t\t\t\t g1_1_g2_0*np.log(g1_1_g2_0 / (g1_1*g2_0+eps)) + \\\n\t\t\t\t\t g1_1_g2_1*np.log(g1_1_g2_1 / (g1_1*g2_1+eps))\n\t\t\t\treturn info\n\n\t\t\tlinkage = []\n\t\t\tinfos = {}\n\t\t\tfor i in range(parents.shape[1]):\n\t\t\t\tfor j in range(i+1, parents.shape[1]):\n\t\t\t\t\tinfos[(i,j)] = mutual_info(parents[:, i], parents[:, j])\n\t\t\t\t\tinfo_idx, max_info = np.argmax(list(infos.values())), np.max(list(infos.values()))\n\t\t\t\t\tif max_info > threshold:\n\t\t\t\t\t\tlinkage.append(info_idx)\n\n\t\t\treturn linkage\n\n\t\t# links = linkage_identification(parents, threshold=0.1)\n\t\t# bb-wise crossover\n\t\tchildren = np.zeros((parents.shape[0]*2, parents.shape[1]), dtype=int)\n\t\t\n\t\tfor i in range(0, children.shape[0], 2):\n\t\t\tidx = np.random.choice(parents.shape[0], 2, replace=False)\n\n\t\t\tif random.random() < self.crossover_prob:\n\t\t\t\tcrossover_points = sorted(np.random.choice(parents.shape[1]//4, self.crossover_points, replace=False)*4)\n\t\t\t\t\n\t\t\t\tchildren[i, :crossover_points[0]] = parents[idx[0], :crossover_points[0]]\n\t\t\t\tchildren[i, crossover_points[0]:crossover_points[1]] = parents[idx[1], crossover_points[0]:crossover_points[1]]\n\t\t\t\tchildren[i, crossover_points[1]:crossover_points[2]] = parents[idx[0], crossover_points[1]:crossover_points[2]]\n\t\t\t\tchildren[i, crossover_points[2]:] = parents[idx[1], crossover_points[2]:]\n\n\t\t\t\tchildren[i+1, :crossover_points[0]] = parents[idx[1], :crossover_points[0]]\n\t\t\t\tchildren[i+1, crossover_points[0]:crossover_points[1]] = parents[idx[0], crossover_points[0]:crossover_points[1]]\n\t\t\t\tchildren[i+1, crossover_points[1]:crossover_points[2]] = parents[idx[1], crossover_points[1]:crossover_points[2]]\n\t\t\t\tchildren[i+1, crossover_points[2]:] = parents[idx[0], crossover_points[2]:]\n\n\t\t\t\t# handle duplicate\n\t\t\t\tfor j in [i, i+1]:\n\t\t\t\t\tflag = {}\n\t\t\t\t\tfor idx in range(children.shape[1]):\n\t\t\t\t\t\tflag[idx] = []\n\t\t\t\t\t\n\t\t\t\t\tfor idx, val in enumerate(children[j]):\n\t\t\t\t\t\tflag[val].append(idx)\n\n\t\t\t\t\tmissing = [key for key in flag if len(flag[key])==0]\n\t\t\t\t\tduplicate = [key for key in flag if len(flag[key])==2]\n\n\t\t\t\t\tfor (m, d) in zip(missing, duplicate):\n\t\t\t\t\t\tchildren[j, flag[d][-1]] = m\n\t\t\telse:\n\t\t\t\tchildren[i, :] = parents[idx[0], :]\n\t\t\t\tchildren[i+1, :] = parents[idx[1], :]\n\n\t\treturn children\n\n\tdef mutation(self, children):\n\t\t# pair-wise mutation\n\t\tfor i in range(children.shape[0]):\n\t\t\tif random.random() < self.mutation_prob:\n\t\t\t\tmutation_points = np.random.choice(children.shape[1], 2, replace=False)\n\t\t\t\ttemp = children[i, mutation_points[0]]\n\t\t\t\tchildren[i, mutation_points[0]] = children[i, mutation_points[1]]\n\t\t\t\tchildren[i, mutation_points[1]] = temp\n\t\treturn children\n\n\tdef run(self):\n\t\tfitness_history = []\n\t\tpopulation = self.init_population()\n\n\t\tfor i in range(self.num_generations):\n\t\t\tfitness = np.array([self.fitness(indv) for indv in population])\n\t\t\tfitness_history.append(fitness)\n\t\t\t\n\t\t\t# selection\n\t\t\tif self.selection_algorithm == 'rws':\n\t\t\t\tparents = self.selection_rws(fitness, population)\n\t\t\telif self.selection_algorithm == 'pwts':\n\t\t\t\tparents = self.selection_pwts(fitness, population)\n\t\t\telif self.selection_algorithm == 'rank':\n\t\t\t\tparents = self.selection_rank(fitness, population)\n\n\t\t\t# crossover\n\t\t\tif self.crossover_algorithm == 'uniform':\n\t\t\t\tchildren = self.uniform_crossover(parents)\n\t\t\telif self.crossover_algorithm == 'pointwise':\n\t\t\t\tchildren = self.pointwise_crossover(parents)\n\t\t\telif self.crossover_algorithm == 'bbwise':\n\t\t\t\tchildren = self.bbwise_crossover(parents)\n\n\t\t\tpopulation = self.mutation(children)\n\n\t\t\tif (i+1)%10 == 0:\n\t\t\t\tprint(f'{i+1}th generation population: {population}')\n\n\t\tfitness = np.array([self.fitness(indv) for indv in population])\n\t\tmax_fitness = np.where(fitness == np.max(fitness))\n\t\tparameters = population[max_fitness[0][0]]\n\t\treturn parameters, fitness_history\n\ndef setup_logger(name, save_dir, filename=\"log.txt\"):\n\tif not os.path.exists(save_dir):\n\t\tos.makedirs(save_dir)\n\n\tlogger = logging.getLogger(name)\n\tlogger.setLevel(logging.DEBUG) # DEBUG, INFO, ERROR, WARNING\n\tformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\tstream_handler = logging.StreamHandler(stream=sys.stdout)\n\tstream_handler.setFormatter(formatter)\n\tlogger.addHandler(stream_handler)\n\tfile_handler = logging.FileHandler(os.path.join(save_dir, filename))\n\tfile_handler.setFormatter(formatter)\n\tlogger.addHandler(file_handler)\n\treturn logger\n\ndef get_timestamp():\n\tnow = datetime.now()\n\ttimestamp = datetime.timestamp(now)\n\tst = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d-%H:%M:%S')\n\treturn st\n\ndef get_arguments():\n\tparser = argparse.ArgumentParser(description='4-bit deceptive problem')\n\tparser.add_argument('--iter', type=str, help='ith iteration', required=True)\n\tparser.add_argument('--gen', type=int, help='number of generations', default=400)\n\tparser.add_argument('--pop', type=int, help='population size', default=200)\n\tparser.add_argument('--indv', type=int, help='individual length', default=100)\n\tparser.add_argument('--sel', type=str, help='selection algorithm (pwts; rws; rank)', default='pwts')\n\tparser.add_argument('--c_alg', type=str, help='crossover algorithm (uniform; pointwise; bbwise)', default='pointwise')\n\tparser.add_argument('--c_prob', type=float, help='crossover probability', default=1.0)\n\tparser.add_argument('--c_point', type=int, help='crossover points', default=3)\n\tparser.add_argument('--m_prob', type=float, help='mutation probability', default=0.02)\n\n\targs = parser.parse_args()\n\treturn args\n\ndef plot_fitness(iter, save_dir, num_generations, fitness_history):\n\t# visualize how the fitness changes with every generation\n\tif not os.path.exists(save_dir):\n\t\tos.makedirs(save_dir)\n\n\tfitness_history_mean = [np.mean(fitness) for fitness in fitness_history]\n\tfitness_history_max = [np.max(fitness) for fitness in fitness_history]\n\tplt.plot(list(range(num_generations)), fitness_history_mean, label = 'Mean Fitness')\n\tplt.plot(list(range(num_generations)), fitness_history_max, label = 'Max Fitness')\n\n\tplt.legend()\n\tplt.xlabel('Generations')\n\tplt.ylabel('Fitness')\n\t# plt.show()\n\tplt.savefig(f'{save_dir}/fitness_iter_{iter}')\n\nif __name__=='__main__':\n\targs = get_arguments()\n\n\tlogger = setup_logger(name=args.iter, save_dir='logs', filename='{}_fourbit_{}.txt'.format(get_timestamp(), args.iter))\n\tlogger = logging.getLogger(args.iter)\n\tlogger.info(f\"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Training start!\")\n\n\tfourbit = Fourbit(crossover_algorithm=args.c_alg,\n\t\t\t\t\t crossover_prob=args.c_prob,\n\t\t\t\t\t crossover_points=args.c_point,\n\t\t\t\t\t mutation_prob=args.m_prob,\n\t\t\t\t\t population_size=args.pop,\n\t\t\t\t\t individual_len=args.indv,\n\t\t\t\t\t num_generations=args.gen,\n\t\t\t\t\t selection_algorithm=args.sel) # rws, pwts, rank\n\n\tparameters, fitness_history = fourbit.run()\n\n\tdelimeter = \" \"\n\tlogger.info(\n\t\t\t\tdelimeter.join(\n\t\t\t\t\t[\"Optimal individual: {indv}\",\n\t\t\t\t\t \"Maximum fitness: {fitness}\"]\n\t\t\t\t ).format(\n\t\t\t\t\tindv=parameters,\n\t\t\t\t\tfitness=max(fitness_history[-1]))\n\t\t\t)\n\n\tplot_fitness(iter=args.iter, save_dir='figures', num_generations=args.gen, fitness_history=fitness_history)" ]
[ [ "numpy.max", "numpy.array", "numpy.random.choice", "numpy.zeros", "numpy.log", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig", "numpy.sum", "matplotlib.pyplot.legend", "numpy.mean", "numpy.logical_and", "matplotlib.pyplot.ylabel", "numpy.argsort" ] ]
abw-24/nets
[ "217030e0edd7f9891dfb8ca00d6a64439b7def95" ]
[ "nets/layers.py" ]
[ "\nfrom tensorflow.keras import layers as klayers\nimport tensorflow as tf\n\n\nclass SequentialBlock(klayers.Layer):\n \"\"\"\n Base block class. Creates a generic call method referencing\n self._block_layers, which is utilized by each child class to\n store computations. Layers that use the `training` argument\n to change computations will of course need to overwrite\n the call method.\n \"\"\"\n\n def __init__(self, **kwargs):\n super(SequentialBlock, self).__init__(**kwargs)\n self._block_layers = {}\n\n def call(self, inputs, training=False):\n x = inputs\n for i in range(len(self._block_layers)):\n x = self._block_layers[str(i)](x, training=training)\n return x\n\n\nclass DenseBlock(SequentialBlock):\n \"\"\"\n Block of densely connected layers.\n \"\"\"\n\n def __init__(self, dims, activation, kernel_regularizer=None, activity_regularizer=None, **kwargs):\n\n super(DenseBlock, self).__init__(**kwargs)\n\n if isinstance(dims, int):\n self._dims = [dims]\n else:\n self._dims = dims\n if isinstance(activation, str):\n self._activation = [activation]*len(self._dims)\n else:\n self._activation = activation\n\n layer_enum = enumerate(zip(self._dims, self._activation))\n self._block_layers = {\n str(i): klayers.Dense(\n v[0],\n v[1],\n kernel_regularizer=kernel_regularizer,\n activity_regularizer=activity_regularizer\n )\n for i, v in layer_enum\n }\n\n def get_config(self):\n config = super(DenseBlock, self).get_config()\n config.update({\n \"dims\": self._dims,\n \"activation\": self._activation\n })\n return config\n\n\nclass ConvBlock(SequentialBlock):\n\n def __init__(\n self,\n filters,\n kernel=3,\n stride=(1,1),\n padding=\"same\",\n activation=\"relu\",\n pool=True,\n batch_norm=False,\n **kwargs\n ):\n \"\"\"\n 2d CNN Block (series of convolution and pooling ops). Assumes reshaping and\n input formatting is done already, and expects the input dim to be\n dynamically assigned with build(). Note: if you wish to specify a non-square\n kernel (shame on you), specify as a tuple.\n\n :param filters: List of integers specifying the number of feature filters in\n each layer. The length implicitly specifies the number of\n convolution+pooling layers in the block.\n :param kernel: Kernel size for each filter (int or tuple)\n :param stride: Kernel stride (int)\n :param activation: Activation function (str)\n :param pool: Flag to add pooling layer after each convolution\n :param batch_norm: Flag to add batch normalization after each convolution\n :return:\n \"\"\"\n\n super(ConvBlock, self).__init__(**kwargs)\n\n self._pool_flag = pool\n self._activation = activation\n self._batch_norm_flag = batch_norm\n\n if isinstance(filters, int):\n self._filters = [filters]\n else:\n self._filters = filters\n\n depth = len(filters)\n\n if isinstance(kernel, int) or isinstance(kernel, tuple):\n self._kernel = [kernel]*depth\n else:\n self._kernel = kernel\n if isinstance(stride, int) or isinstance(stride, tuple):\n self._stride = [stride]*depth\n else:\n self._stride = stride\n if isinstance(padding, str) or isinstance(padding, tuple):\n self._padding = [padding]*depth\n else:\n self._padding = padding\n\n layer_index = 0\n for f, k, s, p in zip(self._filters, self._kernel, self._stride, self._padding):\n self._block_layers[str(layer_index)] = klayers.Conv2D(\n f, k, strides=s, padding=p, activation=self._activation\n )\n layer_index += 1\n if self._batch_norm_flag:\n self._block_layers[str(layer_index)] = klayers.BatchNormalization()\n layer_index += 1\n if self._pool_flag:\n self._block_layers[str(layer_index)] = klayers.MaxPooling2D()\n layer_index += 1\n\n def get_config(self):\n config = super(ConvBlock, self).get_config()\n config.update({\n \"filters\": self._filters,\n \"kernel\": self._kernel,\n \"stride\": self._stride,\n \"padding\": self._padding,\n \"activation\": self._activation,\n \"pool\": self._pool_flag,\n \"batch_norm\": self._batch_norm_flag\n })\n return config\n\n\nclass ResidualLayer(klayers.Layer):\n\n def __init__(self, filters, activation=\"relu\", **kwargs):\n \"\"\"\n Single 2D convolutional block (of configurable depth) plus a residual connection\n at the end. Assumes \"same\" padding, so residual connection dims will match.\n\n :param filters: List of integers specifying the number of feature filters in\n each layer. The length implicitly specifies the number of\n convolution layers in the block.\n :param activation: Activation function (str)\n \"\"\"\n\n super(ResidualLayer, self).__init__(**kwargs)\n\n self._conv_activation = activation\n self._conv_layer = ConvBlock(\n filters,\n kernel=3,\n stride=(1,1),\n activation=self._conv_activation,\n padding=\"same\",\n pool=False,\n batch_norm=False\n )\n self._add_op = klayers.Add()\n self._activation_op = klayers.Activation(self._conv_activation)\n\n def call(self, inputs, training=False):\n x = inputs\n conv_out = self._conv_layer(x, training=training)\n res_out = self._add_op([x, conv_out])\n output = self._activation_op(res_out)\n return output\n\n def get_config(self):\n config = super(ResidualLayer, self).get_config()\n config.update({\n \"filters\": self._filters,\n \"activation\": self._activation,\n })\n return config\n\n\nclass MultiPathResidualLayer(klayers.Layer):\n\n def __init__(self, n_paths, filters, activation=\"relu\", **kwargs):\n \"\"\"\n Multiple 2D convolutional block paths (of configurable depth) merged\n plus a residual connection. Assumes \"same\" padding, so residual\n connection dims will match. The number of filters is altered (divided by a factor\n of 2) in secondary paths to encourage information flow.\n\n :param n_paths: Number of convolutional paths\n :param filters: List of integers specifying the number of feature filters in\n each conv layer (for each path). The length implicitly specifies the number of\n convolution layers in the block.\n :param activation: Activation function (str)\n \"\"\"\n\n super(MultiPathResidualLayer, self).__init__(**kwargs)\n\n self._n_paths = n_paths\n self._conv_activation = activation\n self._conv_paths = {}\n\n if isinstance(filters, int):\n self._filters = [filters]\n else:\n self._filters = filters\n\n # change the number of filters in the secondary paths to\n # try to encourage different/more helpful representations.\n # in this case, we just divide each subsequent path by\n # an increasing power of 2. we make sure to use the same\n # number for the last conv op in each path so we can merge\n # them before the final residual connection\n\n for i in range(self._n_paths):\n self._conv_paths[str(i)] = ConvBlock(\n filters=[int(f/pow(2, i)) for f in self._filters[:-1]] + [self._filters[-1]],\n kernel=3,\n stride=(1,1),\n activation=self._conv_activation,\n padding=\"same\",\n pool=False,\n batch_norm=True\n )\n\n self._add_op = klayers.Add()\n self._activation_op = klayers.Activation(self._conv_activation)\n\n def call(self, inputs, training=False):\n x = inputs\n path_outputs = []\n for i in range(self._n_paths):\n path_out = self._conv_paths[str(i)](x, training=training)\n path_outputs.append(path_out)\n merged = self._add_op(path_outputs)\n output = self._add_op([x, merged])\n output = self._activation_op(output)\n return output\n\n def get_config(self):\n config = super(MultiPathResidualLayer, self).get_config()\n config.update({\n \"n_paths\": self._n_paths,\n \"filters\": self._filters,\n \"activation\": self._activation,\n })\n return config\n\n\nclass ResidualBlock(SequentialBlock):\n \"\"\"\n\n \"\"\"\n\n def __init__(self, block_depth, filters, activation=\"relu\", **kwargs):\n\n super(ResidualBlock, self).__init__(**kwargs)\n\n self._block_depth = block_depth\n self._block_filters = filters\n self._res_activation = activation\n\n if isinstance(self._block_filters, int):\n self._block_filters = [self._block_filters] * self._block_depth\n else:\n if isinstance(self._block_filters[0], int):\n self._block_filters = [self._block_filters] * self._block_depth\n\n for i in range(self._block_depth):\n self._block_layers[str(i)] = ResidualLayer(self._block_filters[i], self._res_activation)\n\n def get_config(self):\n config = super(ResidualBlock, self).get_config()\n config.update({\n \"block_depth\": self._block_depth,\n \"filters\": self._block_filters,\n \"activation\": self._res_activation,\n })\n return config\n\n\nclass MultiPathResidualBlock(SequentialBlock):\n \"\"\"\n\n \"\"\"\n\n def __init__(self, block_depth, n_paths, filters, activation=\"relu\", **kwargs):\n\n super(MultiPathResidualBlock, self).__init__(**kwargs)\n\n self._block_depth = block_depth\n self._n_paths = n_paths\n self._block_filters = filters\n self._res_activation = activation\n\n if isinstance(n_paths, int):\n self._n_paths = [self._n_paths]*self._block_depth\n\n if isinstance(self._block_filters, int):\n self._block_filters = [self._block_filters] * self._block_depth\n else:\n if isinstance(self._block_filters[0], int):\n self._block_filters = [self._block_filters] * self._block_depth\n\n for i in range(self._block_depth):\n self._block_layers[str(i)] = MultiPathResidualLayer(\n self._n_paths[i],\n filters=self._block_filters[i],\n activation=self._res_activation\n )\n\n def get_config(self):\n config = super(MultiPathResidualBlock, self).get_config()\n config.update({\n \"block_depth\": self._block_depth,\n \"n_paths\": self._n_paths,\n \"filters\": self._block_filters,\n \"activation\": self._res_activation,\n })\n return config\n\n\nclass VAESampling(klayers.Layer):\n \"\"\"\n Samples from distribution defined by the latent layer values to\n generate values from which to decode.\n \"\"\"\n\n def call(self, inputs):\n z_mean, z_log_var = inputs\n epsilon = tf.keras.backend.random_normal(\n shape=(tf.shape(z_mean)[0],\n tf.shape(z_mean)[1])\n )\n return z_mean + tf.exp(0.5 * z_log_var) * epsilon\n\n def get_config(self):\n return super(VAESampling, self).get_config()\n\n\nclass DenseVariationalEncoder(klayers.Layer):\n\n def __init__(self, mapping_dims, latent_dim, activation=\"relu\", activity_regularizer=None, **kwargs):\n\n super(DenseVariationalEncoder, self).__init__(**kwargs)\n\n self._mapping_dims = mapping_dims\n self._latent_dim = latent_dim\n self._activation = activation\n\n self._encode_block = DenseBlock(\n self._mapping_dims,\n activation=self._activation,\n activity_regularizer=activity_regularizer\n )\n self._latent_mean = klayers.Dense(self._latent_dim)\n self._latent_log_var = klayers.Dense(self._latent_dim)\n self._sampling = VAESampling()\n\n def call(self, inputs):\n x = self._encode_block(inputs)\n z_mean = self._latent_mean(x)\n z_log_var = self._latent_log_var(x)\n z = self._sampling((z_mean, z_log_var))\n return z_mean, z_log_var, z\n\n def get_config(self):\n config = super(DenseVariationalEncoder, self).get_config()\n config.update({\n \"mapping_dims\": self._mapping_dims,\n \"latent_dim\": self._latent_dim,\n \"activation\": self._activation\n })\n return config\n\n\nclass DenseVariationalDecoder(klayers.Layer):\n\n def __init__(self, inverse_mapping_dims, input_dim, activation=\"relu\", activity_regularizer=None, **kwargs):\n\n super(DenseVariationalDecoder, self).__init__(**kwargs)\n\n self._inverse_mapping_dims = inverse_mapping_dims\n self._input_dim = input_dim\n self._activation = activation\n\n self._decode_block = DenseBlock(\n self._inverse_mapping_dims,\n activation=self._activation,\n activity_regularizer=activity_regularizer\n )\n self._output = klayers.Dense(self._input_dim)\n\n def call(self, inputs):\n x = self._decode_block(inputs)\n return self._output(x)\n\n def get_config(self):\n config = super(DenseVariationalDecoder, self).get_config()\n config.update({\n \"inverse_mapping_dims\": self._inverse_mapping_dims,\n \"input_dim\": self._input_dim,\n \"activation\": self._activation\n })\n return config\n\n\nclass DenseEncoder(klayers.Layer):\n\n def __init__(self, mapping_dims, latent_dim, activation=\"relu\", activity_regularizer=None, **kwargs):\n\n super(DenseEncoder, self).__init__(**kwargs)\n\n self._mapping_dims = mapping_dims\n\n if isinstance(self._mapping_dims, int):\n self._mapping_dims = [self._mapping_dims]\n else:\n assert hasattr(self._mapping_dims, \"__iter__\"), \\\n \"Expecting either an int or an iterable of ints.\"\n self._mapping_dims = list(self._mapping_dims)\n\n self._latent_dim = latent_dim\n self._activation = activation\n\n self._encode_block = DenseBlock(\n self._mapping_dims + [self._latent_dim],\n activation=self._activation,\n activity_regularizer=activity_regularizer\n )\n\n def call(self, inputs):\n return self._encode_block(inputs)\n\n def get_config(self):\n config = super(DenseEncoder, self).get_config()\n config.update({\n \"mapping_dims\": self._mapping_dims,\n \"latent_dim\": self._latent_dim,\n \"activation\": self._activation\n })\n return config\n\n\nclass DenseDecoder(klayers.Layer):\n\n def __init__(self, inverse_mapping_dims, input_dim, activation=\"relu\", activity_regularizer=None, **kwargs):\n\n super(DenseDecoder, self).__init__(**kwargs)\n\n self._inverse_mapping_dims = inverse_mapping_dims\n self._input_dim = input_dim\n self._activation = activation\n\n self._decode_block = DenseBlock(\n self._inverse_mapping_dims,\n activation=self._activation,\n activity_regularizer=activity_regularizer\n )\n self._output = klayers.Dense(self._input_dim)\n\n def call(self, inputs):\n x = self._decode_block(inputs)\n return self._output(x)\n\n def get_config(self):\n config = super(DenseDecoder, self).get_config()\n config.update({\n \"inverse_mapping_dims\": self._inverse_mapping_dims,\n \"input_dim\": self._input_dim,\n \"activation\": self._activation\n })\n return config\n" ]
[ [ "tensorflow.exp", "tensorflow.keras.layers.Add", "tensorflow.shape", "tensorflow.keras.layers.Activation", "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.layers.MaxPooling2D", "tensorflow.keras.layers.BatchNormalization" ] ]
gpiantoni/boavus
[ "855bc92cbb8a6062313d97d21813be87ba39bc81" ]
[ "boavus/ieeg/preprocessing.py" ]
[ "from logging import getLogger\nfrom pickle import load, dump\nfrom numpy import empty, arange\nfrom wonambi.trans import montage\nfrom wonambi.trans.select import _create_subepochs\n\nfrom bidso.utils import replace_extension\n\n\nlg = getLogger(__name__)\n\n\ndef preprocess_ecog(ieeg_file, reref, duration, offset, output_dir):\n \"\"\"\n\n Parameters\n ----------\n reref : str\n 'average' or 'regression'\n duration : int\n length of the segments\n offset : bool\n remove one sample for whole duration\n\n TODO\n ----\n labels_in_roi = find_labels_in_regions(electrodes, regions)\n clean_roi_labels = [label for label in clean_labels if label in labels_in_roi]\n data = select(data, chan=clean_roi_labels)\n \"\"\"\n with ieeg_file.open('rb') as f:\n data = load(f)\n\n data = montage(data, ref_to_avg=True, method=reref)\n data = make_segments(data, duration, offset)\n\n output_file = output_dir / replace_extension(ieeg_file.name, 'proc.pkl')\n with output_file.open('wb') as f:\n dump(data, f)\n\n return output_file\n\n\ndef make_segments(dat, duration=2, offset=True):\n\n dur_smp = int(dat.s_freq * duration)\n if offset:\n dur_smp -= 1\n\n trials = []\n for d in dat.data:\n v = _create_subepochs(d, dur_smp, dur_smp)\n for i in range(v.shape[1]):\n trials.append(v[:, i, :])\n\n out = dat._copy(axis=False)\n out.data = empty(len(trials), dtype='O')\n out.axis['chan'] = empty(len(trials), dtype='O')\n out.axis['time'] = empty(len(trials), dtype='O')\n\n for i, trial in enumerate(trials):\n out.data[i] = trial\n out.axis['time'][i] = arange(i * dur_smp, i * dur_smp + dur_smp) / dat.s_freq\n out.axis['chan'][i] = dat.axis['chan'][0]\n\n return out\n" ]
[ [ "numpy.arange" ] ]
cyphyhouse/CyPyHous3
[ "9ba2e9681391d6b9773258bcc73b5e10f403dda7" ]
[ "tests/base/test_obstacle.py" ]
[ "# Copyright (c) 2019 CyPhyHouse. All Rights Reserved.\n\nimport unittest\n\nimport numpy as np\n\nimport src.datatypes.motion.abstract.obstacle as obs\nimport src.datatypes.motion.pos as pos\nimport src.datatypes.motion.seg as seg\n\n\nclass DummyObs(obs.Obstacle):\n\n def __init__(self, point: pos.Pos, size: np.ndarray):\n super(DummyObs, self).__init__(point, size)\n\n def _collision_path(self, path: seg.Seg):\n return False\n\n def _collision_point(self, point: pos.Pos):\n return False\n\n\nclass TestObs(unittest.TestCase):\n \"\"\"\n testing the obstacle abstract type member access methods\n \"\"\"\n\n def setUp(self):\n self.obs = DummyObs(pos.Pos(np.array([1, 2, 3])), np.array([1]))\n self.pos = pos.Pos(np.array([4, 5, 6]))\n self.seg = seg.Seg(pos.Pos(np.array([1, 1, 1])), pos.Pos(np.array([2, 2, 3])))\n\n def test_pos(self):\n self.assertEqual(self.obs.position, pos.Pos(np.array([1, 2, 3])), \"testing position of obstacle\")\n\n def test_size(self):\n self.assertEqual(self.obs.size, np.array([1]), \"testing size of obstacle\")\n\n def test_path_collision(self):\n self.assertTrue(not (self.obs._collision_path(self.seg)), \" testing dummy path collision\")\n\n def test_pt_collision(self):\n self.assertTrue(not (self.obs._collision_point(self.pos)), \" testing dummy point collision\")\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.array" ] ]
Indrajeetja/ga-learner-dsmp-repo
[ "ea5977dceb32af003fcdd4bc39195fbb4c1f5a20" ]
[ "GRADIENT-BOOSTING-MACHINES/code.py" ]
[ "# --------------\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n#path - Path of file \ndf=pd.read_csv(path)\n# Code starts here\nX = df.drop([\"customerID\",\"Churn\"],1)\ny = df[\"Churn\"].copy()\n\nX_train, X_test, y_train, y_test = train_test_split(X,y,test_size =0.3 , random_state = 0)\n\n\n\n# --------------\nimport numpy as np\nfrom sklearn.preprocessing import LabelEncoder\n\n# Code starts here\n\n#Replacing spaces with 'NaN' in train dataset\nX_train['TotalCharges'].replace(' ',np.NaN, inplace=True)\n\n#Replacing spaces with 'NaN' in test dataset\nX_test['TotalCharges'].replace(' ',np.NaN, inplace=True)\n\n#Converting the type of column from X_train to float\nX_train['TotalCharges'] = X_train['TotalCharges'].astype(float)\n\n#Converting the type of column from X_test to float\nX_test['TotalCharges'] = X_test['TotalCharges'].astype(float)\n\n#Filling missing values\nX_train['TotalCharges'].fillna(X_train['TotalCharges'].mean(),inplace=True)\nX_test['TotalCharges'].fillna(X_train['TotalCharges'].mean(), inplace=True)\n\n#Check value counts\nprint(X_train.isnull().sum())\n\ncat_cols = X_train.select_dtypes(include='O').columns.tolist()\n\n#Label encoding train data\nfor x in cat_cols:\n le = LabelEncoder()\n X_train[x] = le.fit_transform(X_train[x])\n\n#Label encoding test data \nfor x in cat_cols:\n le = LabelEncoder() \n X_test[x] = le.fit_transform(X_test[x])\n\n#Encoding train data target \ny_train = y_train.replace({'No':0, 'Yes':1})\n\n#Encoding test data target\ny_test = y_test.replace({'No':0, 'Yes':1})\n\n\n\n# --------------\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.metrics import accuracy_score,classification_report,confusion_matrix\n\n# Code starts here\nada_model=AdaBoostClassifier(random_state=0)\nada_model.fit(X_train,y_train)\n\ny_pred = ada_model.predict(X_test)\n\nada_score=accuracy_score(y_test,y_pred)\nada_cm=confusion_matrix(y_test,y_pred)\nada_cr=classification_report(y_test,y_pred)\n\n\n# --------------\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import GridSearchCV\n\n#Parameter list\nparameters={'learning_rate':[0.1,0.15,0.2,0.25,0.3],\n 'max_depth':range(1,3)}\n\n# Code starts here\nxgb_model=XGBClassifier(random_state=0)\nxgb_model.fit(X_train,y_train)\ny_pred = xgb_model.predict(X_test)\nxgb_score=accuracy_score(y_test,y_pred)\n\nxgb_cm=confusion_matrix(y_test,y_pred)\n\nxgb_cr=classification_report(y_test,y_pred)\n\nclf_model=GridSearchCV(estimator=xgb_model,param_grid=parameters)\n\nclf_model.fit(X_train,y_train)\ny_pred = clf_model.predict(X_test)\nclf_score=accuracy_score(y_test,y_pred)\n\nclf_cm=confusion_matrix(y_test,y_pred)\n\nclf_cr=classification_report(y_test,y_pred)\n\n\n\n" ]
[ [ "sklearn.metrics.confusion_matrix", "sklearn.preprocessing.LabelEncoder", "sklearn.ensemble.AdaBoostClassifier", "sklearn.model_selection.GridSearchCV", "sklearn.metrics.accuracy_score", "sklearn.metrics.classification_report", "sklearn.model_selection.train_test_split", "pandas.read_csv" ] ]
mphancock/cctbx_project
[ "ec8a239c5bcee9c9b2d1c6c95dc3fff2580bbb85" ]
[ "simtbx/nanoBragg/nanoBragg_gui_frames.py" ]
[ "'''\nAuthor : Lyubimov, A.Y.\nCreated : 12/12/2017\nLast Changed: 06/20/2019\nDescription : SIMTBX (nanoBragg) GUI Windows / frames\n'''\nfrom __future__ import absolute_import, division, print_function\n\nimport os\nimport wx\nimport numpy as np\n\nfrom wxtbx import bitmaps\n\nfrom matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\nfrom iotbx import phil as ip\nfrom simtbx.nanoBragg import nanoBragg_gui_dialogs as dlg\nfrom simtbx.nanoBragg import nanoBragg_threads as thr\nfrom iota.components.gui import controls as ct\nfrom iota.components.iota_utils import InputFinder, WxFlags, noneset\nfrom six.moves import range\n\nginp = InputFinder()\nimport time\n\nf = WxFlags()\n\n# ------------------------------ Input Window -------------------------------- #\n\nclass BasePanel(wx.Panel):\n def __init__(self, parent):\n wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY, size=(800, 800))\n\n self.main_sizer = wx.BoxSizer(wx.VERTICAL)\n self.SetSizer(self.main_sizer)\n\n\nclass TopPanel(BasePanel):\n def __init__(self, parent):\n BasePanel.__init__(self, parent=parent)\n\n self.parent = parent\n self.img_filename = None\n self.input_phil = None\n self.sparams = None\n self.coord_filename = None\n self.mtz_filename = None\n self.stol_filename = None\n self.ref_img_filename = None\n self.dblclick = False\n\n\n self.project_folder = ct.InputCtrl(self,\n label='Project Folder: ',\n label_size=(150, -1),\n label_style='bold',\n value=os.path.abspath(os.curdir),\n buttons=True)\n\n self.project_title = ct.InputCtrl(self,\n label='Description',\n label_size=(150, -1),\n label_style='normal')\n\n self.splitter = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE |\n wx.SP_3DSASH |\n wx.SP_NOBORDER)\n self.file_panel = wx.Panel(self.splitter, size=(-1, 200))\n self.file_sizer = wx.BoxSizer(wx.VERTICAL)\n self.file_panel.SetSizer(self.file_sizer)\n self.preview_panel = wx.Panel(self.splitter, size=(-1, 500))\n self.preview_sizer = wx.BoxSizer(wx.VERTICAL)\n self.preview_panel.SetSizer(self.preview_sizer)\n self.splitter.SplitHorizontally(self.file_panel, self.preview_panel, 200)\n\n self.input = FileListCtrl(self.file_panel)\n self.file_sizer.Add(self.input, 1, flag=wx.ALL | wx.EXPAND, border=10)\n\n # Image preview box w/ options\n prev_box = wx.GridBagSizer(5, 15)\n\n # self.opt_knb_start = ct.KnobCtrl(self.preview_panel,\n # label='start',\n # label_size=(40, -1),\n # spin_ctr_size=(50, -1),\n # knob_size=(120, 120),\n # values_start=0,\n # values_end=360,\n # values_step=1,\n # value=0)\n #\n # self.opt_knb_end = ct.KnobCtrl(self.preview_panel,\n # label='end',\n # label_size=(40, -1),\n # spin_ctr_size=(50, -1),\n # knob_size=(120, 120),\n # values_start=0,\n # values_end=360,\n # values_step=1,\n # value=360)\n\n self.opt_spc_start = ct.SpinCtrl(self.preview_panel,\n label='start:',\n label_size=(50, -1),\n ctrl_size=(60, -1),\n ctrl_value='0',\n ctrl_max=360,\n ctrl_min=0,\n ctrl_step=0.1,\n ctrl_digits=1)\n\n self.opt_spc_end = ct.SpinCtrl(self.preview_panel,\n label='finish:',\n label_size=(50, -1),\n ctrl_size=(60, -1),\n ctrl_value='360',\n ctrl_max=360,\n ctrl_min=0,\n ctrl_step=0.1,\n ctrl_digits=1)\n\n self.opt_spc_osc = ct.SpinCtrl(self.preview_panel,\n label='step:',\n label_size=(50, -1),\n ctrl_size=(60, -1),\n ctrl_value='1.0',\n ctrl_max=360,\n ctrl_min=0,\n ctrl_step=0.1,\n ctrl_digits=2)\n\n self.opt_btn_prev = wx.Button(self.preview_panel,\n label='PREVIEW IMAGE')\n\n self.opt_chk_bkg = wx.CheckBox(self.preview_panel, label='Add Background')\n self.opt_chk_bkg.SetValue(True)\n self.opt_chk_noise = wx.CheckBox(self.preview_panel, label='Add Noise')\n self.opt_chk_noise.SetValue(True)\n self.opt_chk_rand = wx.CheckBox(self.preview_panel,\n label='Randomize Orientation')\n self.opt_chk_rand.SetValue(True)\n\n self.opt_spc_scale = ct.SpinCtrl(self.preview_panel,\n label='Crystal size (um): ',\n label_size=(120, -1),\n ctrl_size=(100, -1),\n ctrl_min = 1,\n ctrl_max = 1000,\n ctrl_step = 1,\n ctrl_value = 30)\n\n self.img_figure = Figure(figsize=(3, 3))\n self.img_axes = self.img_figure.add_subplot(111)\n\n self.img_axes.set_frame_on(False)\n self.img_axes.axis('off')\n self.img_axes.set_aspect('equal')\n\n self.img_figure.patch.set_visible(False)\n self.img_canvas = FigureCanvas(self.preview_panel, -1, self.img_figure)\n\n prev_box.Add(self.opt_spc_start, pos=(0, 0))\n prev_box.Add(self.opt_spc_end, pos=(0, 1))\n prev_box.Add(self.opt_spc_osc, pos=(1, 0))\n prev_box.Add(self.opt_chk_bkg, flag=wx.EXPAND, pos=(4, 0), span=(1, 2))\n prev_box.Add(self.opt_chk_noise, flag=wx.EXPAND, pos=(5, 0), span=(1, 2))\n prev_box.Add(self.opt_chk_rand, flag=wx.EXPAND, pos=(6, 0), span=(1, 2))\n prev_box.Add(self.opt_spc_scale, flag=wx.EXPAND, pos=(7, 0), span=(1, 2))\n prev_box.Add(self.opt_btn_prev, flag=wx.EXPAND, pos=(8,0), span=(1, 2))\n prev_box.Add(self.img_canvas, pos=(0, 2), span=(9, 1),\n flag=wx.EXPAND)\n prev_box.AddGrowableCol(2)\n prev_box.AddGrowableRow(8)\n\n self.preview_sizer.Add(prev_box, 1, flag=wx.EXPAND | wx.ALL, border=10)\n\n self.main_sizer.Add(self.project_title, flag=wx.EXPAND | wx.ALL, border=10)\n self.main_sizer.Add(self.project_folder, flag=wx.EXPAND | wx.ALL, border=10)\n self.main_sizer.Add(self.splitter, 1, flag=wx.EXPAND)\n\n # Button bindings\n self.Bind(wx.EVT_BUTTON, self.onRunPreview, self.opt_btn_prev)\n\n # Thread bindings\n self.Bind(thr.EVT_NBDONE, self.onFinishedSimThread)\n\n # Image bindings\n xid = self.img_canvas.mpl_connect('button_press_event', self.on_button_press)\n xid = self.img_canvas.mpl_connect('button_release_event',\n self.on_button_release)\n\n def onRunPreview(self, e):\n e.Skip()\n\n def generate_phil(self):\n\n coord_path = None\n FCalc_path = None\n bkg_path = None\n img_path = None\n\n # Grab inputs (if any) from file list control\n idxs = self.input.ctr.GetItemCount()\n inputs = [self.input.ctr.GetItemData(i) for i in range(idxs)]\n\n for idx in range(idxs):\n item = self.input.ctr.GetItemData(idx)\n item_type_sel = item.type_selection\n item_type = item.type.type.GetString(item_type_sel)\n\n if item_type == 'coordinates':\n coord_path = item.path\n elif item_type == 'structure factors':\n FCalc_path = item.path\n elif item_type == 'background':\n bkg_path = item.path\n elif item_type == 'raw image file':\n img_path = item.path\n\n simtbx_phil_string = '\\n'.join([\n 'description = {}'.format(noneset(self.project_title.ctr.GetValue())),\n 'output = {}'.format(noneset(self.project_folder.ctr.GetValue())),\n 'reference_coordinates = {}'.format(coord_path),\n 'reference_FCalc = {}'.format(FCalc_path),\n 'reference_image = {}'.format(img_path),\n 'radial_average_background = {}'.format(bkg_path),\n 'dataset',\n '{',\n ' start_phi = {}'.format(str(self.opt_spc_start.ctr.GetValue())),\n ' finish_phi = {}'.format(str(self.opt_spc_end.ctr.GetValue())),\n ' oscillation = {}'.format(str(self.opt_spc_osc.ctr.GetValue())),\n ' }'\n ])\n\n self.input_phil = ip.parse(simtbx_phil_string)\n\n def run_simulator(self, init=None):\n pass\n\n def run_preview(self):\n img_filename = 'test_image.{}'.format(self.sparams.image_format)\n self.img_filename = os.path.join(self.sparams.output, img_filename)\n self.start_timer = time.time()\n self.sim = thr.nanoBraggThread(self,\n params=self.sparams,\n add_background=self.opt_chk_bkg.GetValue(),\n add_noise=self.opt_chk_noise.GetValue(),\n randomize=self.opt_chk_rand.GetValue(),\n pixel_scale=self.opt_spc_scale.ctr.GetValue(),\n preview=True)\n self.sim.start()\n\n def onFinishedSimThread(self, e):\n pixels = e.GetValue()\n self.display_image(pixels=pixels)\n print('TOTAL TIME = ', time.time() - self.start_timer)\n\n def display_image(self, pixels=None):\n if pixels is None:\n pixels = np.random.randint(low=0, high=1500000, size=(2576, 2576))\n else:\n pixels = pixels.as_numpy_array()\n\n clim = (pixels.min(), np.percentile(pixels, 99))\n\n self.img_axes.imshow(pixels,\n #interpolation='nearest',\n cmap='gray_r',\n clim=clim)\n self.img_figure.subplots_adjust(left=0, bottom=0, right=1, top=1)\n\n self.preview_panel.Layout()\n print('DEBUG: AVERAGE PIXEL VALUE = ', np.mean(pixels))\n print('DONE!')\n\n def on_button_press(self, e):\n if e.button == 1 and e.dblclick:\n self.dblclick = True\n else:\n self.dblclick = False\n\n def on_button_release(self, e):\n if e.button == 1 and self.dblclick:\n self.view_image()\n\n def view_image(self):\n viewer = thr.ImageViewerThread(self,\n file_string=self.img_filename)\n viewer.start()\n\nclass FileListCtrl(ct.CustomListCtrl):\n ''' File list window for the input tab '''\n\n def __init__(self, parent, size=(-1, 250)):\n ct.CustomListCtrl.__init__(self, parent=parent, size=size)\n\n self.parent = parent\n self.main_window = parent.GetParent()\n\n # Generate columns\n self.ctr.InsertColumn(0, \"Input Path\")\n self.ctr.InsertColumn(1, \"Input Type\")\n self.ctr.InsertColumn(2, \"Action\")\n self.ctr.setResizeColumn(1)\n\n # Add file / folder buttons\n self.button_sizer = wx.BoxSizer(wx.HORIZONTAL)\n self.btn_add_file = wx.Button(self, label='Add File...')\n #self.btn_browse = wx.Button(self, label='Add Folder...')\n self.button_sizer.Add(self.btn_add_file)\n #self.proc_sizer.Add(self.btn_browse, flag=wx.LEFT, border=10)\n\n self.sizer.Add(self.button_sizer, flag=wx.TOP | wx.BOTTOM, border=10)\n\n # Event bindings\n self.Bind(wx.EVT_BUTTON, self.onAddFile, self.btn_add_file)\n\n self.Layout()\n\n def onAddFile(self, e):\n file_dlg = wx.FileDialog(self,\n message=\"Load File\",\n defaultDir=os.curdir,\n defaultFile=\"*\",\n wildcard=\"*\",\n style=wx.OPEN | wx.FD_FILE_MUST_EXIST |\n wx.FD_MULTIPLE)\n if file_dlg.ShowModal() == wx.ID_OK:\n files = file_dlg.GetPaths()\n for item in files:\n self.add_item(item)\n file_dlg.Destroy()\n e.Skip()\n\n def set_type_choices(self, path):\n # Determine what type of input this is and present user with choices\n # (this so far works for images ONLY)\n type_choices = ['[ SELECT INPUT TYPE ]',\n 'coordinates',\n 'structure factors',\n 'background',\n 'raw image file']\n preferred_selection = 0\n inputs, input_type = ginp.get_input(path, filter_results=False)\n\n if input_type == 'data (MTZ)':\n input_type = 'structure factors'\n elif input_type == 'text' and path.endswith('stol'):\n input_type = 'background'\n\n if input_type in type_choices:\n preferred_selection = type_choices.index(input_type)\n return inputs, type_choices, preferred_selection\n\n def add_item(self, path):\n # Generate item\n inputs, inp_choices, inp_sel = self.set_type_choices(path)\n type_choice = ct.DataTypeChoice(self.ctr,\n choices=inp_choices)\n item = ct.InputListItem(path=path,\n type=type_choice,\n buttons=ct.MiniButtonBoxInput(self.ctr))\n\n self.Bind(wx.EVT_CHOICE, self.onTypeChoice, item.type.type)\n # item.buttons.btn_mag.Bind(wx.EVT_BUTTON, self.onMagButton)\n # item.buttons.btn_delete.Bind(wx.EVT_BUTTON, self.onDelButton)\n # item.buttons.btn_info.Bind(wx.EVT_BUTTON, self.onInfoButton)\n self.Bind(wx.EVT_BUTTON, self.onMagButton, item.buttons.btn_mag)\n self.Bind(wx.EVT_BUTTON, self.onDelButton, item.buttons.btn_delete)\n self.Bind(wx.EVT_BUTTON, self.onInfoButton, item.buttons.btn_info)\n\n # Insert list item\n idx = self.ctr.InsertStringItem(self.ctr.GetItemCount() + 1, item.path)\n self.ctr.SetItemWindow(idx, 1, item.type, expand=True)\n self.ctr.SetItemWindow(idx, 2, item.buttons, expand=True)\n\n # Set drop-down selection, check it for data and open other tabs\n item.type.type.SetSelection(inp_sel)\n if item.type.type.GetString(inp_sel) in ('coordinates',\n 'structure factors',\n 'background',\n 'raw image file'):\n if \"image\" in item.type.type.GetString(inp_sel):\n view_bmp = bitmaps.fetch_custom_icon_bitmap('image_viewer16')\n item.buttons.btn_mag.SetBitmapLabel(view_bmp)\n else:\n warn_bmp = bitmaps.fetch_icon_bitmap('actions', 'status_unknown',\n size=16)\n item.buttons.btn_info.SetBitmapLabel(warn_bmp)\n item.warning = True\n\n # Record index in all relevant places\n item.id = idx\n item.buttons.index = idx\n item.type.index = idx\n item.type_selection = inp_sel\n\n # Resize columns to fit content\n self.ctr.SetColumnWidth(1, width=-1)\n self.ctr.SetColumnWidth(2, width=-1)\n self.ctr.SetColumnWidth(0, width=-3)\n\n # Make sure all the choice lists are the same size\n if item.type.type.GetSize()[0] < self.ctr.GetColumnWidth(2) - 5:\n item.type.type.SetSize((self.ctr.GetColumnWidth(2) - 5, -1))\n\n # Attach data object to item\n self.ctr.SetItemData(item.id, item)\n\n self.Layout()\n\n def onTypeChoice(self, e):\n type = e.GetEventObject().GetParent()\n item_data = self.ctr.GetItemData(type.index)\n item_data.type.type.SetSelection(type.type.GetSelection())\n item_data.type_selection = type.type.GetSelection()\n\n # Evaluate whether data folders / files are present\n data_items = 0\n for idx in range(self.ctr.GetItemCount()):\n if self.ctr.GetItemData(idx).type_selection != 0:\n data_items += 1\n if data_items > 0:\n self.main_window.toolbar.EnableTool(self.main_window.tb_btn_run.GetId(),\n True)\n else:\n self.main_window.toolbar.EnableTool(self.main_window.tb_btn_run.GetId(),\n False)\n e.Skip()\n\n def onMagButton(self, e):\n idx = e.GetEventObject().GetParent().index\n item_obj = self.ctr.GetItemData(idx)\n path = item_obj.path\n type = item_obj.type.type.GetString(item_obj.type_selection)\n\n if os.path.isfile(path):\n if type in ('raw image file', 'image pickle file'):\n self.view_images([path], img_type=type)\n elif type == 'text':\n with open(path, 'r') as f:\n file_list = f.readlines()\n msg = ' '.join(file_list)\n textview = dlg.TextFileView(self, title=path, contents=msg)\n textview.ShowModal()\n else:\n wx.MessageBox('Unknown file format', 'Warning',\n wx.OK | wx.ICON_EXCLAMATION)\n\n def view_images(self, img_list, img_type=None):\n ''' Launches image viewer (depending on backend) '''\n viewer = self.parent.gparams.advanced.image_viewer\n if viewer == 'cxi.view' and 'pickle' not in img_type:\n wx.MessageBox('cxi.view only accepts image pickles', 'Warning',\n wx.OK | wx.ICON_EXCLAMATION)\n else:\n if len(img_list) > 10:\n view_warning = dlg.ViewerWarning(self, len(img_list))\n if view_warning.ShowModal() == wx.ID_OK:\n # parse 'other' entry\n img_no_string = str(view_warning.no_images).split(',')\n filenames = []\n for n in img_no_string:\n if '-' in n:\n img_limits = n.split('-')\n start = int(min(img_limits))\n end = int(max(img_limits))\n if start <= len(img_list) and end <= len(img_list):\n filenames.extend(img_list[start:end])\n else:\n if int(n) <= len(img_list):\n filenames.append(img_list[int(n)])\n file_string = ' '.join(filenames)\n else:\n return\n view_warning.Close()\n elif viewer == 'distl.image_viewer' and len(img_list) > 1:\n wx.MessageBox('distl.image_viewer can show only one image', 'Warning',\n wx.OK | wx.ICON_EXCLAMATION)\n file_string = img_list[0]\n else:\n file_string = ' '.join(img_list)\n\n viewer = thr.ImageViewerThread(self,\n viewer=viewer,\n file_string=file_string,\n img_type=img_type)\n viewer.start()\n\n\n def onDelButton(self, e):\n item = e.GetEventObject().GetParent()\n self.delete_button(item.index)\n\n def delete_all(self):\n for idx in range(self.ctr.GetItemCount()):\n self.delete_button(index=0)\n\n def delete_button(self, index):\n self.ctr.DeleteItem(index)\n\n # Refresh widget and list item indices\n if self.ctr.GetItemCount() > 0:\n for i in range(self.ctr.GetItemCount()):\n item_data = self.ctr.GetItemData(i)\n item_data.id = i\n item_data.buttons.index = i\n item_data.type.index = i\n type_choice = self.ctr.GetItemWindow(i, col=1)\n type_selection = item_data.type.type.GetSelection()\n type_choice.type.SetSelection(type_selection)\n self.ctr.SetItemData(i, item_data)\n\n def onInfoButton(self, e):\n ''' Info / alert / error button (will change depending on circumstance) '''\n idx = e.GetEventObject().GetParent().index\n item_obj = self.ctr.GetItemData(idx)\n item_type = item_obj.type.type.GetString(item_obj.type_selection)\n\n if item_obj.warning:\n wx.MessageBox(item_obj.info['WARNING'], 'Warning', wx.OK |\n wx.ICON_EXCLAMATION)\n else:\n wx.MessageBox(item_obj.info[item_type], 'Info', wx.OK |\n wx.ICON_INFORMATION)\n" ]
[ [ "numpy.percentile", "matplotlib.backends.backend_wxagg.FigureCanvasWxAgg", "numpy.mean", "numpy.random.randint", "matplotlib.figure.Figure" ] ]
mandubian/transformers
[ "0cb163865a4c761c226b151283309eedb2b1ca4d" ]
[ "transformers/tests/modeling_tf_transfo_xl_test.py" ]
[ "# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport unittest\nimport random\nimport shutil\n\nfrom .modeling_tf_common_test import (TFCommonTestCases, ids_tensor)\nfrom .configuration_common_test import ConfigTester\nfrom .utils import require_tf, slow\n\nfrom transformers import TransfoXLConfig, is_tf_available\n\nif is_tf_available():\n import tensorflow as tf\n from transformers.modeling_tf_transfo_xl import (TFTransfoXLModel,\n TFTransfoXLLMHeadModel,\n TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_MAP)\n\n\n@require_tf\nclass TFTransfoXLModelTest(TFCommonTestCases.TFCommonModelTester):\n\n all_model_classes = (TFTransfoXLModel, TFTransfoXLLMHeadModel) if is_tf_available() else ()\n test_pruning = False\n test_torchscript = False\n test_resize_embeddings = False\n\n class TFTransfoXLModelTester(object):\n\n def __init__(self,\n parent,\n batch_size=13,\n seq_length=7,\n mem_len=30,\n clamp_len=15,\n is_training=True,\n use_labels=True,\n vocab_size=99,\n cutoffs=[10, 50, 80],\n hidden_size=32,\n d_embed=32,\n num_attention_heads=4,\n d_head=8,\n d_inner=128,\n div_val=2,\n num_hidden_layers=5,\n scope=None,\n seed=1,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.mem_len = mem_len\n self.key_len = seq_length + mem_len\n self.clamp_len = clamp_len\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.cutoffs = cutoffs\n self.hidden_size = hidden_size\n self.d_embed = d_embed\n self.num_attention_heads = num_attention_heads\n self.d_head = d_head\n self.d_inner = d_inner\n self.div_val = div_val\n self.num_hidden_layers = num_hidden_layers\n self.scope = scope\n self.seed = seed\n\n def prepare_config_and_inputs(self):\n input_ids_1 = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)\n input_ids_2 = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)\n\n lm_labels = None\n if self.use_labels:\n lm_labels = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)\n\n config = TransfoXLConfig(\n vocab_size_or_config_json_file=self.vocab_size,\n mem_len=self.mem_len,\n clamp_len=self.clamp_len,\n cutoffs=self.cutoffs,\n d_model=self.hidden_size,\n d_embed=self.d_embed,\n n_head=self.num_attention_heads,\n d_head=self.d_head,\n d_inner=self.d_inner,\n div_val=self.div_val,\n n_layer=self.num_hidden_layers)\n\n return (config, input_ids_1, input_ids_2, lm_labels)\n\n def set_seed(self):\n random.seed(self.seed)\n tf.random.set_seed(self.seed)\n\n def create_and_check_transfo_xl_model(self, config, input_ids_1, input_ids_2, lm_labels):\n model = TFTransfoXLModel(config)\n\n hidden_states_1, mems_1 = model(input_ids_1)\n\n inputs = {'input_ids': input_ids_2,\n 'mems': mems_1}\n\n hidden_states_2, mems_2 = model(inputs)\n\n result = {\n \"hidden_states_1\": hidden_states_1.numpy(),\n \"mems_1\": [mem.numpy() for mem in mems_1],\n \"hidden_states_2\": hidden_states_2.numpy(),\n \"mems_2\": [mem.numpy() for mem in mems_2],\n }\n\n self.parent.assertListEqual(\n list(result[\"hidden_states_1\"].shape),\n [self.batch_size, self.seq_length, self.hidden_size])\n self.parent.assertListEqual(\n list(result[\"hidden_states_2\"].shape),\n [self.batch_size, self.seq_length, self.hidden_size])\n self.parent.assertListEqual(\n list(list(mem.shape) for mem in result[\"mems_1\"]),\n [[self.mem_len, self.batch_size, self.hidden_size]] * self.num_hidden_layers)\n self.parent.assertListEqual(\n list(list(mem.shape) for mem in result[\"mems_2\"]),\n [[self.mem_len, self.batch_size, self.hidden_size]] * self.num_hidden_layers)\n\n\n def create_and_check_transfo_xl_lm_head(self, config, input_ids_1, input_ids_2, lm_labels):\n model = TFTransfoXLLMHeadModel(config)\n\n lm_logits_1, mems_1 = model(input_ids_1)\n\n inputs = {'input_ids': input_ids_1,\n 'labels': lm_labels}\n _, mems_1 = model(inputs)\n\n lm_logits_2, mems_2 = model([input_ids_2, mems_1])\n\n inputs = {'input_ids': input_ids_1,\n 'mems': mems_1,\n 'labels': lm_labels}\n\n _, mems_2 = model(inputs)\n\n result = {\n \"mems_1\": [mem.numpy() for mem in mems_1],\n \"lm_logits_1\": lm_logits_1.numpy(),\n \"mems_2\": [mem.numpy() for mem in mems_2],\n \"lm_logits_2\": lm_logits_2.numpy(),\n }\n\n self.parent.assertListEqual(\n list(result[\"lm_logits_1\"].shape),\n [self.batch_size, self.seq_length, self.vocab_size])\n self.parent.assertListEqual(\n list(list(mem.shape) for mem in result[\"mems_1\"]),\n [[self.mem_len, self.batch_size, self.hidden_size]] * self.num_hidden_layers)\n\n self.parent.assertListEqual(\n list(result[\"lm_logits_2\"].shape),\n [self.batch_size, self.seq_length, self.vocab_size])\n self.parent.assertListEqual(\n list(list(mem.shape) for mem in result[\"mems_2\"]),\n [[self.mem_len, self.batch_size, self.hidden_size]] * self.num_hidden_layers)\n\n def prepare_config_and_inputs_for_common(self):\n config_and_inputs = self.prepare_config_and_inputs()\n (config, input_ids_1, input_ids_2, lm_labels) = config_and_inputs\n inputs_dict = {'input_ids': input_ids_1}\n return config, inputs_dict\n\n\n def setUp(self):\n self.model_tester = TFTransfoXLModelTest.TFTransfoXLModelTester(self)\n self.config_tester = ConfigTester(self, config_class=TransfoXLConfig, d_embed=37)\n\n def test_config(self):\n self.config_tester.run_common_tests()\n\n def test_transfo_xl_model(self):\n self.model_tester.set_seed()\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_transfo_xl_model(*config_and_inputs)\n\n def test_transfo_xl_lm_head(self):\n self.model_tester.set_seed()\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_transfo_xl_lm_head(*config_and_inputs)\n\n @slow\n def test_model_from_pretrained(self):\n cache_dir = \"/tmp/transformers_test/\"\n for model_name in list(TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]:\n model = TFTransfoXLModel.from_pretrained(model_name, cache_dir=cache_dir)\n shutil.rmtree(cache_dir)\n self.assertIsNotNone(model)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "tensorflow.random.set_seed" ] ]
tanakatsu/jobcan_man_hour_auto_input
[ "e68cc438205162d604ea15b4bc7fdc8c66c0e0df" ]
[ "generate_projects_and_tasks.py" ]
[ "from lib.jobcan import JobcanInput\nimport pandas as pd\nfrom argparse import ArgumentParser\nimport os\n\nparser = ArgumentParser()\nparser.add_argument('--chrome_driver_path', help='chrome driver path')\nparser.add_argument('--client_id', help='client_id')\nparser.add_argument('--email', help='email')\nparser.add_argument('--password', help='password')\nargs = parser.parse_args()\n\n# Get credentials\nCHROMEDRIVER_PATH = args.chrome_driver_path if args.chrome_driver_path else os.environ.get('JOBCAN_CHROMEDRIVER_PATH')\nCLIENT_ID = args.client_id if args.client_id else os.environ.get('JOBCAN_CLIENT_ID')\nEMAIL = args.email if args.email else os.environ.get('JOBCAN_EMAIL')\nPASSWORD = args.password if args.password else os.environ.get('JOBCAN_PASSWORD')\n\n# Retrieve projects and tasks list\njobcan_cli = JobcanInput(CHROMEDRIVER_PATH, client_id=CLIENT_ID, email=EMAIL, password=PASSWORD)\njobcan_cli.login()\njobcan_cli.open_man_hour_manage()\njobcan_cli.select_date(open=True)\njobcan_cli.add_blank_record()\nprojects_and_tasks = jobcan_cli.get_projects_and_tasks()\njobcan_cli.quit()\nprint(projects_and_tasks)\n\n# create csv file\ndf = pd.DataFrame(columns=[\"project\", \"task\"])\nfor project, tasks in projects_and_tasks.items():\n for task in tasks:\n df = df.append(pd.Series([project, task], index=df.columns), ignore_index=True)\ndf.to_csv(\"project_task.csv\", index=False)\n" ]
[ [ "pandas.DataFrame", "pandas.Series" ] ]
markorland/markorland
[ "a14d75b0d75cdaaf49209c0cb9074e5d05992a0e" ]
[ "Scraping/aws_scraper.py" ]
[ "import pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom time import sleep\nimport re\n\ndef get_new_driver():\n options = webdriver.ChromeOptions()\n options.binary_location = '/opt/google/chrome/google-chrome'\n options.add_argument('headless')\n driver = webdriver.Chrome('./chromedriver', chrome_options=options)\n\n return driver\n\nreview_grabber = lambda x: re.search('overall:\\s\\d\\.\\d*(.*[\\s\\S]*\\d characters)', x).group(1)\n\ndef review_cleaner(string):\n x = review_grabber(string)\n x = re.sub('\\d* characters', '', x)\n x = re.sub('\\n', ' ', x)\n x = re.sub(',', '', x)\n return x\n\ndef get_user_reviews_csv(url):\n counter = 0\n review_number = 1\n for i in range(0,101):\n driver.get(f'https://www.beeradvocate.com{url}?view=beer&sort=&start={i*25}')\n sleep(2)\n beer_page = driver.page_source\n beer_page_soup = BeautifulSoup(beer_page, 'lxml')\n \n reviews = beer_page_soup.find_all('div', {'id':'rating_fullview_content_2'})\n \n counter += 1\n print(f'{url} -- page {counter}')\n \n for count, review in enumerate(reviews):\n score = review.find('span', {'class': 'BAscore_norm'}).text\n breakdown = review.find('span', {'class': 'muted'}).text\n u_names = review.find('a', {'class':'username'}).text\n try:\n r_text = review_cleaner(reviews[count].text)\n except:\n r_text = \"No Review\"\n \n master_list = [str(review_number), url, score, breakdown, u_names, r_text]\n with open('./aws_user_reviews.csv', 'a+') as f:\n print(','.join(master_list), file=f)\n \n review_number += 1\n \n sleep(2)\n\n\nsleep(50)\n\ndriver = get_new_driver()\ndf_beer = pd.read_csv('./df_beer.csv', encoding = \"latin1\")\ndf_beer['url'].apply(get_user_reviews_csv)" ]
[ [ "pandas.read_csv" ] ]
tsutterley/LSsurf
[ "6333e70f33b7d9fed25fbfe4c45b9d5a8e2ef488" ]
[ "LSsurf/read_ICESat2.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 20 15:00:05 2019\n\n@author: ben\n\"\"\"\nimport numpy as np\nfrom ATL11.check_ATL06_hold_list import read_files as read_hold_files\n#from PointDatabase.geo_index import geo_index\n#from PointDatabase.point_data import point_data\n#from PointDatabase.ATL06_filters import segDifferenceFilter\nimport pointCollection as pc\n\ndef segDifferenceFilter(D6, tol=2, setValid=True, toNaN=False, subset=False):\n dAT=20.\n if D6.h_li.shape[0] < 3:\n mask=np.ones_like(D6.h_li, dtype=bool)\n return mask\n EPplus=D6.h_li + dAT*D6.dh_fit_dx\n EPminus=D6.h_li - dAT*D6.dh_fit_dx\n segDiff=np.zeros_like(D6.h_li)\n if len(D6.h_li.shape)>1:\n segDiff[0:-1,:]=np.abs(EPplus[0:-1,:]-D6.h_li[1:, :])\n segDiff[1:,:]=np.maximum(segDiff[1:,:], np.abs(D6.h_li[0:-1,:]-EPminus[1:,:]))\n else:\n segDiff[0:-1]=np.abs(EPplus[0:-1]-D6.h_li[1:])\n segDiff[1:]=np.maximum(segDiff[1:], np.abs(D6.h_li[0:-1]-EPminus[1:]))\n mask=segDiff<tol\n if setValid:\n D6.valid=D6.valid & mask\n if toNaN:\n D6.h_li[mask==0]=np.NaN\n if subset:\n D6.index(np.any(mask==1, axis=1))\n\n return mask\n\n\ndef read_ICESat2(xy0, W, gI_file, sensor=2, SRS_proj4=None, tiled=True, seg_diff_tol=2, blockmedian_scale=None, cplx_accept_threshold=0.):\n field_dict={None:['delta_time','h_li','h_li_sigma','latitude','longitude','atl06_quality_summary','segment_id','sigma_geo_h'], \n 'fit_statistics':['dh_fit_dx', 'dh_fit_dy', 'n_fit_photons','w_surface_window_final','snr_significance'],\n 'geophysical':['tide_ocean'],\n 'ground_track':['x_atc'],\n 'orbit_info':['rgt','cycle_number'],\n 'derived':['valid', 'BP','LR']}\n if tiled:\n fields=[]\n for key in field_dict:\n fields += field_dict[key]\n fields += ['x','y']\n else:\n fields=field_dict\n px, py=np.meshgrid(np.arange(xy0[0]-W['x']/2, xy0[0]+W['x']/2+1.e4, 1.e4),np.arange(xy0[1]-W['y']/2, xy0[1]+W['y']/2+1.e4, 1.e4) ) \n D0=pc.geoIndex().from_file(gI_file).query_xy((px.ravel(), py.ravel()), fields=fields)\n if D0 is None or len(D0)==0:\n return [None]\n # check the D6 filenames against the blacklist of bad files\n if tiled:\n D0=pc.reconstruct_ATL06_tracks(pc.data(fields=fields).from_list(D0))\n hold_list = read_hold_files()\n hold_list = {(item[0], item[1]) for item in hold_list}\n D1=list()\n for ind, D in enumerate(D0):\n if D.size<2:\n continue\n delete_file = (D.cycle_number[0], D.rgt[0]) in hold_list\n if delete_file==0:\n D1.append(D)\n\n # D1 is now a filtered version of D0\n D_pt=pc.data().from_list(D1)\n bin_xy=1.e4*np.round((D_pt.x+1j*D_pt.y)/1.e4)\n cplx_bins=[]\n for xy0 in np.unique(bin_xy):\n ii=np.flatnonzero(bin_xy==xy0)\n if np.mean(D_pt.atl06_quality_summary[ii]==0) < cplx_accept_threshold:\n cplx_bins+=[xy0]\n cplx_bins=np.array(cplx_bins)\n sigma_corr=np.zeros(len(D1))\n for ind, D in enumerate(D1):\n\n\n valid=segDifferenceFilter(D, setValid=False, toNaN=False, tol=seg_diff_tol)\n \n D.assign({'quality':D.atl06_quality_summary})\n \n cplx_data=np.in1d(1.e4*np.round((D.x+1j*D.y)/1.e4), cplx_bins)\n if np.any(cplx_data):\n D.quality[cplx_data] = (D.snr_significance[cplx_data] > 0.02) | \\\n (D.n_fit_photons[cplx_data]/D.w_surface_window_final[cplx_data] < 5)\n valid[cplx_data] |= segDifferenceFilter(D, setValid=False, toNaN=False, tol=2*seg_diff_tol)[cplx_data]\n \n D.h_li[valid==0] = np.NaN\n D.h_li[D.quality==1] = np.NaN\n if blockmedian_scale is not None:\n D.blockmedian(blockmedian_scale, field='h_li')\n \n # rename the h_li field to 'z', and set time to the year\n # note that the extra half day is needed because 2018 is in between two leap years\n D.assign({'z': D.h_li, 'time':D.delta_time/24/3600/365.25+2018+0.5/365.25,\n 'sigma':D.h_li_sigma,'cycle':D.cycle_number})\n # thin to 40 m\n D.index(np.mod(D.segment_id, 2)==0) \n if 'x' not in D.fields:\n D.get_xy(SRS_proj4)\n #D.index(np.isfinite(D.h_li), list_of_fields=['x','y','z','time','year','sigma','sigma_corr','rgt','cycle'])\n \n D.assign({'sensor':np.zeros_like(D.x)+sensor})\n if np.any(np.isfinite(D.dh_fit_dy)):\n dhdy_med=np.nanmedian(D.dh_fit_dy)\n dhdx_med=np.nanmedian(D.dh_fit_dx)\n else:\n dhdy_med=np.NaN\n dhdx_med=np.NaN\n sigma_geo_x=8\n sigma_corr[ind]=np.sqrt(0.03**2+sigma_geo_x**2*(dhdx_med**2+dhdy_med**2))\n if ~np.isfinite(sigma_corr[ind]):\n sigma_corr[ind]=0.1\n D.assign({'sigma_corr':np.zeros_like(D.h_li)+sigma_corr[ind]})\n D1[ind]=D.copy_subset(np.isfinite(D.h_li), datasets=['x','y','z','time',\\\n 'delta_time','sigma','sigma_corr','rgt','cycle',\\\n 'sensor', 'BP','LR'])\n return D1\n\ndef main():\n import glob\n #gI_file='/Volumes/insar10/ben/IS2_tiles/GL/GeoIndex.h5'\n gI_file=glob.glob('/Volumes/ice2/ben/scf/GL_06/latest/tiles/*/GeoIndex.h5')[0]\n xy0=[-170000.0, -2280000.0]\n dI=pc.data().from_list(read_ICESat2(xy0, {'x':4.e4, 'y':4.e4}, gI_file, cplx_accept_threshold=0.25))\n import matplotlib.pyplot as plt\n\n plt.scatter(dI.x, dI.y, c=dI.z, linewidth=0); plt.colorbar()\n plt.axis('equal')\n \n \nif __name__=='__main__':\n main()" ]
[ [ "numpy.array", "numpy.zeros_like", "matplotlib.pyplot.colorbar", "numpy.ones_like", "numpy.mod", "numpy.round", "numpy.mean", "numpy.any", "numpy.arange", "numpy.abs", "numpy.sqrt", "matplotlib.pyplot.axis", "matplotlib.pyplot.scatter", "numpy.isfinite", "numpy.nanmedian", "numpy.unique", "numpy.flatnonzero" ] ]
Liang-ZX/EDSR-PyTorch
[ "a245d02fa1c3d799402aeadf7320f1c8a116e86a" ]
[ "src/model/latticenet.py" ]
[ "import torch\r\nimport torch.nn as nn\r\nfrom model import common\r\nimport torch.nn.functional as F\r\nfrom model.splitsr import ResidualBlock, SplitSRBlock\r\n\r\n\r\ndef make_model(args, parent=False):\r\n return LatticeNet(args)\r\n\r\n\r\ndef mean_channels(x):\r\n assert(x.dim() == 4)\r\n spatial_sum = x.sum(3, keepdim=True).sum(2, keepdim=True)\r\n return spatial_sum / (x.shape[2] * x.shape[3])\r\n\r\n\r\ndef std(x):\r\n assert(x.dim() == 4)\r\n x_mean = mean_channels(x)\r\n x_var = (x - x_mean).pow(2).sum(3, keepdim=True).sum(2, keepdim=True) / (x.shape[2] * x.shape[3])\r\n return x_var.pow(0.5)\r\n\r\n\r\nclass CoffConv(nn.Module):\r\n def __init__(self, num_fea):\r\n super(CoffConv, self).__init__()\r\n self.upper_branch = nn.Sequential(\r\n nn.AdaptiveAvgPool2d(1),\r\n nn.Conv2d(num_fea, num_fea // 16, 1, 1, 0),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(num_fea // 16, num_fea, 1, 1, 0),\r\n # nn.ReLU(inplace=True),\r\n nn.Sigmoid()\r\n )\r\n\r\n self.std = std\r\n self.lower_branch = nn.Sequential(\r\n nn.Conv2d(num_fea, num_fea // 16, 1, 1, 0),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(num_fea // 16, num_fea, 1, 1, 0),\r\n # nn.ReLU(inplace=True),\r\n nn.Sigmoid()\r\n )\r\n\r\n def forward(self, fea):\r\n upper = self.upper_branch(fea)\r\n lower = self.std(fea)\r\n lower = self.lower_branch(lower)\r\n\r\n out = torch.add(upper, lower) / 2\r\n\r\n return out\r\n\r\n\r\nclass ResLBlock(nn.Module):\r\n def __init__(self, num_fea):\r\n super(ResLBlock, self).__init__()\r\n conv = common.default_conv\r\n H_modules = [\r\n ResidualBlock(\r\n conv, num_fea, kernel_size=3, bias=True, bn=False, act=nn.LeakyReLU(0.05))\r\n # SplitSRBlock(\r\n # conv, num_fea, kernel_size=3, alpha=0.25, bias=True, bn=False, act=nn.LeakyReLU(0.05))\r\n for _ in range(3)]\r\n self.H_conv = nn.Sequential(*H_modules)\r\n\r\n self.A1_coff_conv = CoffConv(num_fea)\r\n self.B1_coff_conv = CoffConv(num_fea)\r\n\r\n G_modules = [\r\n ResidualBlock(\r\n conv, num_fea, kernel_size=3, bias=True, bn=False, act=nn.LeakyReLU(0.05))\r\n # SplitSRBlock(\r\n # conv, num_fea, kernel_size=3, alpha=0.25, bias=True, bn=False, act=nn.LeakyReLU(0.05))\r\n for _ in range(3)]\r\n self.G_conv = nn.Sequential(*G_modules)\r\n\r\n self.A2_coff_conv = CoffConv(num_fea)\r\n self.B2_coff_conv = CoffConv(num_fea)\r\n\r\n self.fuse = nn.Conv2d(num_fea * 2, num_fea, 1, 1, 0)\r\n\r\n def forward(self, x):\r\n H = self.H_conv(x)\r\n A1 = self.A1_coff_conv(H)\r\n P1 = x + A1 * H\r\n B1 = self.B1_coff_conv(x)\r\n Q1 = H + B1 * x\r\n\r\n G = self.G_conv(P1)\r\n B2 = self.B2_coff_conv(G)\r\n Q2 = Q1 + B2 * G\r\n A2 = self.A2_coff_conv(Q1)\r\n P2 = G + Q1 * A2\r\n\r\n out = self.fuse(torch.cat([P2, Q2], dim=1))\r\n\r\n return out\r\n\r\n\r\nclass LBlock(nn.Module):\r\n def __init__(self, num_fea):\r\n super(LBlock, self).__init__()\r\n mid_channel = 48 #num_fea #48\r\n self.H_conv = nn.Sequential(\r\n nn.Conv2d(num_fea, mid_channel, 3, 1, 1),\r\n nn.LeakyReLU(0.05),\r\n nn.Conv2d(mid_channel, mid_channel, 3, 1, 1),\r\n nn.LeakyReLU(0.05),\r\n nn.Conv2d(mid_channel, num_fea, 3, 1, 1),\r\n nn.LeakyReLU(0.05),\r\n )\r\n\r\n self.A1_coff_conv = CoffConv(num_fea)\r\n self.B1_coff_conv = CoffConv(num_fea)\r\n\r\n self.G_conv = nn.Sequential(\r\n nn.Conv2d(num_fea, mid_channel, 3, 1, 1),\r\n nn.LeakyReLU(0.05),\r\n nn.Conv2d(mid_channel, mid_channel, 3, 1, 1),\r\n nn.LeakyReLU(0.05),\r\n nn.Conv2d(mid_channel, num_fea, 3, 1, 1),\r\n nn.LeakyReLU(0.05),\r\n )\r\n\r\n self.A2_coff_conv = CoffConv(num_fea)\r\n self.B2_coff_conv = CoffConv(num_fea)\r\n\r\n self.fuse = nn.Conv2d(num_fea * 2, num_fea, 1, 1, 0)\r\n\r\n def forward(self, x):\r\n H = self.H_conv(x)\r\n A1 = self.A1_coff_conv(H)\r\n P1 = x + A1 * H\r\n B1 = self.B1_coff_conv(x)\r\n Q1 = H + B1 * x\r\n\r\n G = self.G_conv(P1)\r\n B2 = self.B2_coff_conv(G)\r\n Q2 = Q1 + B2 * G\r\n A2 = self.A2_coff_conv(Q1)\r\n P2 = G + Q1 * A2\r\n\r\n out = self.fuse(torch.cat([P2, Q2], dim=1))\r\n\r\n return out\r\n\r\n\r\nclass BFModule(nn.Module):\r\n def __init__(self, num_fea):\r\n super(BFModule, self).__init__()\r\n self.conv4 = nn.Conv2d(num_fea, num_fea // 2, 1, 1, 0)\r\n self.conv3 = nn.Conv2d(num_fea, num_fea // 2, 1, 1, 0)\r\n self.fuse43 = nn.Conv2d(num_fea, num_fea // 2, 1, 1, 0)\r\n self.conv2 = nn.Conv2d(num_fea, num_fea // 2, 1, 1, 0)\r\n self.fuse32 = nn.Conv2d(num_fea, num_fea // 2, 1, 1, 0)\r\n self.conv1 = nn.Conv2d(num_fea, num_fea // 2, 1, 1, 0)\r\n\r\n self.act = nn.ReLU(inplace=True)\r\n\r\n def forward(self, x_list):\r\n H4 = self.act(self.conv4(x_list[3]))\r\n H3_half = self.act(self.conv3(x_list[2]))\r\n H3 = self.fuse43(torch.cat([H4, H3_half], dim=1))\r\n H2_half = self.act(self.conv2(x_list[1]))\r\n H2 = self.fuse32(torch.cat([H3, H2_half], dim=1))\r\n H1_half = self.act(self.conv1(x_list[0]))\r\n H1 = torch.cat([H2, H1_half], dim=1)\r\n\r\n return H1\r\n\r\n\r\nclass LatticeNet(nn.Module):\r\n def __init__(self, args):\r\n super(LatticeNet, self).__init__()\r\n in_channels = args.n_colors\r\n out_channels = args.n_colors\r\n # num_fea = args.n_feats\r\n num_fea = 64 #TODO FOR LatticeNet\r\n upscale_factor = args.scale[0]\r\n num_LBs = args.num_LBs\r\n self.sub_mean = common.MeanShift(args.rgb_range)\r\n self.add_mean = common.MeanShift(args.rgb_range, sign=1)\r\n self.num_LBs = num_LBs\r\n\r\n # feature extraction\r\n self.fea_conv = nn.Sequential(\r\n nn.Conv2d(in_channels, num_fea, 3, 1, 1),\r\n nn.Conv2d(num_fea, num_fea, 3, 1, 1)\r\n )\r\n\r\n # LBlocks\r\n LBs = []\r\n for i in range(num_LBs):\r\n LBs.append(LBlock(num_fea)) #TODO\r\n # LBs.append(ResLBlock(num_fea))\r\n self.LBs = nn.ModuleList(LBs)\r\n\r\n # BFModule\r\n self.BFM = BFModule(num_fea)\r\n\r\n # Reconstruction\r\n self.upsample = nn.Sequential(\r\n nn.Conv2d(num_fea, num_fea, 3, 1, 1),\r\n nn.Conv2d(num_fea, out_channels * (upscale_factor ** 2), 3, 1, 1),\r\n nn.PixelShuffle(upscale_factor)\r\n )\r\n\r\n def forward(self, x):\r\n x = self.sub_mean(x)\r\n\r\n # feature extraction\r\n fea = self.fea_conv(x)\r\n\r\n # LBlocks\r\n outs = []\r\n temp = fea\r\n for i in range(self.num_LBs):\r\n temp = self.LBs[i](temp)\r\n outs.append(temp)\r\n\r\n # BFM\r\n H = self.BFM(outs)\r\n\r\n # reconstruct\r\n out = self.upsample(H + fea)\r\n\r\n out = self.add_mean(out)\r\n\r\n return out\r\n\r\n def load_state_dict(self, state_dict, strict=False):\r\n own_state = self.state_dict()\r\n for name, param in state_dict.items():\r\n if name in own_state:\r\n if isinstance(param, nn.Parameter):\r\n param = param.data\r\n try:\r\n own_state[name].copy_(param)\r\n except Exception:\r\n if name.find('tail') >= 0:\r\n print('Replace pre-trained upsampler to new one...')\r\n else:\r\n raise RuntimeError('While copying the parameter named {}, '\r\n 'whose dimensions in the model are {} and '\r\n 'whose dimensions in the checkpoint are {}.'\r\n .format(name, own_state[name].size(), param.size()))\r\n elif strict:\r\n if name.find('tail') == -1:\r\n raise KeyError('unexpected key \"{}\" in state_dict'\r\n .format(name))\r\n\r\n if strict:\r\n missing = set(own_state.keys()) - set(state_dict.keys())\r\n if len(missing) > 0:\r\n raise KeyError('missing keys in state_dict: \"{}\"'.format(missing))\r\n" ]
[ [ "torch.cat", "torch.nn.ModuleList", "torch.nn.Sigmoid", "torch.nn.Sequential", "torch.nn.LeakyReLU", "torch.add", "torch.nn.ReLU", "torch.nn.PixelShuffle", "torch.nn.Conv2d", "torch.nn.AdaptiveAvgPool2d" ] ]
saksham/CarND-Advanced-Lane-Lines
[ "0ac649696bc00cf7be03107733eba0e4dbd27d9f" ]
[ "scripts/plot.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport math\n\nfrom matplotlib import image as mpimg\nfrom matplotlib import pyplot as plt\n\n# measured coordinates from lane corners for perspective transform\n# img = mpimg.imread('examples/straight_lines1.jpg')\n\n# measured lane marking for calculating curvature\nimg = mpimg.imread('output/images/test5.jpg.2.warped_orig.jpg')\nprint('Distances is approx {} and {} pixels in X and Y directions respectively'.format(1167.92 - 169.8, 673-554))\n\n\n\nplt.imshow(img)\nplt.show()\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.image.imread", "matplotlib.pyplot.imshow" ] ]
hadisna/Makov-Decision-Process-Neural-Network-For-Global-Optimization
[ "228d650d7ac45d0d5ddd020c6d01d26de7db91a7" ]
[ "MDPN.py" ]
[ "import numpy as np\r\nimport math\r\nimport argparse, random\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef ChangeDomain(temp_e, umax, umin, Size, Codel, n, Po, temp_e3, temp_e2):\r\n v_max = math.floor((n * Codel - 1) / Codel)\r\n umax1 = np.array([[0.0] for i in range(v_max + 1)])\r\n umin1 = np.array([[0.0] for i in range(v_max + 1)])\r\n\r\n for j in range(0, n * Codel, Codel):\r\n xx = temp_e[:, j]\r\n xx = xx.reshape((-1, 1))\r\n xx = np.array(sorted(xx))\r\n dd = np.diff(np.concatenate([xx, [max(xx) + 1]], axis=0), axis=0)\r\n tmp = np.concatenate([[[1]], dd], axis=0)\r\n tmp3 = np.where(tmp > 0)[0]\r\n count = np.diff(tmp3, axis=0)\r\n count = count.reshape((-1, 1))\r\n yy = np.concatenate([xx[np.where(dd > 0)[0]], count], axis=1)\r\n yy = yy.T\r\n JJ = yy.shape\r\n y0 = 0.0\r\n y1 = 0.0\r\n y2 = 0.0\r\n y3 = 0.0\r\n y4 = 0.0\r\n for i in range(JJ[1]):\r\n if yy[0, i] == 0:\r\n y0 = yy[1, i] / Size\r\n elif yy[0, i] == 1:\r\n y1 = yy[1, i] / Size\r\n elif yy[0, i] == 2:\r\n y2 = yy[1, i] / Size\r\n elif yy[0, i] == 3:\r\n y3 = yy[1, i] / Size\r\n elif yy[0, i] == 4:\r\n y4 = yy[1, i] / Size\r\n v = math.floor(j / Codel)\r\n umax1[v] = umax[v]\r\n umin1[v] = umin[v]\r\n if y0 > Po and temp_e[0, j] == 0:\r\n umax[v] = (umax1[v] - umin1[v]) / 5 + umin1[v]\r\n umin[v] = umin1[v]\r\n if y1 > Po and temp_e[0, j] == 1:\r\n umax[v] = (umax1[v] - umin1[v]) * 2 / 5 + umin1[v]\r\n umin[v] = (umax1[v] - umin1[v]) / 5 + umin1[v]\r\n if y2 > Po and temp_e[0, j] == 2:\r\n umax[v] = (umax1[v] - umin1[v]) * 3 / 5 + umin1[v]\r\n umin[v] = (umax1[v] - umin1[v]) * 2 / 5 + umin1[v]\r\n if y3 > Po and temp_e[0, j] == 3:\r\n umax[v] = (umax1[v] - umin1[v]) * 4 / 5 + umin1[v]\r\n umin[v] = (umax1[v] - umin1[v]) * 3 / 5 + umin1[v]\r\n if y4 > Po and temp_e[0, j] == 4:\r\n umin[v] = (umax1[v] - umin1[v]) * 4 / 5 + umin1[v]\r\n umax[v] = umax1[v]\r\n if umax[v] != umax1[v] or umin[v] != umin1[v]:\r\n QBack = temp_e[:, (j + 1):(v + 1) * Codel]\r\n temp_e[:, j:((v + 1) * Codel - 1)] = QBack\r\n temp_e[:, (v + 1) * Codel - 1] = np.squeeze(np.round(4 * np.random.rand(Size, 1)), axis=(1,))\r\n temp_e[0, (v + 1) * Codel - 1] = 0\r\n TE1 = temp_e3\r\n QBack1 = TE1[:, (j + 1):(v + 1) * Codel]\r\n temp_e2[:, j:((v + 1) * Codel - 1)] = QBack1\r\n temp_e2[:, (v + 1) * Codel - 1] = np.squeeze(np.round(4 * np.random.rand(Size, 1)), axis=(1,))\r\n RR = [0 for i in range(Size)]\r\n for i in range(Size):\r\n for j in range(n * Codel):\r\n if temp_e[i, j] == temp_e[0, j] and j % (Codel-1) != 0:\r\n RR[i] = RR[i] + (math.pow(5, (Codel - ((j + 1) % Codel)))) / constant\r\n elif temp_e[i, j] == temp_e[0, j] and j % (Codel-1) == 0:\r\n RR[i] = RR[i] + 1 / constant\r\n for i in range(Size):\r\n RR[i] = RR[i] + 1 / (i + 1)\r\n\r\n OderRR = sorted(RR, reverse=True)\r\n IndexRR = sorted(range(len(RR)), key=lambda x: RR[x], reverse=True)\r\n TER = np.array([temp_e[IndexRR[i], :] for i in range(Size)])\r\n temp_e = TER.copy()\r\n temp_e1 = temp_e.copy()\r\n\r\n return temp_e, umax, umin, temp_e1, temp_e2\r\n\r\ndef ackley(fval, n):\r\n\r\n obj = 0.0\r\n obj1 = 0.0\r\n obj2 = 0.0\r\n for i in range(n):\r\n obj1 = obj1+fval[i]**2\r\n obj2 = obj2+math.cos(2*math.pi*fval[i])\r\n obj = -20*math.exp(-0.2*math.sqrt(obj1/n))-math.exp(obj2/n)+20+math.e\r\n\r\n return obj\r\n\r\ndef rosenbrock(fval, n):\r\n\r\n obj = 0\r\n for i in range(n-1):\r\n obj = obj+100*pow(fval[i+1]-pow((fval[i]), 2), 2)+pow((1-fval[i]), 2)\r\n\r\n return obj\r\n\r\ndef griewank(fval, n):\r\n\r\n obj = 0.0\r\n objt = 0.0\r\n objd = 1.0\r\n for i in range(n):\r\n objt = fval[i]**2.0/2.0+objt\r\n objd = math.cos(fval[i]/math.sqrt(i+1))*objd\r\n\r\n obj = objt-objd+1\r\n\r\n return obj\r\n\r\ndef rastrigin(fval, n):\r\n\r\n obj = 0.0\r\n for i in range(n):\r\n obj = obj+fval[i]**2-10*math.cos(2*math.pi*fval[i])\r\n\r\n obj=obj+10*n\r\n\r\n return obj\r\n\r\ndef evaluation(m, n, Codel, uma, umi):\r\n\r\n y = [0.0 for i in range(n)]\r\n x = [0.0 for i in range(n)]\r\n r = [0.0 for i in range(n)]\r\n\r\n for v in range(n):\r\n y[v] = 0.0\r\n mm[v] = m[[i for i in range(Codel * v, (v + 1) * Codel)]]\r\n for i in range(Codel):\r\n y[v] = y[v] + mm[v][i] * pow(5, Codel - (i + 1))\r\n x[v] = (uma[v] - umi[v]) * y[v] / (5 ** Codel) + umi[v]\r\n r[v] = x[v]\r\n Fi = eval(obj_function)(r, n)\r\n return Fi\r\n\r\nparser = argparse.ArgumentParser(description='Markov Decision Process Neural Network for Global Optimization')\r\n\r\nparser.add_argument('--obj_function', type=str, default='griewank')\r\nparser.add_argument('--Size', type=int, default=100)\r\nparser.add_argument('--G', type=int, default=100)\r\nparser.add_argument('--Codel', type=int, default=4)\r\nparser.add_argument('--umaxo', type=int, default=1000000)\r\nparser.add_argument('--umino', type=int, default=-1000000)\r\nparser.add_argument('--n', type=int, default=2)\r\nparser.add_argument('--Po', type=float, default=0.8)\r\n\r\nargs = parser.parse_args()\r\nobj_function = args.obj_function\r\nSize = args.Size\r\nG = args.G\r\nCodel = args.Codel\r\numaxo = args.umaxo\r\numino = args.umino\r\nn = args.n\r\nPo = args.Po\r\n\r\nmm = [[] for i in range(n)]\r\nmmb = [[] for i in range(n)]\r\nbfi = [None for _ in range(G)]\r\nBS = [None for _ in range(G)]\r\n\r\nQ = list([])\r\nEX = list([])\r\nEX1 = list([])\r\n\r\nfor i in range(5):\r\n Q.append(np.round(4 * np.random.rand(Size, n * Codel)))\r\n EX.append(np.round(4 * np.random.rand(Size, n * Codel)))\r\n EX1.append(np.round(4 * np.random.rand(Size, n * Codel)))\r\n\r\numax = [umaxo for i in range(n)]\r\numin = [umino for i in range(n)]\r\n\r\nconstant = 0\r\nfor i in range(Codel):\r\n constant = constant + n * (5 ^ i)\r\n\r\nax = []\r\nay = []\r\nplt.ion()\r\n\r\nfor k in range(G):\r\n\r\n F = [0 for s in range(15 * Size)]\r\n\r\n for i in range(Size):\r\n for j in range(Codel * n):\r\n for b in range(4):\r\n Q[b + 1][i, j] = (Q[b][i, j] + 1) % 5\r\n EX[b + 1][i, j] = (EX[b][i, j] + 1) % 5\r\n EX1[b + 1][i, j] = (EX1[b][i, j] + 1) % 5\r\n\r\n E = np.concatenate((Q, EX, EX1), axis=0)\r\n E = E.reshape(15 * Size, n * Codel)\r\n\r\n for s in range(15 * Size):\r\n m = E[s, :]\r\n F[s] = evaluation(m, n, Codel, umax, umin)\r\n\r\n fi = F\r\n Oderfi = sorted(fi)\r\n Indexfi = sorted(range(len(fi)), key=lambda x: fi[x])\r\n Oderfi1 = sorted(fi, reverse=True)\r\n Indexfi1 = sorted(range(len(fi)), key=lambda x: fi[x], reverse=True)\r\n Bestfitness = Oderfi[0]\r\n TempE = np.array([list(E[Indexfi[i]]) for i in range(Size)])\r\n TempE2 = np.array([list(E[Indexfi1[i]]) for i in range(Size)])\r\n TempE3 = np.array([list(E[Indexfi[i]]) for i in range(9 * Size, 10 * Size)])\r\n TempE3 = np.flipud(TempE3)\r\n BestS = TempE[0, :]\r\n bfi[k] = Bestfitness\r\n BS[k] = BestS\r\n\r\n TempE, umax, umin, TempE1, TempE2 = ChangeDomain(TempE, umax, umin, Size, Codel, n, Po, TempE3, TempE2)\r\n\r\n m = TempE[0, :]\r\n F1 = evaluation(m, n, Codel, umax, umin)\r\n\r\n for i in range(Size - 2):\r\n for j in range(n * Codel):\r\n if TempE[i, j] == TempE[i + 1, j] and TempE[i, j] != 4:\r\n TempE[i + 1, j] = TempE[i + 1, j] + 1\r\n elif TempE[i, j] == TempE[i + 1, j] and TempE[i, j] == 4:\r\n TempE[i + 1, j] = 0\r\n elif TempE[i, j] == TempE[i + 2, j] and TempE[i, j] != 4:\r\n TempE[i + 2, j] = TempE[i + 2, j] + 1\r\n elif TempE[i, j] == TempE[i + 2, j] and TempE[i, j] == 4:\r\n TempE[i + 2, j] = 0\r\n\r\n if TempE1[i, j] == TempE1[i + 1, j] and TempE1[i, j] != 0:\r\n TempE1[i + 1, j] = TempE1[i + 1, j] - 1\r\n elif TempE1[i, j] == TempE1[i + 1, j] and TempE1[i, j] == 0:\r\n TempE1[i + 1, j] = 4\r\n elif TempE1[i, j] == TempE1[i + 2, j] and TempE1[i, j] != 0:\r\n TempE1[i + 2, j] = TempE1[i + 2, j] - 1\r\n elif TempE1[i, j] == TempE1[i + 2, j] and TempE1[i, j] == 0:\r\n TempE1[i + 2, j] = 4\r\n\r\n if TempE2[i, j] == TempE2[i + 1, j] and TempE2[i, j] != 4:\r\n TempE2[i + 1, j] = TempE2[i + 1, j] + 1\r\n elif TempE2[i, j] == TempE2[i + 1, j] and TempE2[i, j] == 4:\r\n TempE2[i + 1, j] = 0\r\n elif TempE2[i, j] == TempE2[i + 2, j] and TempE2[i, j] != 4:\r\n TempE2[i + 2, j] = TempE2[i + 2, j] + 1\r\n elif TempE2[i, j] == TempE2[i + 2, j] and TempE2[i, j] == 4:\r\n TempE2[i + 2, j] = 0\r\n\r\n for i in range(Size - 1):\r\n for j in range(n * Codel):\r\n if TempE2[0, j] == TempE[i+1, j]:\r\n TempE[i+1, j] == TempE[0, j]\r\n if TempE2[0, j] == TempE1[i+1, j]:\r\n TempE1[i + 1, j] = TempE1[0, j]\r\n if TempE[0, j] == TempE2[i + 1, j]:\r\n TempE2[i + 1, j] = TempE2[0, j]\r\n\r\n TempE1[0, :] = np.round(4 * np.random.rand(1, n * Codel))\r\n\r\n for i in range(Size):\r\n for j in range(Codel * n):\r\n Q[0][i, j] = TempE[i, j]\r\n EX[0][i, j] = TempE1[i, j]\r\n EX1[0][i, j] = TempE2[i, j]\r\n\r\n yb = [0 for i in range(n)]\r\n variables = [0 for i in range(n)]\r\n\r\n for v in range(n):\r\n yb[v] = 0\r\n mmb[v] = m[[i for i in range(Codel * v, (v + 1) * Codel)]]\r\n for i in range(Codel):\r\n yb[v] = yb[v] + mm[v][i] * pow(5, Codel - (i + 1))\r\n variables[v] = (umax[v] - umin[v]) * yb[v] / (5 ** Codel) + umin[v]\r\n Fist = eval(obj_function)(variables, n)\r\n print('Bestfitness3', k, Fist, variables, m, umax, umin)\r\n ax.append(k)\r\n ay.append(Fist)\r\n plt.clf()\r\n if len(ax) > 20:\r\n plt.plot(ax[-20:-1], ay[-20:-1])\r\n else:\r\n plt.plot(ax, ay)\r\n plt.pause(0.1)\r\n plt.ioff()\r\n\r\n\r\n\r\n\r\n\r\n" ]
[ [ "numpy.concatenate", "matplotlib.pyplot.ion", "numpy.random.rand", "matplotlib.pyplot.plot", "numpy.diff", "numpy.flipud", "numpy.where", "matplotlib.pyplot.pause", "matplotlib.pyplot.ioff", "matplotlib.pyplot.clf" ] ]
U8NWXD/vivarium
[ "19c6a4096fe94e3342e40ce03e6708c24dd38fa3" ]
[ "vivarium/processes/membrane_potential.py" ]
[ "from __future__ import absolute_import, division, print_function\n\nimport os\n\nimport numpy as np\nimport scipy.constants as constants\nimport matplotlib.pyplot as plt\n\nfrom vivarium.core.process import Process\nfrom vivarium.library.dict_utils import deep_merge\nfrom vivarium.core.composition import (\n simulate_process_in_experiment,\n plot_simulation_output,\n PROCESS_OUT_DIR,\n)\n\n\nNAME = 'membrane_potential'\n\n# PMF ~170mV at pH 7. ~140mV at pH 7.7 (Berg)\n# Ecoli internal pH in range 7.6-7.8 (Berg)\n\n# (mmol) http://book.bionumbers.org/what-are-the-concentrations-of-different-ions-in-cells/\n# Schultz, Stanley G., and A. K. Solomon. \"Cation Transport in Escherichia coli\" (1961)\n# TODO -- add Mg2+, Ca2+\nDEFAULT_STATE = {\n 'internal': {\n 'K': 300, # (mmol) 30-300\n 'Na': 10, # (mmol) 10\n 'Cl': 10}, # (mmol) 10-200 media-dependent\n 'external': {\n 'K': 5,\n 'Na': 145,\n 'Cl': 110, # (mmol)\n 'T': 310.15}\n }\n\nDEFAULT_PARAMETERS = {\n 'p_K': 1, # unitless, relative membrane permeability of K\n 'p_Na': 0.05, # unitless, relative membrane permeability of Na\n 'p_Cl': 0.05, # unitless, relative membrane permeability of Cl\n }\n\nPERMEABILITY_MAP = {\n 'K': 'p_K',\n 'Na': 'p_Na',\n 'Cl': 'p_Cl'\n }\n\n# cation is positively charged, anion is negatively charged\nCHARGE_MAP = {\n 'K': 'cation',\n 'Na': 'cation',\n 'Cl': 'anion',\n 'PROTON': 'cation',\n }\n\nclass NoChargeError(Exception):\n pass\n\nclass MembranePotential(Process):\n '''\n Need to add a boot method for this process to vivarium/environment/boot.py for it to run on its own\n '''\n\n defaults = {\n 'initial_state': DEFAULT_STATE,\n 'parameters': DEFAULT_PARAMETERS,\n 'permeability': PERMEABILITY_MAP,\n 'charge': CHARGE_MAP,\n 'constants': {\n 'R': constants.gas_constant, # (J * K^-1 * mol^-1) gas constant\n 'F': constants.physical_constants['Faraday constant'][0], # (C * mol^-1) Faraday constant\n 'k': constants.Boltzmann, # (J * K^-1) Boltzmann constant\n }\n }\n\n def __init__(self, initial_parameters=None):\n if not initial_parameters:\n initial_parameters = {}\n\n self.initial_state = self.or_default(\n initial_parameters, 'initial_state')\n self.permeability = self.or_default(\n initial_parameters, 'permeability')\n self.charge = self.or_default(\n initial_parameters, 'charge')\n self.parameters = self.or_default(\n initial_parameters, 'parameters')\n self.parameters.update(self.defaults['constants'])\n\n super(MembranePotential, self).__init__(self.parameters)\n\n def ports_schema(self):\n ports = [\n 'internal',\n 'membrane',\n 'external',\n ]\n schema = {port: {} for port in ports}\n\n ## internal\n # internal ions and charge (c_in)\n for state in list(self.initial_state['internal'].keys()):\n schema['internal'][state] = {\n '_default': self.initial_state['internal'].get(state, 0.0),\n '_emit': True,\n }\n\n ## external\n # external ions, charge (c_out) and temperature (T)\n for state in list(self.initial_state['external'].keys()) + ['T']:\n schema['external'][state] = {\n '_default': self.initial_state['external'].get(state, 0.0),\n '_emit': True,\n }\n\n ## membrane\n # proton motive force (PMF), electrical difference (d_V), pH difference (d_pH)\n for state in ['PMF', 'd_V', 'd_pH']:\n schema['membrane'][state] = {\n '_updater': 'set',\n '_emit': True,\n }\n\n return schema\n\n def next_update(self, timestep, states):\n internal_state = states['internal']\n external_state = states['external']\n\n # parameters\n R = self.parameters['R']\n F = self.parameters['F']\n k = self.parameters['k']\n\n # state\n T = external_state['T'] # temperature\n # e = 1 # proton charge # TODO -- get proton charge from state\n\n # Membrane potential.\n numerator = 0\n denominator = 0\n for ion_id, p_ion_id in self.permeability.items():\n charge = self.charge[ion_id]\n p_ion = self.parameters[p_ion_id]\n\n # ions states\n internal = internal_state[ion_id]\n external = external_state[ion_id]\n\n if charge is 'cation':\n numerator += p_ion * external\n denominator += p_ion * internal\n elif charge is 'anion':\n numerator += p_ion * internal\n denominator += p_ion * external\n else:\n raise NoChargeError(\n \"No charge given for {}\".format(ion_id))\n\n # Goldman equation for membrane potential\n # expected d_V = -120 mV\n d_V = (R * T) / (F) * np.log(numerator / denominator) * 1e3 # (mV). 1e3 factor converts from V\n\n # Nernst equation for pH difference\n # -2.3 * k * T / e # -2.3 Boltzmann constant * temperature\n # expected d_pH = -50 mV\n d_pH = -50 # (mV) for cells grown at pH 7. (Berg, H. \"E. coli in motion\", pg 105)\n\n # proton motive force\n PMF = d_V + d_pH\n\n return {\n 'membrane': {\n 'd_V': d_V,\n 'd_pH': d_pH,\n 'PMF': PMF}}\n\ndef test_mem_potential():\n initial_parameters = {\n 'initial_state': DEFAULT_STATE,\n 'parameters': DEFAULT_PARAMETERS,\n 'permeability': PERMEABILITY_MAP,\n 'charge': CHARGE_MAP,\n }\n\n # configure process\n mp = MembranePotential(initial_parameters)\n timeline = [\n (0, {('external', 'Na'): 1}),\n (100, {('external', 'Na'): 2}),\n (500, {})]\n\n settings = {'timeline': {'timeline': timeline}}\n return simulate_process_in_experiment(mp, settings)\n\n\nif __name__ == '__main__':\n out_dir = os.path.join(PROCESS_OUT_DIR, NAME)\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n timeseries = test_mem_potential()\n settings = {\n 'remove_first_timestep': True\n }\n plot_simulation_output(timeseries, settings, out_dir)\n" ]
[ [ "numpy.log" ] ]
gp-wang/facenet_celeb
[ "6dba84d4d64951e6d27fe92d385bb5c290123088" ]
[ "src/classifier.py" ]
[ "\"\"\"An example of how to use your own dataset to train a classifier that recognizes people.\n\"\"\"\n# MIT License\n# \n# Copyright (c) 2016 David Sandberg\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport numpy as np\nimport argparse\nimport facenet\nimport os\nimport sys\nimport math\nimport pickle\nfrom sklearn.svm import SVC\nfrom pdb import set_trace as bp\n\ndef main(args):\n \n with tf.Graph().as_default():\n \n with tf.Session() as sess:\n \n np.random.seed(seed=args.seed)\n \n if args.use_split_dataset:\n dataset_tmp = facenet.get_dataset(args.data_dir)\n train_set, test_set = split_dataset(dataset_tmp, args.min_nrof_images_per_class, args.nrof_train_images_per_class)\n if (args.mode=='TRAIN'):\n dataset = train_set\n elif (args.mode=='CLASSIFY'):\n dataset = test_set\n else:\n dataset = facenet.get_dataset(args.data_dir)\n\n # Check that there are at least one training image per class\n for cls in dataset:\n assert(len(cls.image_paths)>0, 'There must be at least one image for each class in the dataset') \n\n \n paths, labels = facenet.get_image_paths_and_labels(dataset)\n \n print('Number of classes: %d' % len(dataset))\n print('Number of images: %d' % len(paths))\n \n # Load the model\n print('Loading feature extraction model')\n facenet.load_model(args.model)\n \n # Get input and output tensors\n images_placeholder = tf.get_default_graph().get_tensor_by_name(\"input:0\")\n embeddings = tf.get_default_graph().get_tensor_by_name(\"embeddings:0\")\n phase_train_placeholder = tf.get_default_graph().get_tensor_by_name(\"phase_train:0\")\n embedding_size = embeddings.get_shape()[1]\n \n # Run forward pass to calculate embeddings\n print('Calculating features for images')\n nrof_images = len(paths)\n nrof_batches_per_epoch = int(math.ceil(1.0*nrof_images / args.batch_size))\n emb_array = np.zeros((nrof_images, embedding_size))\n for i in range(nrof_batches_per_epoch):\n start_index = i*args.batch_size\n end_index = min((i+1)*args.batch_size, nrof_images)\n paths_batch = paths[start_index:end_index]\n images = facenet.load_data(paths_batch, False, False, args.image_size)\n feed_dict = { images_placeholder:images, phase_train_placeholder:False }\n emb_array[start_index:end_index,:] = sess.run(embeddings, feed_dict=feed_dict)\n \n classifier_filename_exp = os.path.expanduser(args.classifier_filename)\n\n if (args.mode=='TRAIN'):\n # Train classifier\n print('Training classifier')\n model = SVC(kernel='linear', probability=True)\n #bp()\n model.fit(emb_array, labels)\n \n # Create a list of class names\n class_names = [ cls.name.replace('_', ' ') for cls in dataset]\n\n # Saving classifier model\n with open(classifier_filename_exp, 'wb') as outfile:\n pickle.dump((model, class_names), outfile)\n print('Saved classifier model to file \"%s\"' % classifier_filename_exp)\n \n elif (args.mode=='CLASSIFY'):\n # Classify images\n print('Testing classifier')\n with open(classifier_filename_exp, 'rb') as infile:\n (model, class_names) = pickle.load(infile)\n\n print('Loaded classifier model from file \"%s\"' % classifier_filename_exp)\n\n predictions = model.predict_proba(emb_array)\n best_class_indices = np.argmax(predictions, axis=1)\n best_class_probabilities = predictions[np.arange(len(best_class_indices)), best_class_indices]\n \n for i in range(len(best_class_indices)):\n print('%4d %s: %.3f' % (i, class_names[best_class_indices[i]], best_class_probabilities[i]))\n \n accuracy = np.mean(np.equal(best_class_indices, labels))\n print('Accuracy: %.3f' % accuracy)\n \n \ndef split_dataset(dataset, min_nrof_images_per_class, nrof_train_images_per_class):\n train_set = []\n test_set = []\n for cls in dataset:\n paths = cls.image_paths\n # Remove classes with less than min_nrof_images_per_class\n if len(paths)>=min_nrof_images_per_class:\n np.random.shuffle(paths)\n train_set.append(facenet.ImageClass(cls.name, paths[:nrof_train_images_per_class]))\n test_set.append(facenet.ImageClass(cls.name, paths[nrof_train_images_per_class:]))\n return train_set, test_set\n\n \ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n \n parser.add_argument('mode', type=str, choices=['TRAIN', 'CLASSIFY'],\n help='Indicates if a new classifier should be trained or a classification ' + \n 'model should be used for classification', default='CLASSIFY')\n parser.add_argument('data_dir', type=str,\n help='Path to the data directory containing aligned LFW face patches.')\n parser.add_argument('model', type=str, \n help='Could be either a directory containing the meta_file and ckpt_file or a model protobuf (.pb) file')\n parser.add_argument('classifier_filename', \n help='Classifier model file name as a pickle (.pkl) file. ' + \n 'For training this is the output and for classification this is an input.')\n parser.add_argument('--use_split_dataset', \n help='Indicates that the dataset specified by data_dir should be split into a training and test set. ' + \n 'Otherwise a separate test set can be specified using the test_data_dir option.', action='store_true')\n parser.add_argument('--test_data_dir', type=str,\n help='Path to the test data directory containing aligned images used for testing.')\n parser.add_argument('--batch_size', type=int,\n help='Number of images to process in a batch.', default=90)\n parser.add_argument('--image_size', type=int,\n help='Image size (height, width) in pixels.', default=160)\n parser.add_argument('--seed', type=int,\n help='Random seed.', default=666)\n parser.add_argument('--min_nrof_images_per_class', type=int,\n help='Only include classes with at least this number of images in the dataset', default=20)\n parser.add_argument('--nrof_train_images_per_class', type=int,\n help='Use this number of images from each class for training and the rest for testing', default=10)\n \n return parser.parse_args(argv)\n\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))\n" ]
[ [ "numpy.equal", "numpy.zeros", "tensorflow.get_default_graph", "numpy.random.seed", "tensorflow.Graph", "tensorflow.Session", "numpy.random.shuffle", "sklearn.svm.SVC", "numpy.argmax" ] ]
yangchongxuan/100-Days-Of-ML-Code
[ "a2197066c07e9830859e20e057393ca2270af374" ]
[ ".history/Code/ycx/day_13 svm_20210303174904.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndataset = pd.read_csv('./datasets/Social_Network_Ads.csv')\n# X = \ndataset.info()" ]
[ [ "pandas.read_csv" ] ]
ceilors/some-games
[ "91685acfccbc62533bb61755af90add182cc13a6" ]
[ "1010.py" ]
[ "#!/usr/bin/env python3\nfrom itertools import product\nfrom pathlib import Path\nimport numpy as np\nimport pygame\nimport os\n\n\n# основные используемые цвета\nbackground_color = (100, 100, 100)\nlayout_color = (120, 120, 120)\nlighter_color = (150, 150, 150)\ntext_color = (200, 200, 200)\ncolors = {\n # игровое поле и шрифт\n 0: (170, 170, 170),\n # фигуры\n 1: (230, 100, 100),\n 2: (230, 210, 100),\n 3: (210, 230, 100),\n 4: (100, 230, 100),\n 5: (100, 230, 210),\n 6: (100, 210, 230),\n 7: (100, 100, 230),\n 8: (210, 100, 230),\n 9: (230, 100, 200)\n}\n\nfigures = [\n # коробки всех размеров\n np.array([[True] * 3, [True] * 3, [True] * 3]).T,\n np.array([[True, True], [True, True]]).T,\n np.array([[True]]).T,\n # # прямые линии\n np.array([[True] * 5]),\n np.array([[True] * 4]),\n np.array([[True] * 3]),\n np.array([[True] * 2]),\n # остальные фигуры\n np.array([[True, False, False], [True, False, False], [True, True, True]]),\n np.array([[True, False, False], [True, False, False], [True, True, False]]),\n np.array([[True, False], [True, True]]),\n]\n\n# сдвига начала координат\nshift_pos = (10, 10)\n# размер одного тайла\nTILE_SIZE = 32\n# сдвиги и пробелы между тайлами для отрисовки\nTILE_SHIFT = 8\nTILE_SKIP = 28\n# размер корзины для фигур\nMAX_BASKET_TILES = 5\n# количество ячеек в корзине для фигур\nMAX_BASKET_SIZE = 3\n# размер игровой доски\nBOARD_SIZE = 10\n\n# идентификаторы кнопок мыши в pygame\nLEFT_MOUSE = 1\nRIGHT_MOUSE = 3\n\n# координаты с корзинам с фигурами\nbasket_pos = [[x + shift_pos[0], TILE_SIZE * 11 + shift_pos[1]]\n for x in np.arange(0, 3 * MAX_BASKET_TILES * TILE_SIZE, TILE_SIZE * 6)]\n\n# автоматический размер окна\ngame_width = basket_pos[2][0] + (basket_pos[1][0] - basket_pos[0][0]) - shift_pos[0]\ngame_height = TILE_SIZE * (BOARD_SIZE + MAX_BASKET_TILES + 2) + shift_pos[1] - shift_pos[1]\n\n\n# gameover params\ngame_over_text = 'КОНЕЦ ИГРЫ'\ngmx, gmy = len(game_over_text) * 30, 48\ngmx_pos = ((game_width - gmx) // 2, (game_height - gmy) // 2)\nrect1 = (gmx_pos[0] - 10, gmx_pos[1], gmx + 15, gmy + 13)\nrect2 = (gmx_pos[0] - 5, gmx_pos[1] + 5, gmx + 5, gmy + 3)\n\n\ndef remove_zeros(arr):\n # находим строки и столбцы полностью пустые\n empty_cols, empty_rows = arr.sum(axis=0), arr.sum(axis=1)\n # и убираем их из текущей фигуры\n return arr[empty_rows != False, :][:, empty_cols != False]\n\n\ndef rotate(figure):\n # помещаем фигуру в квадрат side_size x side_size\n side_size = max(figure.shape)\n zeros = np.zeros((side_size, side_size), dtype=bool)\n zeros[:figure.shape[0], :figure.shape[1]] = figure\n figure = zeros\n # создаём новый массив повёрнутый на 90 градусов\n nf = np.empty(figure.shape, dtype=bool)\n for i in range(side_size):\n for j in range(side_size):\n nf[side_size - i - 1][j] = figure[j][i]\n return remove_zeros(nf)\n\n\ndef prepare_figures(figures):\n result = figures[:3]\n # генерируем все положения для линейных фигур (2 варианта)\n for figure in figures[3:][:4]:\n r_figure = rotate(figure)\n # INFO: не убирать .T (нужно для корректного отображения фигур)\n result += [remove_zeros(figure.T), r_figure.T]\n # генерируем угловые фигуры (4 варианта)\n for figure in figures[-3:]:\n # INFO: не убирать .T (нужно для корректного отображения фигур)\n result.append(remove_zeros(figure.T))\n for _ in range(3):\n figure = rotate(figure)\n result.append(figure.T)\n return result\n\n\ndef AAfilledRoundedRect(surface, rect, color, radius=0.2):\n \"\"\"\n surface : destination\n rect : rectangle\n color : rgb or rgba\n radius : 0 <= radius <= 1\n \"\"\"\n\n rect, color = pygame.Rect(rect), pygame.Color(*color)\n alpha = color.a\n color.a = 0\n pos = rect.topleft\n rect.topleft = 0, 0\n rectangle = pygame.Surface(rect.size, pygame.SRCALPHA)\n circle = pygame.Surface([min(rect.size) * 3] * 2, pygame.SRCALPHA)\n pygame.draw.ellipse(circle, (0, 0, 0), circle.get_rect(), 0)\n circle = pygame.transform.smoothscale(\n circle, [int(min(rect.size) * radius)] * 2)\n radius = rectangle.blit(circle, (0, 0))\n radius.bottomright = rect.bottomright\n rectangle.blit(circle, radius)\n radius.topright = rect.topright\n rectangle.blit(circle, radius)\n radius.bottomleft = rect.bottomleft\n rectangle.blit(circle, radius)\n rectangle.fill((0, 0, 0), rect.inflate(-radius.w, 0))\n rectangle.fill((0, 0, 0), rect.inflate(0, -radius.h))\n rectangle.fill(color, special_flags=pygame.BLEND_RGBA_MAX)\n rectangle.fill((255, 255, 255, alpha), special_flags=pygame.BLEND_RGBA_MIN)\n return surface.blit(rectangle, pos)\n\n\ndef draw_text(r, font, color, position, shift_y, text):\n xp, yp = position\n # режем строку на блоки\n for line in text.split('\\n'):\n # рисуем строку\n text = font.render(line, True, color)\n # переносим на отрисовочный слой\n r.blit(text, (xp, yp))\n # переводим указатель на новую строку\n yp += shift_y\n\n\nclass Board:\n def __init__(self, size_x=10, size_y=10):\n self.width = size_x\n self.height = size_y\n self.cells = np.zeros((size_y, size_y))\n\n def clear(self):\n self.cells = np.zeros((self.width, self.height))\n\n def set(self, pos, figure, color=1):\n width, height = len(figure), len(figure[0])\n x_pos, y_pos = pos[0], pos[1]\n for y in range(y_pos, y_pos + height):\n for x in range(x_pos, x_pos + width):\n if figure[x - x_pos][y - y_pos]:\n self.cells[y, x] = color * figure[x - x_pos][y - y_pos]\n\n def can_set(self, pos, figure):\n width, height = len(figure), len(figure[0])\n x_pos, y_pos = pos[0], pos[1]\n # проверка на выход из границ игрового поля\n pole_cond = x_pos >= 0 and x_pos + width <= self.width and\\\n y_pos >= 0 and y_pos + height <= self.height\n if not pole_cond:\n return False\n for y in range(y_pos, y_pos + height):\n for x in range(x_pos, x_pos + width):\n if self.cells[y, x] * figure[x - x_pos, y - y_pos] != 0:\n return False\n return True\n\n def draw(self, display):\n for j, row in enumerate(self.cells):\n for i, item in enumerate(row):\n rect = (shift_pos[0] + i * TILE_SIZE + TILE_SHIFT,\n shift_pos[1] + j * TILE_SIZE + TILE_SHIFT, TILE_SKIP, TILE_SKIP)\n AAfilledRoundedRect(display, rect, colors[item])\n\n def get_lines(self):\n items = []\n for row in self.cells:\n if np.all(row > 0):\n items.append(row)\n for col in self.cells.T:\n if np.all(col > 0):\n items.append(col)\n return items\n\n\nboard = Board(size_x=BOARD_SIZE, size_y=BOARD_SIZE)\nfigures = prepare_figures(figures)\n\n\nclass App:\n MAX_COUNTDOWN = 1\n GAME_FPS = 60\n\n def __init__(self, width=game_width, height=game_height):\n self.figure_drag = False\n self.figure_index = -1\n self.generate_figures()\n\n self.width = width\n self.height = height\n self._running = True\n self._display_surf = None\n self.game_over = False\n self.clock = pygame.time.Clock()\n self.cwd = Path(os.path.dirname(os.path.abspath(__file__)))\n\n self.remove_animation = False\n self.remove_countdown = App.MAX_COUNTDOWN\n\n self.game_score = 0\n self.score_file = self.cwd / 'gamescore.txt'\n game_score_value = 0\n if self.score_file.exists():\n try:\n game_score_value = int(self.score_file.open('r').read())\n except ValueError:\n pass\n self.game_highscore = game_score_value\n self.lines = None\n\n def generate_figures(self):\n self.basket_figures = np.random.choice(figures, size=MAX_BASKET_SIZE)\n self.basket_colors = np.random.randint(1, len(colors), size=MAX_BASKET_SIZE)\n self.basket_count = 0\n\n def on_init(self):\n pygame.init()\n pygame.display.set_caption('1010')\n self._display_surf = pygame.display.set_mode((self.width, self.height), pygame.HWSURFACE)\n self._running = True\n\n path_to_font = str(self.cwd / 'resources' / 'FiraMono-Regular.ttf')\n self.font = pygame.font.Font(path_to_font, 20)\n self.bigfont = pygame.font.Font(path_to_font, 48)\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self._running = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n self._running = False\n if self.remove_animation:\n return\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == LEFT_MOUSE:\n x, y = pygame.mouse.get_pos()\n if not self.figure_drag and y >= basket_pos[0][1]:\n self.figure_index = x // (game_width // MAX_BASKET_SIZE)\n self.figure_drag = True\n elif self.figure_drag:\n # проверка на вхождения xy в границы игрового поля\n figure_in = x > shift_pos[0] and x < (shift_pos[0] + TILE_SIZE * board.width) and\\\n y > shift_pos[1] and y < (shift_pos[1] + TILE_SIZE * board.height)\n if figure_in:\n index_x = int(np.ceil((x - shift_pos[0] + TILE_SHIFT) / TILE_SIZE) - 1)\n index_y = int(np.ceil((y - shift_pos[1] + TILE_SHIFT) / TILE_SIZE) - 1)\n # можно ли установить фигуру на поле\n if board.can_set((index_x, index_y), self.basket_figures[self.figure_index]):\n self.game_score += int(self.basket_figures[self.figure_index].sum())\n board.set(\n (index_x, index_y),\n self.basket_figures[self.figure_index],\n color=self.basket_colors[self.figure_index])\n # удаляем фигуру из ячейки корзины\n self.basket_figures[self.figure_index] = np.array([[]])\n self.basket_count += 1\n # генерируем новые фигуры, если корзина пуста\n if self.basket_count == MAX_BASKET_SIZE:\n self.generate_figures()\n self.figure_drag = False\n self.figure_index = -1\n if self.game_over:\n board.clear()\n self.generate_figures()\n self.game_highscore = max(self.game_score, self.game_highscore)\n self.save_game_score()\n self.game_over = False\n self.game_score = 0\n\n def on_loop(self):\n if not self.remove_animation:\n # помещение блоков для анимации\n items = board.get_lines()\n if len(items) > 0:\n self.lines = items\n self.remove_animation = True\n if not self.game_over and not self.remove_animation:\n # проверка игры на проигрыш\n figure_cant_set = True\n for figure in self.basket_figures:\n if not figure_cant_set:\n break\n if figure.sum() == 0:\n continue\n for x, y in product(range(board.width), range(board.height)):\n if board.can_set((x, y), figure):\n figure_cant_set = False\n break\n if figure_cant_set:\n self.game_over = True\n else:\n # реализация анимации удаления заполенной полосы\n if self.remove_countdown == 0:\n all_clear = True\n for item in self.lines:\n if item.sum() > 0:\n all_clear = False\n item[item.astype('bool').argmax()] = 0\n self.game_score += 1\n if all_clear:\n self.remove_animation = False\n self.lines = None\n self.remove_countdown = App.MAX_COUNTDOWN\n else:\n self.remove_countdown -= 1\n self.game_highscore = max(self.game_score, self.game_highscore)\n\n def on_render(self):\n # рисование подложки\n pygame.draw.rect(self._display_surf, background_color, (0, 0, self.width, self.height))\n\n # рисование основого игрового поля\n board.draw(self._display_surf)\n\n # рисование подложки для фигур\n for k in range(MAX_BASKET_SIZE):\n for j in range(MAX_BASKET_TILES):\n for i in range(MAX_BASKET_TILES):\n rect = [shift_pos[0], shift_pos[1], TILE_SKIP, TILE_SKIP]\n rect[0] += k * TILE_SIZE * (MAX_BASKET_TILES + 1) + i * TILE_SIZE + TILE_SHIFT\n rect[1] += (board.height + 1) * TILE_SIZE + j * TILE_SIZE + TILE_SHIFT\n AAfilledRoundedRect(self._display_surf, rect, layout_color)\n\n # рисование фигура в корзинах\n for index, (x, y) in enumerate(basket_pos):\n if index == self.figure_index:\n x, y = pygame.mouse.get_pos()\n x -= TILE_SIZE // 2\n y -= TILE_SIZE // 2\n for j, row in enumerate(self.basket_figures[index].T):\n for i, item in enumerate(row):\n if item > 0:\n rect = (x + i * TILE_SIZE + TILE_SHIFT, y + j *\n TILE_SIZE + TILE_SHIFT, TILE_SKIP, TILE_SKIP)\n AAfilledRoundedRect(\n self._display_surf, rect, colors[self.basket_colors[index]])\n\n # вывод игровых очков\n text_pos = (TILE_SIZE * (board.width + 1), shift_pos[1] + 1)\n render_text = f'набранный рекорд\\n{self.game_highscore}\\nтекущий счёт\\n{self.game_score}'\n draw_text(self._display_surf, self.font, text_color, text_pos, 30, render_text)\n if self.game_over:\n AAfilledRoundedRect(self._display_surf, rect1, colors[1], 0.2)\n AAfilledRoundedRect(self._display_surf, rect2, layout_color, 0.2)\n draw_text(self._display_surf, self.bigfont, text_color, gmx_pos, 0, game_over_text)\n\n pygame.display.flip()\n\n def save_game_score(self):\n self.score_file.open('w').write(str(self.game_highscore))\n\n def on_cleanup(self):\n pygame.quit()\n\n def on_execute(self):\n if self.on_init() is False:\n self._running = False\n while self._running:\n for event in pygame.event.get():\n self.on_event(event)\n self.on_loop()\n self.on_render()\n self.clock.tick(App.GAME_FPS)\n self.save_game_score()\n self.on_cleanup()\n\n\nif __name__ == '__main__':\n app = App()\n app.on_execute()\n" ]
[ [ "numpy.array", "numpy.ceil", "numpy.empty", "numpy.random.choice", "numpy.zeros", "numpy.arange", "numpy.all" ] ]
supriya-gdptl/vnn-neural-implicits
[ "34118fac8ccc530c539693381120dbfedf2bc0f8" ]
[ "im2mesh/encoder/vnn2.py" ]
[ "import torch\nimport torch.nn as nn\nfrom im2mesh.layers_equi import *\n\n\ndef maxpool(x, dim=-1, keepdim=False):\n out, _ = x.max(dim=dim, keepdim=keepdim)\n return out\n\n\ndef meanpool(x, dim=-1, keepdim=False):\n out = x.mean(dim=dim, keepdim=keepdim)\n return out\n\n\nclass VNN_DGCNN(nn.Module):\n def __init__(self, c_dim=128, dim=3, hidden_dim=128, k=10, meta_output=None):\n super(VNN_DGCNN, self).__init__()\n self.c_dim = c_dim\n self.k = k\n self.meta_output = meta_output\n \n self.conv_pos = VNLinearLeakyReLU(2, hidden_dim, use_batchnorm=True)\n self.conv_0 = VNLinearLeakyReLU(hidden_dim*2, hidden_dim, use_batchnorm=True)\n self.conv_1 = VNLinearLeakyReLU(hidden_dim*2, hidden_dim, use_batchnorm=True)\n self.conv_2 = VNLinearLeakyReLU(hidden_dim*2, hidden_dim, use_batchnorm=True)\n self.conv_3 = VNLinearLeakyReLU(hidden_dim*2, hidden_dim, use_batchnorm=True)\n \n self.conv_c = VNLinearLeakyReLU(hidden_dim*4, c_dim, dim=4, use_batchnorm=True)\n \n self.pool = meanpool\n self.pool_global = VNMaxPool(c_dim)\n \n if meta_output == 'invariant_latent':\n self.std_feature = VNStdFeature(c_dim, dim=3, normalize_frame=False, use_batchnorm=True)\n elif meta_output == 'invariant_latent_linear':\n self.std_feature = VNStdFeature(c_dim, dim=3, normalize_frame=False, use_batchnorm=True)\n self.vn_inv = VNLinear(c_dim, 3)\n\n def forward(self, x):\n batch_size = x.size(0)\n x = x.unsqueeze(1).transpose(2, 3)\n \n x = get_graph_feature(x, k=self.k)\n x = self.conv_pos(x)\n x = self.pool(x)\n \n x = get_graph_feature(x, k=self.k)\n x = self.conv_0(x)\n x_0 = self.pool(x)\n \n x = get_graph_feature(x_0, k=self.k)\n x = self.conv_1(x)\n x_1 = self.pool(x)\n \n x = get_graph_feature(x_1, k=self.k)\n x = self.conv_2(x)\n x_2 = self.pool(x)\n \n x = get_graph_feature(x_2, k=self.k)\n x = self.conv_3(x)\n x_3 = self.pool(x)\n \n x = torch.cat((x_0, x_1, x_2, x_3), dim=1)\n x = self.conv_c(x)\n c = self.pool_global(x)\n \n if self.meta_output == 'invariant_latent':\n c_std, z0 = self.std_feature(c)\n return c, c_std\n elif self.meta_output == 'invariant_latent_linear':\n c_std, z0 = self.std_feature(c)\n c_std = self.vn_inv(c_std)\n return c, c_std\n \n return c\n\n\nclass VNN_SimplePointnet(nn.Module):\n ''' DGCNN-based VNN encoder network.\n\n Args:\n c_dim (int): dimension of latent code c\n dim (int): input points dimension\n hidden_dim (int): hidden dimension of the network\n '''\n\n def __init__(self, c_dim=128, dim=3, hidden_dim=128, k=20, meta_output=None):\n super().__init__()\n self.c_dim = c_dim\n self.k = k\n self.meta_output = meta_output\n \n self.conv_pos = VNLinearLeakyReLU(3, 64, negative_slope=0.0, use_batchnorm=False)\n self.fc_pos = VNLinear(64, 2*hidden_dim)\n self.fc_0 = VNLinear(2*hidden_dim, hidden_dim)\n self.fc_1 = VNLinear(2*hidden_dim, hidden_dim)\n self.fc_2 = VNLinear(2*hidden_dim, hidden_dim)\n self.fc_3 = VNLinear(2*hidden_dim, hidden_dim)\n self.fc_c = VNLinear(hidden_dim, c_dim)\n \n \n self.actvn_0 = VNLeakyReLU(2*hidden_dim, negative_slope=0.0)\n self.actvn_1 = VNLeakyReLU(2*hidden_dim, negative_slope=0.0)\n self.actvn_2 = VNLeakyReLU(2*hidden_dim, negative_slope=0.0)\n self.actvn_3 = VNLeakyReLU(2*hidden_dim, negative_slope=0.0)\n self.actvn_c = VNLeakyReLU(hidden_dim, negative_slope=0.0)\n \n self.pool = meanpool\n \n if meta_output == 'invariant_latent':\n self.std_feature = VNStdFeature(c_dim, dim=3, normalize_frame=False, use_batchnorm=False)\n elif meta_output == 'invariant_latent_linear':\n self.std_feature = VNStdFeature(c_dim, dim=3, normalize_frame=False, use_batchnorm=False)\n self.vn_inv = VNLinear(c_dim, 3)\n \n def forward(self, p):\n batch_size = p.size(0)\n '''\n p_trans = p.unsqueeze(1).transpose(2, 3)\n \n #net = get_graph_feature(p_trans, k=self.k)\n #net = self.conv_pos(net)\n #net = net.mean(dim=-1, keepdim=False)\n #net = torch.cat([net, p_trans], dim=1)\n \n net = p_trans\n aggr = p_trans.mean(dim=-1, keepdim=True).expand(net.size())\n net = torch.cat([net, aggr], dim=1)\n '''\n p = p.unsqueeze(1).transpose(2, 3)\n #mean = get_graph_mean(p, k=self.k)\n #mean = p_trans.mean(dim=-1, keepdim=True).expand(p_trans.size())\n feat = get_graph_feature_cross(p, k=self.k)\n net = self.conv_pos(feat)\n net = self.pool(net, dim=-1)\n \n net = self.fc_pos(net)\n \n net = self.fc_0(self.actvn_0(net))\n pooled = self.pool(net, dim=-1, keepdim=True).expand(net.size())\n net = torch.cat([net, pooled], dim=1)\n \n net = self.fc_1(self.actvn_1(net))\n pooled = self.pool(net, dim=-1, keepdim=True).expand(net.size())\n net = torch.cat([net, pooled], dim=1)\n\n net = self.fc_2(self.actvn_2(net))\n pooled = self.pool(net, dim=-1, keepdim=True).expand(net.size())\n net = torch.cat([net, pooled], dim=1)\n \n net = self.fc_3(self.actvn_3(net))\n \n net = self.pool(net, dim=-1)\n\n c = self.fc_c(self.actvn_c(net))\n \n if self.meta_output == 'invariant_latent':\n c_std, z0 = self.std_feature(c)\n return c, c_std\n elif self.meta_output == 'invariant_latent_linear':\n c_std, z0 = self.std_feature(c)\n c_std = self.vn_inv(c_std)\n return c, c_std\n\n return c\n\n\nclass VNN_ResnetPointnet(nn.Module):\n ''' DGCNN-based VNN encoder network with ResNet blocks.\n\n Args:\n c_dim (int): dimension of latent code c\n dim (int): input points dimension\n hidden_dim (int): hidden dimension of the network\n '''\n\n def __init__(self, c_dim=128, dim=3, hidden_dim=128, k=20, meta_output=None):\n super().__init__()\n self.c_dim = c_dim\n self.k = k\n self.meta_output = meta_output\n\n self.conv_pos = VNLinearLeakyReLU(3, 64, negative_slope=0.0, use_batchnorm=False)\n self.fc_pos = VNLinear(64, 2*hidden_dim)\n self.block_0 = VNResnetBlockFC(2*hidden_dim, hidden_dim)\n self.block_1 = VNResnetBlockFC(2*hidden_dim, hidden_dim)\n self.block_2 = VNResnetBlockFC(2*hidden_dim, hidden_dim)\n self.block_3 = VNResnetBlockFC(2*hidden_dim, hidden_dim)\n self.block_4 = VNResnetBlockFC(2*hidden_dim, hidden_dim)\n self.fc_c = VNLinear(hidden_dim, c_dim)\n\n self.actvn_c = VNLeakyReLU(hidden_dim, negative_slope=0.0, share_nonlinearity=False)\n \n self.pool_pos = VNMaxPool(64)\n self.pool_0 = VNMaxPool(hidden_dim)\n self.pool_1 = VNMaxPool(hidden_dim)\n self.pool_2 = VNMaxPool(hidden_dim)\n self.pool_3 = VNMaxPool(hidden_dim)\n self.pool_4 = VNMaxPool(hidden_dim)\n \n if meta_output == 'invariant_latent':\n self.std_feature = VNStdFeature(c_dim, dim=3, normalize_frame=False, use_batchnorm=False)\n elif meta_output == 'invariant_latent_linear':\n self.std_feature = VNStdFeature(c_dim, dim=3, normalize_frame=False, use_batchnorm=False)\n self.vn_inv = VNLinear(c_dim, 3)\n\n def forward(self, p):\n batch_size = p.size(0)\n p = p.unsqueeze(1).transpose(2, 3)\n feat = get_graph_feature_cross(p, k=self.k)\n net = self.conv_pos(feat)\n net = self.pool_pos(net)\n \n net = self.fc_pos(net)\n \n net = self.block_0(net)\n pooled = self.pool_0(net).unsqueeze(-1).expand(net.size())\n net = torch.cat([net, pooled], dim=1)\n \n net = self.block_1(net)\n pooled = self.pool_1(net).unsqueeze(-1).expand(net.size())\n net = torch.cat([net, pooled], dim=1)\n \n net = self.block_2(net)\n pooled = self.pool_2(net).unsqueeze(-1).expand(net.size())\n net = torch.cat([net, pooled], dim=1)\n \n net = self.block_3(net)\n pooled = self.pool_3(net).unsqueeze(-1).expand(net.size())\n net = torch.cat([net, pooled], dim=1)\n\n net = self.block_4(net)\n\n # Recude to B x F\n net = self.pool_4(net)\n\n c = self.fc_c(self.actvn_c(net))\n \n if self.meta_output == 'invariant_latent':\n c_std, z0 = self.std_feature(c)\n return c, c_std\n elif self.meta_output == 'invariant_latent_linear':\n c_std, z0 = self.std_feature(c)\n c_std = self.vn_inv(c_std)\n return c, c_std\n\n return c\n" ]
[ [ "torch.cat" ] ]
mb-89/dfana
[ "b21efccdd34eb7fb175e4721a810e04f813e5826" ]
[ "src/dfana/pyqtgraphbackend/fftplt.py" ]
[ "from dfana.sharedfuns import getFixedLenString\nfrom scipy import fft\nimport numpy as np\n\nname = \"fft\"\niconName = \"fft\"\n\n\nclass PltHandler:\n def __init__(self, data, dst):\n self.data = data\n self.dst = dst\n\n def initialize(self):\n plt = self.dst\n src = self.data[\"datasrc\"]\n xname = \"ℱ{\" + src.axes[\"bottom\"][\"item\"].label.toPlainText().strip() + \"}\"\n plt.setLabel(\"bottom\", xname)\n plt.setTitle(\"FFT\")\n plt.customlegend.layout.itemAt(1, 1).setText(xname)\n srccurves = src.curves\n L = len(srccurves)\n for idx, cu in enumerate(srccurves):\n plt.plot(x=[0, 1], y=[0, 1], name=cu.name(), pen=(idx + 1, L))\n\n def updateData(self, reg):\n x0, x1 = reg\n plt = self.dst\n src = self.data[\"datasrc\"]\n xname = src.axes[\"bottom\"][\"item\"].label.toPlainText()\n s0 = getFixedLenString(x0)\n s1 = getFixedLenString(x1)\n plt.setTitle(f\"FFT on {xname}: {s0} -- {s1}\")\n\n for idx, curve in enumerate(src.curves):\n x = curve.xData\n y = curve.yData\n mask = np.logical_and(x >= x0, x <= x1)\n x = x[mask]\n y = y[mask]\n N = len(x)\n try:\n T = (x[-1] - x[0]) / N\n except IndexError:\n continue\n yf = 2.0 / N * np.abs(fft.fft(y)[0 : N // 2])\n xf = np.linspace(0.0, 1.0 / (2.0 * T), N // 2)\n plt.curves[idx].setData(x=xf[1:], y=yf[1:])\n" ]
[ [ "numpy.linspace", "scipy.fft.fft", "numpy.logical_and" ] ]
at-peter/epymarl
[ "e84ee56f435e6fe69e9bb3297256a326f65b3b1f" ]
[ "src/utils/logging.py" ]
[ "from collections import defaultdict\nimport logging\nimport numpy as np\nfrom torch import is_tensor\n\nclass Logger:\n def __init__(self, console_logger):\n self.console_logger = console_logger\n\n self.use_tb = False\n self.use_sacred = False\n self.use_hdf = False\n\n self.stats = defaultdict(lambda: [])\n\n def setup_tb(self, directory_name):\n # Import here so it doesn't have to be installed if you don't use it\n from tensorboard_logger import configure, log_value\n configure(directory_name)\n self.tb_logger = log_value\n self.use_tb = True\n\n def setup_sacred(self, sacred_run_dict):\n self._run_obj = sacred_run_dict\n self.sacred_info = sacred_run_dict.info\n self.use_sacred = True\n\n def log_stat(self, key, value, t, to_sacred=True):\n if is_tensor(value):\n value = value.item()\n self.stats[key].append((t, value))\n\n if self.use_tb:\n self.tb_logger(key, value, t)\n\n if self.use_sacred and to_sacred:\n if key in self.sacred_info:\n self.sacred_info[\"{}_T\".format(key)].append(t)\n self.sacred_info[key].append(value)\n else:\n self.sacred_info[\"{}_T\".format(key)] = [t]\n self.sacred_info[key] = [value]\n \n self._run_obj.log_scalar(key, value, t)\n\n def print_recent_stats(self):\n log_str = \"Recent Stats | t_env: {:>10} | Episode: {:>8}\\n\".format(*self.stats[\"episode\"][-1])\n i = 0\n for (k, v) in sorted(self.stats.items()):\n if k == \"episode\":\n continue\n i += 1\n window = 5 if k != \"epsilon\" else 1\n try:\n item = \"{:.4f}\".format(np.mean([x[1] for x in self.stats[k][-window:]]))\n except:\n item = \"{:.4f}\".format(np.mean([x[1].item() for x in self.stats[k][-window:]]))\n log_str += \"{:<25}{:>8}\".format(k + \":\", item)\n log_str += \"\\n\" if i % 4 == 0 else \"\\t\"\n self.console_logger.info(log_str)\n\n\n# set up a custom logger\ndef get_logger():\n logger = logging.getLogger()\n logger.handlers = []\n ch = logging.StreamHandler()\n formatter = logging.Formatter('[%(levelname)s %(asctime)s] %(name)s %(message)s', '%H:%M:%S')\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n logger.setLevel('DEBUG')\n\n return logger\n\n" ]
[ [ "torch.is_tensor", "numpy.mean" ] ]
statphysandml/LatticeModelImplementations
[ "5cadb44679445d821cc3d88646215d82d71e920c" ]
[ "python_scripts/on_model_measures.py" ]
[ "import numpy as np\n\n\nfrom mcmctools.utils.lattice import get_neighbour_index\n\n\ndef compute_on_model_measures(data, measure_name, sim_params):\n if measure_name == \"TwoPointCorrelation\":\n return compute_two_point_correlation(data, sim_params)\n\n\ndef compute_two_point_correlation(data, sim_params):\n dimensions = sim_params[\"systembase_params\"][\"dimensions\"]\n dim_mul = np.cumprod([1] + dimensions)\n lattice_configs = data[\"Config\"].values\n elem_per_site = 1\n n_sites = np.size(lattice_configs, axis=1)\n\n two_point_correlation = np.zeros(len(data))\n N = int(n_sites / np.prod(dimensions))\n\n # Using translation symmetry\n for site in range(n_sites):\n # Using rotation symmetry\n for dim in range(len(dimensions)):\n neighbour = get_neighbour_index(n=site, dim=dim, direction=True, mu=0, dimensions=dimensions, dim_mul=dim_mul,\n elem_per_site=elem_per_site)\n # Using symmetries in exchanging two components of the n-vector\n two_point_correlation += np.sum(lattice_configs[:, site * N:(site + 1) * N] * lattice_configs[:, neighbour * N:(neighbour + 1) * N], axis=1)\n\n data.insert(len(data.columns), \"TwoPointCorrelation\", two_point_correlation / (N * n_sites * len(dimensions)))\n\n return [\"TwoPointCorrelation\"], data\n\n" ]
[ [ "numpy.sum", "numpy.prod", "numpy.cumprod", "numpy.size" ] ]
SebastianWolf-SAP/data-synthesis-for-machine-learning
[ "b622739776cedf57a906d7304a96aa31f767340c" ]
[ "tests/test_attribute.py" ]
[ "\n\nfrom math import isclose\n\nfrom numpy import random, array_equal\nfrom pandas import Series\nfrom ds4ml.attribute import Attribute\nfrom ds4ml.utils import randomize_string\n\nsize = 30\n\n\ndef test_integer_attribute():\n ints = random.randint(1, 100, size)\n attr = Attribute(Series(ints), name='ID', categorical=False)\n assert attr.type == 'integer'\n assert attr.name == 'ID'\n assert attr.min_ >= 1\n assert attr.max_ <= 100\n assert len(attr.bins) == 20\n assert isclose(sum(attr.prs), 1.0)\n\n from .testdata import adults01\n attr = Attribute(adults01['age'])\n assert attr.type == 'integer'\n\n\ndef test_float_attribute():\n floats = random.uniform(1, 100, size)\n attr = Attribute(Series(floats, name='Float'))\n assert attr.type == 'float'\n assert attr.min_ >= 1\n assert attr.max_ <= 100\n assert len(attr.bins) == 20\n assert isclose(sum(attr.prs), 1.0)\n\n\ndef test_string_attribute():\n strings = list(map(lambda x: randomize_string(5), range(size)))\n attr = Attribute(Series(strings, name='String'), categorical=True)\n assert attr.type == 'string'\n assert attr.min_ == 5\n assert attr.categorical\n\n\ndef test_set_domain_for_integer_attribute():\n ints = random.randint(1, 100, size)\n attr = Attribute(Series(ints, name='Integer'))\n assert attr.min_ >= 1\n assert attr.max_ <= 100\n attr.domain = [-2, 120]\n assert attr.min_ == -2\n assert attr.max_ == 120\n\n\ndef test_set_domain_for_integer_categorical_attribute():\n ints = random.randint(1, 100, size)\n attr = Attribute(Series(ints, name='Integer'), categorical=True)\n assert attr.bins[0] >= 1\n assert attr.bins[-1] <= 100\n attr.domain = [-2, 120]\n assert attr.bins[0] == -2\n assert attr.bins[-1] == 120\n\n\ndef test_set_domain_for_float_attribute():\n floats = random.uniform(1, 100, size)\n attr = Attribute(Series(floats, name='Float'))\n assert attr.min_ >= 1\n assert attr.max_ <= 100\n attr.domain = [-2, 120]\n assert attr.min_ == -2\n assert attr.max_ == 120\n\n\ndef test_set_domain_for_string_attribute():\n strings = list(map(lambda x: randomize_string(5), range(size)))\n attr = Attribute(Series(strings, name='String'), categorical=True)\n bins = attr.bins\n attr.domain = ['a', 'b', 'China', 'USA']\n assert len(bins) + 4 == len(attr.bins)\n\n\ndef test_set_domain_for_datetime_attribute():\n dates = ['05/29/1988', '06/22/1988', '07/30/1992', '07/30/1992',\n '11/12/2000', '01/02/2001', '01/02/2001', '12/03/2001',\n '07/09/2002', '10/22/2002']\n attr = Attribute(Series(dates, name='String'), categorical=True)\n bins = attr.bins\n attr.domain = ['07/01/1997', '12/20/1999', '01/01/2004']\n assert len(bins) + 3 == len(attr.bins)\n\n\ndef test_counts_numerical_attribute():\n ints = random.randint(1, 100, size)\n attr = Attribute(Series(ints, name='Integer'))\n counts = attr.counts(normalize=False)\n assert sum(counts) == 30\n assert len(counts) == 20\n counts = attr.counts(bins=[0, 10, 20, 30, 100], normalize=False)\n assert sum(counts) == 30\n assert len(counts) == 4\n\n # categorical ints\n attr = Attribute(Series([1, 10, 11, 10, 20, 15, 16, 25], name='Integer'),\n categorical=True)\n counts = attr.counts(normalize=False)\n assert sum(counts) == 8\n assert len(counts) == 7\n counts = attr.counts(bins=[5, 10, 15], normalize=False)\n assert sum(counts) == 3\n assert len(counts) == 3\n\n\ndef test_decimals_float_attribute():\n floats = map(lambda v: round(v, 2), random.uniform(1, 10, size))\n attr = Attribute(Series(floats, name='Float'))\n assert attr.decimals() == 2\n\n\ndef test_counts_datetimes():\n dates = ['05/29/1988', '06/22/1988', '07/30/1992', '07/30/1992',\n '11/12/2000', '01/02/2001', '01/02/2001', '12/03/2001',\n '07/09/2002', '10/22/2002']\n attr = Attribute(Series(dates, name='DateTime'), categorical=True)\n counts = attr.counts(normalize=False)\n assert sum(counts) == len(dates)\n assert array_equal(counts, [1, 1, 2, 1, 2, 1, 1, 1])\n\n counts = attr.counts(bins=['12/03/2001', '10/22/2002'], normalize=False)\n assert array_equal(counts, [1, 1])\n\n\ndef test_counts_categorical_attribute():\n ints = random.randint(1, 10, size)\n attr = Attribute(Series(ints, name='Integer'), categorical=True)\n assert sum(attr.counts()) == 30\n\n\ndef test_choice_integers():\n ints = random.randint(1, 100, size)\n attr = Attribute(Series(ints, name='Integer'))\n assert len(attr.bins) == 20\n choices = attr.choice()\n assert len(choices) == size\n\n\ndef test_choice_floats():\n floats = random.uniform(1, 10, size)\n attr = Attribute(Series(floats, name='Float'))\n assert len(attr.bins) == 20\n choices = attr.choice()\n assert len(choices) == size\n\n\ndef test_choice_strings():\n strings = list(map(lambda x: randomize_string(5), range(size)))\n attr = Attribute(Series(strings, name='String'))\n choices = attr.choice()\n assert len(choices) == size\n\n\ndef test_choice_datetimes():\n dates = ['05/29/1988', '06/22/1988', '07/30/1992', '01/02/2001',\n '11/12/2000', '07/09/2002', '08/30/1998', '06/03/1997',\n '10/22/2002', '12/03/2001']\n attr = Attribute(Series(dates, name='DateTime'))\n choices = attr.choice()\n assert len(choices) == len(dates)\n\n\ndef test_bin_indexes_ints():\n ints = [3, 5, 7, 8, 7, 1, 10, 30, 16, 19]\n attr = Attribute(Series(ints), name='ID', categorical=False)\n indexes = attr.bin_indexes()\n assert len(indexes) == len(ints)\n\n\ndef test_bin_indexes_datetimes():\n dates = ['05/29/1988', '06/22/1988', '07/30/1992', '07/30/1992',\n '11/12/2000', '01/02/2001', '01/02/2001', '12/03/2001',\n '07/09/2002', '10/22/2002']\n attr = Attribute(Series(dates, name='DateTime'))\n indexes = attr.bin_indexes()\n assert len(indexes) == len(dates)\n\n\ndef test_pseudonymize_strings():\n strings = Series(['Abc', 'edf', 'Abc', 'take', '中国', 'edf', 'Abc'])\n attr = Attribute(strings, name='String')\n pseudonyms = attr.pseudonymize()\n assert array_equal(strings.value_counts().values,\n pseudonyms.value_counts().values)\n\n\ndef test_pseudonymize_ints():\n ints = Series([11, 2, 3, 4, 5, 4, 3, 2, 3, 4, 11])\n attr = Attribute(ints, name='Integer')\n pseudonyms = attr.pseudonymize()\n assert array_equal(ints.value_counts().values,\n pseudonyms.value_counts().values)\n\n\ndef test_pseudonymize_floats():\n floats = Series([11.5, 2.6, 3.0, 4.3, 5, 4.3, 3.0, 2.6, 3.0, 4.3, 11.6])\n attr = Attribute(floats, name='Float')\n pseudonyms = attr.pseudonymize()\n assert array_equal(floats.value_counts().values,\n pseudonyms.value_counts().values)\n\n\ndef test_pseudonym_dates():\n ints = Series(['07/15/2019', '07/24/2019', '07/23/2019', '07/22/2019',\n '07/21/2019', '07/22/2019', '07/23/2019', '07/24/2019',\n '07/23/2019', '07/22/2019', '07/15/2019'])\n attr = Attribute(ints, name='Date')\n pseudonyms = attr.pseudonymize()\n assert array_equal(ints.value_counts().values,\n pseudonyms.value_counts().values)\n\n\ndef test_random_ints():\n ints = [3, 5, 7, 8, 7, 1, 10, 30, 16, 19]\n attr = Attribute(ints, name='Integer')\n randoms = attr.random()\n assert len(randoms) == len(ints)\n\n\ndef test_random_datetimes():\n datetimes = ['07/15/2019', '07/24/2019', '07/23/2019', '07/22/2019',\n '07/21/2019', '07/22/2019', '07/23/2019', '07/24/2019',\n '07/23/2019', '07/22/2019', '07/15/2019']\n attr = Attribute(datetimes, name='Date')\n randoms = attr.random()\n assert len(randoms) == len(datetimes)\n\n\ndef test_random_strings():\n strings = list(map(lambda x: randomize_string(5), range(size)))\n attr = Attribute(Series(strings, name='String'))\n randoms = attr.random()\n assert len(randoms) == size\n\n\ndef test_retain_ints():\n ints = [3, 5, 7, 8, 7, 1, 10, 30, 16, 19]\n attr = Attribute(ints, name='Integer')\n retains = attr.retain()\n assert len(retains) == len(ints)\n\n retains = attr.retain(size=15)\n assert array_equal(retains.head(len(ints)).tolist(), ints)\n\n\ndef test_encode_numerical_attributes():\n from .testdata import adults01\n attr = Attribute(adults01['age'])\n assert attr.bins[0] <= 19\n assert attr.bins[-1] >= 56\n assert len(attr.encode()) == len(attr)\n\n from sklearn.model_selection import train_test_split\n train, test = train_test_split(adults01['age'])\n assert len(attr.encode(data=train)) == len(train)\n\n\ndef test_encode_categorical_attributes():\n from pandas import DataFrame\n from .testdata import adults01\n frame = DataFrame(adults01)\n attr = Attribute(frame['education'], categorical=True)\n columns = ['11th', '7th-8th', '9th', 'Assoc-acdm', 'Bachelors', 'Doctorate',\n 'HS-grad', 'Masters', 'Some-college']\n assert array_equal(attr.bins, columns)\n assert array_equal(attr.encode().columns, columns)\n\n\ndef test_encode_datetime_attributes():\n from pandas import DataFrame\n from .testdata import adults01\n frame = DataFrame(adults01)\n attr = Attribute(frame['birth'])\n # assert other information\n assert len(attr.encode()) == len(attr)\n\n" ]
[ [ "numpy.array_equal", "pandas.DataFrame", "numpy.random.uniform", "numpy.random.randint", "pandas.Series", "sklearn.model_selection.train_test_split" ] ]
Xiaracto/PaddleRS
[ "b6f7033f3c0ca7bc6952456c0a0f53eef6c1c07f" ]
[ "paddlers/models/ppdet/utils/visualizer.py" ]
[ "# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np\nfrom PIL import Image, ImageDraw\nimport cv2\nimport math\n\nfrom .colormap import colormap\nfrom paddlers.models.ppdet.utils.logger import setup_logger\nlogger = setup_logger(__name__)\n\n__all__ = ['visualize_results']\n\n\ndef visualize_results(image,\n bbox_res,\n mask_res,\n segm_res,\n keypoint_res,\n im_id,\n catid2name,\n threshold=0.5):\n \"\"\"\n Visualize bbox and mask results\n \"\"\"\n if bbox_res is not None:\n image = draw_bbox(image, im_id, catid2name, bbox_res, threshold)\n if mask_res is not None:\n image = draw_mask(image, im_id, mask_res, threshold)\n if segm_res is not None:\n image = draw_segm(image, im_id, catid2name, segm_res, threshold)\n if keypoint_res is not None:\n image = draw_pose(image, keypoint_res, threshold)\n return image\n\n\ndef draw_mask(image, im_id, segms, threshold, alpha=0.7):\n \"\"\"\n Draw mask on image\n \"\"\"\n mask_color_id = 0\n w_ratio = .4\n color_list = colormap(rgb=True)\n img_array = np.array(image).astype('float32')\n for dt in np.array(segms):\n if im_id != dt['image_id']:\n continue\n segm, score = dt['segmentation'], dt['score']\n if score < threshold:\n continue\n import pycocotools.mask as mask_util\n mask = mask_util.decode(segm) * 255\n color_mask = color_list[mask_color_id % len(color_list), 0:3]\n mask_color_id += 1\n for c in range(3):\n color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio * 255\n idx = np.nonzero(mask)\n img_array[idx[0], idx[1], :] *= 1.0 - alpha\n img_array[idx[0], idx[1], :] += alpha * color_mask\n return Image.fromarray(img_array.astype('uint8'))\n\n\ndef draw_bbox(image, im_id, catid2name, bboxes, threshold):\n \"\"\"\n Draw bbox on image\n \"\"\"\n draw = ImageDraw.Draw(image)\n\n catid2color = {}\n color_list = colormap(rgb=True)[:40]\n for dt in np.array(bboxes):\n if im_id != dt['image_id']:\n continue\n catid, bbox, score = dt['category_id'], dt['bbox'], dt['score']\n if score < threshold:\n continue\n\n if catid not in catid2color:\n idx = np.random.randint(len(color_list))\n catid2color[catid] = color_list[idx]\n color = tuple(catid2color[catid])\n\n # draw bbox\n if len(bbox) == 4:\n # draw bbox\n xmin, ymin, w, h = bbox\n xmax = xmin + w\n ymax = ymin + h\n draw.line(\n [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin),\n (xmin, ymin)],\n width=2,\n fill=color)\n elif len(bbox) == 8:\n x1, y1, x2, y2, x3, y3, x4, y4 = bbox\n draw.line(\n [(x1, y1), (x2, y2), (x3, y3), (x4, y4), (x1, y1)],\n width=2,\n fill=color)\n xmin = min(x1, x2, x3, x4)\n ymin = min(y1, y2, y3, y4)\n else:\n logger.error('the shape of bbox must be [M, 4] or [M, 8]!')\n\n # draw label\n text = \"{} {:.2f}\".format(catid2name[catid], score)\n tw, th = draw.textsize(text)\n draw.rectangle(\n [(xmin + 1, ymin - th), (xmin + tw + 1, ymin)], fill=color)\n draw.text((xmin + 1, ymin - th), text, fill=(255, 255, 255))\n\n return image\n\n\ndef save_result(save_path, results, catid2name, threshold):\n \"\"\"\n save result as txt\n \"\"\"\n img_id = int(results[\"im_id\"])\n with open(save_path, 'w') as f:\n if \"bbox_res\" in results:\n for dt in results[\"bbox_res\"]:\n catid, bbox, score = dt['category_id'], dt['bbox'], dt['score']\n if score < threshold:\n continue\n # each bbox result as a line\n # for rbox: classname score x1 y1 x2 y2 x3 y3 x4 y4\n # for bbox: classname score x1 y1 w h\n bbox_pred = '{} {} '.format(catid2name[catid],\n score) + ' '.join(\n [str(e) for e in bbox])\n f.write(bbox_pred + '\\n')\n elif \"keypoint_res\" in results:\n for dt in results[\"keypoint_res\"]:\n kpts = dt['keypoints']\n scores = dt['score']\n keypoint_pred = [img_id, scores, kpts]\n print(keypoint_pred, file=f)\n else:\n print(\"No valid results found, skip txt save\")\n\n\ndef draw_segm(image,\n im_id,\n catid2name,\n segms,\n threshold,\n alpha=0.7,\n draw_box=True):\n \"\"\"\n Draw segmentation on image\n \"\"\"\n mask_color_id = 0\n w_ratio = .4\n color_list = colormap(rgb=True)\n img_array = np.array(image).astype('float32')\n for dt in np.array(segms):\n if im_id != dt['image_id']:\n continue\n segm, score, catid = dt['segmentation'], dt['score'], dt['category_id']\n if score < threshold:\n continue\n import pycocotools.mask as mask_util\n mask = mask_util.decode(segm) * 255\n color_mask = color_list[mask_color_id % len(color_list), 0:3]\n mask_color_id += 1\n for c in range(3):\n color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio * 255\n idx = np.nonzero(mask)\n img_array[idx[0], idx[1], :] *= 1.0 - alpha\n img_array[idx[0], idx[1], :] += alpha * color_mask\n\n if not draw_box:\n center_y, center_x = ndimage.measurements.center_of_mass(mask)\n label_text = \"{}\".format(catid2name[catid])\n vis_pos = (max(int(center_x) - 10, 0), int(center_y))\n cv2.putText(img_array, label_text, vis_pos,\n cv2.FONT_HERSHEY_COMPLEX, 0.3, (255, 255, 255))\n else:\n mask = mask_util.decode(segm) * 255\n sum_x = np.sum(mask, axis=0)\n x = np.where(sum_x > 0.5)[0]\n sum_y = np.sum(mask, axis=1)\n y = np.where(sum_y > 0.5)[0]\n x0, x1, y0, y1 = x[0], x[-1], y[0], y[-1]\n cv2.rectangle(img_array, (x0, y0), (x1, y1),\n tuple(color_mask.astype('int32').tolist()), 1)\n bbox_text = '%s %.2f' % (catid2name[catid], score)\n t_size = cv2.getTextSize(bbox_text, 0, 0.3, thickness=1)[0]\n cv2.rectangle(img_array, (x0, y0), (x0 + t_size[0],\n y0 - t_size[1] - 3),\n tuple(color_mask.astype('int32').tolist()), -1)\n cv2.putText(\n img_array,\n bbox_text, (x0, y0 - 2),\n cv2.FONT_HERSHEY_SIMPLEX,\n 0.3, (0, 0, 0),\n 1,\n lineType=cv2.LINE_AA)\n\n return Image.fromarray(img_array.astype('uint8'))\n\n\ndef draw_pose(image,\n results,\n visual_thread=0.6,\n save_name='pose.jpg',\n save_dir='output',\n returnimg=False,\n ids=None):\n try:\n import matplotlib.pyplot as plt\n import matplotlib\n plt.switch_backend('agg')\n except Exception as e:\n logger.error('Matplotlib not found, please install matplotlib.'\n 'for example: `pip install matplotlib`.')\n raise e\n\n skeletons = np.array([item['keypoints'] for item in results])\n kpt_nums = 17\n if len(skeletons) > 0:\n kpt_nums = int(skeletons.shape[1] / 3)\n skeletons = skeletons.reshape(-1, kpt_nums, 3)\n if kpt_nums == 17: #plot coco keypoint\n EDGES = [(0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6), (5, 7),\n (6, 8), (7, 9), (8, 10), (5, 11), (6, 12), (11, 13), (12, 14),\n (13, 15), (14, 16), (11, 12)]\n else: #plot mpii keypoint\n EDGES = [(0, 1), (1, 2), (3, 4), (4, 5), (2, 6), (3, 6), (6, 7),\n (7, 8), (8, 9), (10, 11), (11, 12), (13, 14), (14, 15),\n (8, 12), (8, 13)]\n NUM_EDGES = len(EDGES)\n\n colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \\\n [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \\\n [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]\n cmap = matplotlib.cm.get_cmap('hsv')\n plt.figure()\n\n img = np.array(image).astype('float32')\n\n color_set = results['colors'] if 'colors' in results else None\n\n if 'bbox' in results and ids is None:\n bboxs = results['bbox']\n for j, rect in enumerate(bboxs):\n xmin, ymin, xmax, ymax = rect\n color = colors[0] if color_set is None else colors[color_set[j] %\n len(colors)]\n cv2.rectangle(img, (xmin, ymin), (xmax, ymax), color, 1)\n\n canvas = img.copy()\n for i in range(kpt_nums):\n for j in range(len(skeletons)):\n if skeletons[j][i, 2] < visual_thread:\n continue\n if ids is None:\n color = colors[i] if color_set is None else colors[color_set[j]\n %\n len(colors)]\n else:\n color = get_color(ids[j])\n\n cv2.circle(\n canvas,\n tuple(skeletons[j][i, 0:2].astype('int32')),\n 2,\n color,\n thickness=-1)\n\n to_plot = cv2.addWeighted(img, 0.3, canvas, 0.7, 0)\n fig = matplotlib.pyplot.gcf()\n\n stickwidth = 2\n\n for i in range(NUM_EDGES):\n for j in range(len(skeletons)):\n edge = EDGES[i]\n if skeletons[j][edge[0], 2] < visual_thread or skeletons[j][edge[\n 1], 2] < visual_thread:\n continue\n\n cur_canvas = canvas.copy()\n X = [skeletons[j][edge[0], 1], skeletons[j][edge[1], 1]]\n Y = [skeletons[j][edge[0], 0], skeletons[j][edge[1], 0]]\n mX = np.mean(X)\n mY = np.mean(Y)\n length = ((X[0] - X[1])**2 + (Y[0] - Y[1])**2)**0.5\n angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))\n polygon = cv2.ellipse2Poly((int(mY), int(mX)),\n (int(length / 2), stickwidth),\n int(angle), 0, 360, 1)\n if ids is None:\n color = colors[i] if color_set is None else colors[color_set[j]\n %\n len(colors)]\n else:\n color = get_color(ids[j])\n cv2.fillConvexPoly(cur_canvas, polygon, color)\n canvas = cv2.addWeighted(canvas, 0.4, cur_canvas, 0.6, 0)\n image = Image.fromarray(canvas.astype('uint8'))\n plt.close()\n return image\n" ]
[ [ "matplotlib.pyplot.switch_backend", "numpy.array", "matplotlib.cm.get_cmap", "numpy.sum", "matplotlib.pyplot.close", "numpy.nonzero", "matplotlib.pyplot.figure", "numpy.mean", "numpy.where", "matplotlib.pyplot.gcf" ] ]
Mackiovello/full-stack-of-politics
[ "63d4f103190985a5accce8e0f9d1d7eb597731ab" ]
[ "viz.py" ]
[ "import pandas as pd\nfrom bokeh.io import output_file, save\nfrom bokeh.plotting import figure\nfrom bokeh.models import HoverTool, ColumnDataSource, Legend\nfrom bokeh.palettes import Category20_18\nimport re\n\n\ndef get_y_coordinate(x_frac, currenty, nexty, offset):\n return currenty + (nexty - currenty) * x_frac + offset\n\n\ndef get_coordinates(time_data, df, offset=1500):\n text_time = [float(i) for i in re.split('-| |:', time_data)]\n x_int = int(text_time[0])\n x_frac = text_time[1] / 12 + text_time[2] / 365\n\n currenty = df.loc[str(x_int)]['num_houses_built']\n nexty = df.loc[str(x_int + 1)]['num_houses_built']\n y = get_y_coordinate(x_frac, currenty, nexty, offset)\n return x_int + x_frac, y\n\n\ndef get_tweets_for_plot(tweets, df):\n x = []\n text = []\n y = []\n time = []\n for i in range(len(tweets)):\n text.append(tweets[i]['text'])\n time_data = tweets[i]['time']\n current_x, current_y = get_coordinates(time_data, df)\n x.append(current_x)\n y.append(current_y)\n time.append(time_data.split(' ')[0])\n return ColumnDataSource(dict(x=x, y=y, text=text, time=time))\n\n\ndef get_voting_for_plot(voting, df):\n x = []\n area = []\n y = []\n time = []\n vote = []\n id = []\n for i in range(len(voting)):\n area.append(voting[i]['area'])\n vote.append(voting[i]['vote'])\n id.append(voting[i]['id'])\n time_data = voting[i]['time']\n current_x, current_y = get_coordinates(time_data, df, offset=-1500)\n x.append(current_x)\n y.append(current_y)\n time.append(time_data.split(' ')[0])\n return ColumnDataSource(\n dict(x=x, y=y, id=id, area=area, time=time, vote=vote))\n\n\ndef plot_stats(width,\n height,\n stats_csv,\n politician_name='Stefan Löfven',\n outfile='vis.html',\n tweets=[],\n voting=[]):\n housing = pd.read_csv(stats_csv)\n\n sum_p = figure(\n plot_width=width,\n plot_height=height,\n title='Total amount of houses built between 1991 and 2016')\n\n summary_stats = housing.sum(axis=0)[2:]\n summary_stats.index.astype(int)\n\n summary_df = summary_stats.to_frame()\n summary_df['year'] = summary_df.index\n summary_df.columns = ['num_houses_built', 'year']\n\n src = ColumnDataSource(summary_df)\n line = sum_p.line(\n 'year',\n 'num_houses_built',\n source=src,\n legend='Housing market statistics',\n line_width=5)\n circle = sum_p.circle('year', 'num_houses_built', \n fill_color='white', \n size=5, source=src)\n\n sum_hover = HoverTool(\n tooltips=[('time', '@year'), ('number of houses built',\n '@num_houses_built')],\n renderers=[line, circle])\n sum_p.xaxis.axis_label = 'Year'\n sum_p.yaxis.axis_label = 'Total amount of houses built'\n sum_p.add_tools(sum_hover)\n\n # Add tweets data\n if tweets != []:\n tweet_data = get_tweets_for_plot(tweets, summary_df)\n tweet_triangles = sum_p.inverted_triangle(\n x='x',\n y='y',\n size=20,\n color='#f48fb1',\n source=tweet_data,\n legend='Relevant tweets from ' + politician_name)\n tweet_hover = HoverTool(\n tooltips=[('time', '@time'), ('text', '@text')],\n renderers=[tweet_triangles])\n sum_p.add_tools(tweet_hover)\n\n # Add voting data\n if voting != []:\n voting_data = get_voting_for_plot(voting, summary_df)\n voting_triangles = sum_p.triangle(\n x='x',\n y='y',\n size=20,\n color='#80cbc4',\n source=voting_data,\n legend='Relevant votings from ' + politician_name)\n voting_hover = HoverTool(\n tooltips=[('time', '@time'), ('proposal topic', '@area'),\n ('id', '@id'), ('voting', '@vote')],\n renderers=[voting_triangles])\n sum_p.add_tools(voting_hover)\n\n output_file(outfile)\n save(sum_p)\n\n\ndef get_sample_data():\n tweets = [{\n 'time': '2014-08-29 17:53:00',\n 'text': 'Jag lovar 150001 bostäder. Tihi, jag vann!'\n }]\n\n votings = [{\n 'time': '2014-04-10',\n 'id': 'Civilutskottets betänkande 2013/14:CU22',\n 'area': 'Fler bostäder åt unga och studenter',\n 'vote': 'yes'\n }, {\n 'time': '2011-04-06',\n 'id': 'Civilutskottets betänkande 2010/11:CU22',\n 'area': 'Plan- och byggfrågor',\n 'vote': 'yes'\n }, {\n 'time': '2006-03-08',\n 'id': 'BoUs betänkande 2005/06:BoU7',\n 'vote': 'yes',\n 'area': 'Plan- och byggfrågor'\n }]\n return tweets, votings\n" ]
[ [ "pandas.read_csv" ] ]
shoes22/openpilot
[ "a965de3c96a53b67d106cfa775e3407db82dd0e1" ]
[ "selfdrive/debug/check_timings.py" ]
[ "#!/usr/bin/env python3\n# type: ignore\nimport sys\nimport time\nimport numpy as np\nfrom collections import defaultdict, deque\n\nimport cereal.messaging as messaging\n\nsocks = {s: messaging.sub_sock(s, conflate=False) for s in sys.argv[1:]}\nts = defaultdict(lambda: deque(maxlen=100))\n\nif __name__ == \"__main__\":\n while True:\n print()\n for s, sock in socks.items():\n msgs = messaging.drain_sock(sock)\n for m in msgs:\n ts[s].append(m.logMonoTime / 1e6)\n\n if len(ts[s]):\n d = np.diff(ts[s])\n print(f\"{s:25} {np.mean(d):.2f} {np.std(d):.2f} {np.max(d):.2f} {np.min(d):.2f}\")\n time.sleep(1)\n" ]
[ [ "numpy.max", "numpy.min", "numpy.mean", "numpy.diff", "numpy.std" ] ]
SciTools-incubator/iris-ugrid
[ "ce035e6de456b5ab9df5daa9d164c59baddd7552" ]
[ "iris_ugrid/tests/synthetic_data_generator/__init__.py" ]
[ "# Copyright Iris contributors\n#\n# This file is part of Iris and is released under the LGPL license.\n# See COPYING and COPYING.LESSER in the root of the repository for full\n# licensing details.\n\"\"\"\nProvides synthetic data generation capability in order to test ugrid loading\nand regridding.\n\nConcept:\n * Directory of CDL header template strings (`mesh_headers/`), formatted as\n :class:string.Template s, including placeholders.\n * Functions to fill placeholders, write NetCDF files then populate with data\n using :mod:NetCDF4.\n * One function per template - no risk of inflexibility when adding templates.\n * Some private convenience functions for the template functions to call.\n\"\"\"\n\nfrom pathlib import Path\nfrom string import Template\nimport subprocess\n\nimport netCDF4\nimport numpy as np\n\n\ndef _file_from_cdl_template(\n temp_file_dir, dataset_name, dataset_type, template_subs\n):\n \"\"\"Shared template filling behaviour.\n\n Substitutes placeholders in the appropriate CDL template, saves to a\n NetCDF file.\n \"\"\"\n nc_write_path = (\n Path(temp_file_dir).joinpath(dataset_name).with_suffix(\".nc\")\n )\n # Fetch the specified CDL template type.\n templates_dir = Path(__file__).parent / \"mesh_headers\"\n template_filepath = templates_dir.joinpath(dataset_type).with_suffix(\n \".txt\"\n )\n # Substitute placeholders.\n with open(template_filepath) as file:\n template_string = Template(file.read())\n cdl = template_string.substitute(template_subs)\n\n # Spawn an \"ncgen\" command to create an actual NetCDF file from the\n # CDL string.\n subprocess.run(\n [\"ncgen\", \"-o\" + str(nc_write_path)],\n input=cdl,\n encoding=\"ascii\",\n check=True,\n )\n\n return nc_write_path\n\n\ndef _add_standard_data(nc_path, unlimited_dim_size=0):\n \"\"\"Shared data populating behaviour.\n\n Adds placeholder data to the variables in a NetCDF file, accounting for\n dimension size, 'dimension coordinates' and a possible unlimited dimension.\n \"\"\"\n\n ds = netCDF4.Dataset(nc_path, \"r+\")\n\n unlimited_dim_names = [\n dim for dim in ds.dimensions if ds.dimensions[dim].size == 0\n ]\n # Data addition dependent on this assumption:\n assert len(unlimited_dim_names) < 2\n\n # Fill all data variables (both mesh and phenomenon vars) with placeholder\n # numbers.\n for var in ds.variables.values():\n shape = list(var.shape)\n dims = var.dimensions\n # Fill the unlimited dimension with the input size.\n shape = [\n unlimited_dim_size if dim == unlimited_dim_names[0] else size\n for dim, size in zip(dims, shape)\n ]\n data = np.zeros(shape, dtype=var.dtype)\n if len(var.dimensions) == 1 and var.dimensions[0] == var.name:\n # Fill the var with ascending values (not all zeroes),\n # so it can be a dim-coord.\n data = np.arange(data.size, dtype=data.dtype).reshape(data.shape)\n var[:] = data\n\n ds.close()\n\n\ndef create_file__xios_2d_face_half_levels(\n temp_file_dir, dataset_name, n_faces=866, n_times=1\n):\n \"\"\"Create a synthetic NetCDF file with XIOS-like content.\n\n Starts from a template CDL headers string, modifies to the input\n dimensions then adds data of the correct size.\n\n Parameters\n ----------\n temp_file_dir : str or pathlib.Path\n The directory in which to place the created file.\n dataset_name : str\n The name for the NetCDF dataset and also the created file.\n n_faces, n_times: int\n Dimension sizes for the dataset.\n\n Returns\n -------\n str\n Path of the created NetCDF file.\n\n \"\"\"\n dataset_type = \"xios_2D_face_half_levels\"\n\n # Set the placeholder substitutions.\n template_subs = {\n \"DATASET_NAME\": dataset_name,\n \"NUM_NODES\": n_faces + 2,\n \"NUM_FACES\": n_faces,\n }\n\n # Create a NetCDF file based on the dataset type template and substitutions.\n nc_path = _file_from_cdl_template(\n temp_file_dir, dataset_name, dataset_type, template_subs\n )\n\n # Populate with the standard set of data, sized correctly.\n _add_standard_data(nc_path, unlimited_dim_size=n_times)\n\n return str(nc_path)\n\n\n# 2020-12-14: still used downstream, now deprecated in favour of more precise naming.\ncreate_file__xios_half_levels_faces = create_file__xios_2d_face_half_levels\n\n\ndef create_file__xios_3d_face_half_levels(\n temp_file_dir, dataset_name, n_faces=866, n_times=1, n_levels=38\n):\n \"\"\"Create a synthetic NetCDF file with XIOS-like content.\n\n Starts from a template CDL headers string, modifies to the input\n dimensions then adds data of the correct size.\n\n Parameters\n ----------\n temp_file_dir : str or pathlib.Path\n The directory in which to place the created file.\n dataset_name : str\n The name for the NetCDF dataset and also the created file.\n n_faces, n_times, n_levels: int\n Dimension sizes for the dataset.\n\n Returns\n -------\n str\n Path of the created NetCDF file.\n\n \"\"\"\n dataset_type = \"xios_3D_face_half_levels\"\n\n # Set the placeholder substitutions.\n template_subs = {\n \"DATASET_NAME\": dataset_name,\n \"NUM_NODES\": n_faces + 2,\n \"NUM_FACES\": n_faces,\n \"NUM_LEVELS\": n_levels,\n }\n\n # Create a NetCDF file based on the dataset type template and\n # substitutions.\n nc_path = _file_from_cdl_template(\n temp_file_dir, dataset_name, dataset_type, template_subs\n )\n\n # Populate with the standard set of data, sized correctly.\n _add_standard_data(nc_path, unlimited_dim_size=n_times)\n\n return str(nc_path)\n\n\ndef create_file__xios_3d_face_full_levels(\n temp_file_dir, dataset_name, n_faces=866, n_times=1, n_levels=39\n):\n \"\"\"Create a synthetic NetCDF file with XIOS-like content.\n\n Starts from a template CDL headers string, modifies to the input\n dimensions then adds data of the correct size.\n\n Parameters\n ----------\n temp_file_dir : str or pathlib.Path\n The directory in which to place the created file.\n dataset_name : str\n The name for the NetCDF dataset and also the created file.\n n_faces, n_times, n_levels: int\n Dimension sizes for the dataset.\n\n Returns\n -------\n str\n Path of the created NetCDF file.\n\n \"\"\"\n dataset_type = \"xios_3D_face_full_levels\"\n\n # Set the placeholder substitutions.\n template_subs = {\n \"DATASET_NAME\": dataset_name,\n \"NUM_NODES\": n_faces + 2,\n \"NUM_FACES\": n_faces,\n \"NUM_LEVELS\": n_levels,\n }\n\n # Create a NetCDF file based on the dataset type template and\n # substitutions.\n nc_path = _file_from_cdl_template(\n temp_file_dir, dataset_name, dataset_type, template_subs\n )\n\n # Populate with the standard set of data, sized correctly.\n _add_standard_data(nc_path, unlimited_dim_size=n_times)\n\n return str(nc_path)\n" ]
[ [ "numpy.arange", "numpy.zeros" ] ]
decisionforce/EGPO
[ "aba65504795e7d5bf652c8bb9ed1f1fb73d84b45" ]
[ "egpo_utils/sac_pid/sac_pid_model.py" ]
[ "import numpy as np\nfrom gym.spaces import Discrete\nfrom ray.rllib.models.tf.tf_modelv2 import TFModelV2\nfrom ray.rllib.utils.framework import try_import_tf\nfrom ray.rllib.models.tf.misc import normc_initializer\n\ntf, _, _ = try_import_tf()\n\nSCALE_DIAG_MIN_MAX = (-20, 2)\n\n\nclass ConstrainedSACModel(TFModelV2):\n \"\"\"Extension of standard TFModel for SAC.\n\n Data flow:\n obs -> forward() -> model_out\n model_out -> get_policy_output() -> pi(s)\n model_out, actions -> get_q_values() -> Q(s, a)\n model_out, actions -> get_twin_q_values() -> Q_twin(s, a)\n\n Note that this class by itself is not a valid model unless you\n implement forward() in a subclass.\"\"\"\n\n def __init__(\n self,\n obs_space,\n action_space,\n num_outputs,\n model_config,\n name,\n actor_hidden_activation=\"relu\",\n actor_hiddens=(256, 256),\n critic_hidden_activation=\"relu\",\n critic_hiddens=(256, 256),\n twin_q=False,\n twin_cost_q=False,\n initial_alpha=1.0,\n target_entropy=None\n ):\n \"\"\"Initialize variables of this model.\n\n Extra model kwargs:\n actor_hidden_activation (str): activation for actor network\n actor_hiddens (list): hidden layers sizes for actor network\n critic_hidden_activation (str): activation for critic network\n critic_hiddens (list): hidden layers sizes for critic network\n twin_q (bool): build twin Q networks.\n initial_alpha (float): The initial value for the to-be-optimized\n alpha parameter (default: 1.0).\n\n Note that the core layers for forward() are not defined here, this\n only defines the layers for the output heads. Those layers for\n forward() should be defined in subclasses of SACModel.\n \"\"\"\n super(ConstrainedSACModel, self).__init__(\n obs_space, action_space, num_outputs, model_config, name\n )\n self.discrete = False\n if isinstance(action_space, Discrete):\n self.action_dim = action_space.n\n self.discrete = True\n action_outs = q_outs = self.action_dim\n else:\n self.action_dim = np.product(action_space.shape)\n action_outs = 2 * self.action_dim\n q_outs = 1\n\n self.model_out = tf.keras.layers.Input(\n shape=(self.num_outputs,), name=\"model_out\"\n )\n self.action_model = tf.keras.Sequential(\n [\n tf.keras.layers.Dense(\n units=hidden,\n activation=getattr(tf.nn, actor_hidden_activation, None),\n name=\"action_{}\".format(i + 1)\n ) for i, hidden in enumerate(actor_hiddens)\n ] + [\n tf.keras.layers.\n Dense(units=action_outs, activation=None, name=\"action_out\")\n ]\n )\n self.shift_and_log_scale_diag = self.action_model(self.model_out)\n\n self.register_variables(self.action_model.variables)\n\n self.actions_input = None\n if not self.discrete:\n self.actions_input = tf.keras.layers.Input(\n shape=(self.action_dim,), name=\"actions\"\n )\n\n def build_q_net(name, observations, actions):\n # For continuous actions: Feed obs and actions (concatenated)\n # through the NN. For discrete actions, only obs.\n q_net = tf.keras.Sequential(\n (\n [\n tf.keras.layers.Concatenate(axis=1),\n ] if not self.discrete else []\n ) + [\n tf.keras.layers.Dense(\n units=units,\n activation=getattr(\n tf.nn, critic_hidden_activation, None\n ),\n kernel_initializer=normc_initializer(1.0),\n name=\"{}_hidden_{}\".format(name, i)\n ) for i, units in enumerate(critic_hiddens)\n ] + [\n tf.keras.layers.Dense(\n units=q_outs,\n activation=None,\n kernel_initializer=normc_initializer(1.0),\n name=\"{}_out\".format(name)\n )\n ]\n )\n\n if self.discrete:\n q_net = tf.keras.Model(observations, q_net(observations))\n else:\n q_net = tf.keras.Model(\n [observations, actions], q_net([observations, actions])\n )\n return q_net\n\n self.q_net = build_q_net(\"q\", self.model_out, self.actions_input)\n self.cost_q_net = build_q_net(\n \"cost_q\", self.model_out, self.actions_input\n )\n self.register_variables(self.q_net.variables)\n self.register_variables(self.cost_q_net.variables)\n\n if twin_q:\n self.twin_q_net = build_q_net(\n \"twin_q\", self.model_out, self.actions_input\n )\n self.register_variables(self.twin_q_net.variables)\n else:\n self.twin_q_net = None\n if twin_cost_q:\n self.cost_twin_q_net = build_q_net(\n \"cost_twin_q\", self.model_out, self.actions_input\n )\n self.register_variables(self.cost_twin_q_net.variables)\n else:\n self.cost_twin_q_net = None\n\n self.log_alpha = tf.Variable(\n np.log(initial_alpha), dtype=tf.float32, name=\"log_alpha\"\n )\n self.alpha = tf.exp(self.log_alpha)\n\n # Auto-calculate the target entropy.\n if target_entropy is None or target_entropy == \"auto\":\n # See hyperparams in [2] (README.md).\n if self.discrete:\n target_entropy = 0.98 * np.array(\n -np.log(1.0 / action_space.n), dtype=np.float32\n )\n # See [1] (README.md).\n else:\n target_entropy = -np.prod(action_space.shape)\n self.target_entropy = target_entropy\n\n self.register_variables([self.log_alpha])\n\n def get_q_values(self, model_out, actions=None):\n \"\"\"Return the Q estimates for the most recent forward pass.\n\n This implements Q(s, a).\n\n Arguments:\n model_out (Tensor): obs embeddings from the model layers, of shape\n [BATCH_SIZE, num_outputs].\n actions (Optional[Tensor]): Actions to return the Q-values for.\n Shape: [BATCH_SIZE, action_dim]. If None (discrete action\n case), return Q-values for all actions.\n\n Returns:\n tensor of shape [BATCH_SIZE].\n \"\"\"\n if actions is not None:\n return self.q_net([model_out, actions])\n else:\n return self.q_net(model_out)\n\n def get_cost_q_values(self, model_out, actions=None):\n if actions is not None:\n return self.cost_q_net([model_out, actions])\n else:\n return self.cost_q_net(model_out)\n\n def get_twin_cost_q_values(self, model_out, actions=None):\n if actions is not None:\n return self.cost_twin_q_net([model_out, actions])\n else:\n return self.cost_twin_q_net(model_out)\n\n def get_twin_q_values(self, model_out, actions=None):\n \"\"\"Same as get_q_values but using the twin Q net.\n\n This implements the twin Q(s, a).\n\n Arguments:\n model_out (Tensor): obs embeddings from the model layers, of shape\n [BATCH_SIZE, num_outputs].\n actions (Optional[Tensor]): Actions to return the Q-values for.\n Shape: [BATCH_SIZE, action_dim]. If None (discrete action\n case), return Q-values for all actions.\n\n Returns:\n tensor of shape [BATCH_SIZE].\n \"\"\"\n if actions is not None:\n return self.twin_q_net([model_out, actions])\n else:\n return self.twin_q_net(model_out)\n\n def get_policy_output(self, model_out):\n \"\"\"Return the action output for the most recent forward pass.\n\n This outputs the support for pi(s). For continuous action spaces, this\n is the action directly. For discrete, is is the mean / std dev.\n\n Arguments:\n model_out (Tensor): obs embeddings from the model layers, of shape\n [BATCH_SIZE, num_outputs].\n\n Returns:\n tensor of shape [BATCH_SIZE, action_out_size]\n \"\"\"\n return self.action_model(model_out)\n\n def policy_variables(self):\n \"\"\"Return the list of variables for the policy net.\"\"\"\n\n return list(self.action_model.variables)\n\n def q_variables(self):\n \"\"\"Return the list of variables for Q / twin Q nets.\"\"\"\n\n return self.q_net.variables + (\n self.twin_q_net.variables if self.twin_q_net else []\n )\n\n def cost_q_variables(self):\n return self.cost_q_net.variables + (\n self.cost_twin_q_net.variables\n if self.cost_twin_q_net else []\n )\n" ]
[ [ "numpy.product", "numpy.prod", "numpy.log" ] ]