repo_name
stringlengths
6
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
possible_versions
list
AdamStelmaszczyk/learning2run
[ "71341f7cc76c297980fb0e0b67076425a5bde878" ]
[ "baselines/baselines/common/mpi_adam.py" ]
[ "from mpi4py import MPI\nimport baselines.common.tf_util as U\nimport tensorflow as tf\nimport numpy as np\n\nclass MpiAdam(object):\n def __init__(self, var_list, beta1=0.9, beta2=0.999, epsilon=1e-08, scale_grad_by_procs=True, comm=None):\n self.var_list = var_list\n self.beta1 = beta1\n self.beta2 = beta2\n self.epsilon = epsilon\n self.scale_grad_by_procs = scale_grad_by_procs\n size = sum(U.numel(v) for v in var_list)\n self.m = np.zeros(size, 'float32')\n self.v = np.zeros(size, 'float32')\n self.t = 0\n self.setfromflat = U.SetFromFlat(var_list)\n self.getflat = U.GetFlat(var_list)\n self.comm = MPI.COMM_WORLD if comm is None else comm\n\n def update(self, localg, stepsize):\n if self.t % 100 == 0:\n self.check_synced()\n localg = localg.astype('float32')\n globalg = np.zeros_like(localg)\n self.comm.Allreduce(localg, globalg, op=MPI.SUM)\n if self.scale_grad_by_procs:\n globalg /= self.comm.Get_size()\n\n self.t += 1\n a = stepsize * np.sqrt(1 - self.beta2**self.t)/(1 - self.beta1**self.t)\n self.m = self.beta1 * self.m + (1 - self.beta1) * globalg\n self.v = self.beta2 * self.v + (1 - self.beta2) * (globalg * globalg)\n step = (- a) * self.m / (np.sqrt(self.v) + self.epsilon)\n self.setfromflat(self.getflat() + step)\n\n def sync(self):\n theta = self.getflat()\n self.comm.Bcast(theta, root=0)\n self.setfromflat(theta)\n\n def check_synced(self):\n if self.comm.Get_rank() == 0: # this is root\n theta = self.getflat()\n self.comm.Bcast(theta, root=0)\n else:\n thetalocal = self.getflat()\n thetaroot = np.empty_like(thetalocal)\n self.comm.Bcast(thetaroot, root=0)\n assert (thetaroot == thetalocal).all(), (thetaroot, thetalocal)\n\[email protected]_session\ndef test_MpiAdam():\n np.random.seed(0)\n tf.set_random_seed(0)\n \n a = tf.Variable(np.random.randn(3).astype('float32'))\n b = tf.Variable(np.random.randn(2,5).astype('float32'))\n loss = tf.reduce_sum(tf.square(a)) + tf.reduce_sum(tf.sin(b))\n\n stepsize = 1e-2\n update_op = tf.train.AdamOptimizer(stepsize).minimize(loss)\n do_update = U.function([], loss, updates=[update_op])\n\n tf.get_default_session().run(tf.global_variables_initializer())\n for i in range(10):\n print(i,do_update())\n\n tf.set_random_seed(0)\n tf.get_default_session().run(tf.global_variables_initializer())\n\n var_list = [a,b]\n lossandgrad = U.function([], [loss, U.flatgrad(loss, var_list)], updates=[update_op])\n adam = MpiAdam(var_list)\n\n for i in range(10):\n l,g = lossandgrad()\n adam.update(g, stepsize)\n print(i,l)" ]
[ [ "tensorflow.get_default_session", "tensorflow.sin", "numpy.sqrt", "numpy.random.seed", "numpy.empty_like", "tensorflow.global_variables_initializer", "numpy.zeros_like", "numpy.random.randn", "tensorflow.square", "tensorflow.train.AdamOptimizer", "tensorflow.set_random_seed", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
igorfyago/Andrew-Ng-Machine-Learning
[ "e6f947c93f9a4b1c9cfdaab4333525c504fd9233" ]
[ "Python/pruebas/prueba1NumPy.py" ]
[ "# generar una normal de altura y peso\nimport numpy as np\n\nheight = np.round(np.random.normal(1.75, 0.20, 5000), 2)\nweight = np.round(np.random.normal(60.32, 15, 5000), 2)\nnp_city = np.column_stack((height, weight))\n\nprint(np_city)\n\n# Print mean height (first column)\navg = round(np.mean(np_city[:,0]),2)\nprint(\"Average: \" + str(avg))\n\n# Print median height.\nmed = np.median(np_city[:,0])\nprint(\"Median: \" + str(med))\n\n# Print out the standard deviation on height.\nstddev = round(np.std(np_city[:,0]),2)\nprint(\"Standard Deviation: \" + str(stddev))\n\n# Print out correlation between first and second column.\ncorr = np.corrcoef(np_city[:,0],np_city[:,1])\nprint(\"Correlation: \" + str(corr))" ]
[ [ "numpy.median", "numpy.random.normal", "numpy.std", "numpy.mean", "numpy.column_stack", "numpy.corrcoef" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cts198859/ReAgent
[ "866f91785ca86db32fb67744aa063fe77791ff21", "20f3d333821bad364fd567cce97de51c44123484", "866f91785ca86db32fb67744aa063fe77791ff21", "20f3d333821bad364fd567cce97de51c44123484" ]
[ "reagent/gym/policies/samplers/discrete_sampler.py", "reagent/ope/estimators/estimator.py", "reagent/gym/policies/samplers/continuous_sampler.py", "reagent/ope/test/unit_tests/test_types.py" ]
[ "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\n\n\nimport reagent.types as rlt\nimport torch\nimport torch.nn.functional as F\nfrom reagent.gym.types import Sampler\n\n\nclass SoftmaxActionSampler(Sampler):\n \"\"\"\n Softmax sampler.\n Equation: http://incompleteideas.net/book/first/ebook/node17.html\n The action scores are logits.\n\n Args:\n temperature: A measure of how uniformly random the distribution looks.\n The higher the temperature, the more uniform the sampling.\n \"\"\"\n\n def __init__(self, temperature: float = 1.0):\n assert temperature > 0, f\"Invalid non-positive temperature {temperature}.\"\n self.temperature = temperature\n\n def _get_distribution(\n self, scores: torch.Tensor\n ) -> torch.distributions.Categorical:\n return torch.distributions.Categorical(logits=scores / self.temperature)\n\n @torch.no_grad()\n def sample_action(self, scores: torch.Tensor) -> rlt.ActorOutput:\n assert (\n scores.dim() == 2\n ), f\"scores shape is {scores.shape}, not (batch_size, num_actions)\"\n batch_size, num_actions = scores.shape\n m = self._get_distribution(scores)\n raw_action = m.sample()\n assert raw_action.shape == (\n batch_size,\n ), f\"{raw_action.shape} != ({batch_size}, )\"\n action = F.one_hot(raw_action, num_actions)\n assert action.ndim == 2\n log_prob = m.log_prob(raw_action)\n assert log_prob.ndim == 1\n return rlt.ActorOutput(action=action, log_prob=log_prob)\n\n @torch.no_grad()\n def log_prob(self, scores: torch.Tensor, action: torch.Tensor) -> torch.Tensor:\n assert len(scores.shape) == 2, f\"{scores.shape}\"\n assert scores.shape == action.shape, f\"{scores.shape} != {action.shape}\"\n m = self._get_distribution(scores)\n # pyre-fixme[16]: `Tensor` has no attribute `argmax`.\n return m.log_prob(action.argmax(dim=1))\n\n\nclass GreedyActionSampler(Sampler):\n \"\"\"\n Return the highest scoring action.\n \"\"\"\n\n def _get_greedy_indices(self, scores: torch.Tensor) -> torch.Tensor:\n assert (\n len(scores.shape) == 2\n ), f\"scores shape is {scores.shape}, not (batchsize, num_actions)\"\n # pyre-fixme[16]: `Tensor` has no attribute `argmax`.\n return scores.argmax(dim=1)\n\n @torch.no_grad()\n def sample_action(self, scores: torch.Tensor) -> rlt.ActorOutput:\n\n batch_size, num_actions = scores.shape\n raw_action = self._get_greedy_indices(scores)\n action = F.one_hot(raw_action, num_actions)\n assert action.shape == (batch_size, num_actions)\n return rlt.ActorOutput(action=action, log_prob=torch.ones_like(raw_action))\n\n @torch.no_grad()\n def log_prob(self, scores: torch.Tensor, action: torch.Tensor) -> torch.Tensor:\n greedy_indices = self._get_greedy_indices(scores)\n # pyre-fixme[16]: `Tensor` has no attribute `argmax`.\n match = greedy_indices == action.argmax(-1)\n lp = torch.zeros(scores.shape[0]).float()\n lp[match] = -float(\"inf\")\n return lp\n\n\nclass EpsilonGreedyActionSampler(Sampler):\n \"\"\"\n Epsilon-Greedy Policy\n\n With probability epsilon, a random action is sampled. Otherwise,\n the highest scoring (greedy) action is chosen.\n\n Call update() to decay the amount of exploration by lowering\n `epsilon` by a factor of `epsilon_decay` (<=1) until we reach\n `minimum_epsilon`\n \"\"\"\n\n def __init__(\n self, epsilon: float, epsilon_decay: float = 1.0, minimum_epsilon: float = 0.0\n ):\n self.epsilon = float(epsilon)\n assert epsilon_decay <= 1\n self.epsilon_decay = epsilon_decay\n assert minimum_epsilon <= epsilon_decay\n self.minimum_epsilon = minimum_epsilon\n\n def sample_action(self, scores: torch.Tensor) -> rlt.ActorOutput:\n assert scores.dim() == 2, (\n \"scores dim is %d\" % scores.dim()\n ) # batch_size x num_actions\n batch_size, num_actions = scores.shape\n\n # pyre-fixme[16]: `Tensor` has no attribute `argmax`.\n argmax = F.one_hot(scores.argmax(dim=1), num_actions).bool()\n\n rand_prob = self.epsilon / num_actions\n p = torch.full_like(rand_prob, scores)\n\n greedy_prob = 1 - self.epsilon + rand_prob\n p[argmax] = greedy_prob\n\n m = torch.distributions.Categorical(probs=p)\n raw_action = m.sample()\n action = F.one_hot(raw_action, num_actions)\n assert action.shape == (batch_size, num_actions)\n log_prob = m.log_prob(raw_action)\n assert log_prob.shape == (batch_size,)\n return rlt.ActorOutput(action=action, log_prob=log_prob)\n\n def log_prob(self, scores: torch.Tensor, action: torch.Tensor) -> torch.Tensor:\n max_index = self.sample_action(scores).argmax(-1)\n # pyre-fixme[16]: `Tensor` has no attribute `argmax`.\n opt = max_index == action.argmax(-1)\n n = len(scores)\n lp = torch.ones(n) * self.epsilon / n\n lp[opt] = 1 - self.epsilon + self.epsilon / n\n return lp\n\n def update(self) -> None:\n self.epsilon *= self.epsilon_decay\n if self.minimum_epsilon is not None:\n self.epsilon = max(self.epsilon, self.minimum_epsilon)\n", "#!/usr/bin/env python3\n\nimport logging\nimport math\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass\nfrom typing import Optional, Tuple, Union\n\nimport torch\nfrom torch import Tensor\n\n\nclass ResultDiffs:\n def __init__(self, diffs: Tensor):\n self._diffs = diffs\n self._rmse = None\n self._bias = None\n self._variance = None\n\n @property\n def rmse(self) -> Tensor:\n if self._rmse is None:\n self._rmse = (self._diffs ** 2.0).mean().sqrt()\n return self._rmse\n\n @property\n def bias(self) -> Tensor:\n if self._bias is None:\n self._bias = self._diffs.mean()\n return self._bias\n\n @property\n def variance(self) -> Tensor:\n if self._variance is None:\n self._variance = self._diffs.var()\n return self._variance\n\n def __repr__(self):\n return (\n f\"samples={self._diffs.shape[0]}, rmse={self.rmse.item()}\"\n f\", bias={self.bias}, variance={self.variance}\"\n )\n\n\n@dataclass(frozen=True)\nclass EstimatorResults:\n \"\"\"\n Estimator results\n \"\"\"\n\n logs: Tensor\n estimates: Tensor\n ground_truths: Optional[Tensor] = None\n estimate_log_diffs: Optional[ResultDiffs] = None\n estimate_gt_diffs: Optional[ResultDiffs] = None\n\n def __repr__(self):\n repr = \"\"\n if self.estimate_gt_diffs is not None:\n repr += f\"Target vs GT: {self.estimate_gt_diffs}\"\n if self.estimate_log_diffs is not None:\n if len(repr) > 0:\n repr += \", \"\n repr += f\"Target vs Log: {self.estimate_log_diffs}\"\n return repr\n\n\nclass Estimator(ABC):\n \"\"\"\n Estimator interface\n \"\"\"\n\n def __init__(self, device=None):\n self._device = device\n self._logs = [] # logged values\n self._estimates = [] # estimated values\n self._ground_truths = [] # ground truth values\n self._results = None\n\n def reset(self):\n self._logs.clear()\n self._estimates.clear()\n self._ground_truths.clear()\n self._results = None\n\n @property\n def logged_values(self):\n return self._logs\n\n @property\n def estimated_values(self):\n return self._estimates\n\n @property\n def ground_truth_values(self):\n return self._ground_truths\n\n def _append_estimate(\n self,\n log: Union[float, Tensor],\n estimate: Union[float, Tensor],\n ground_truth: Optional[Union[float, Tensor]] = None,\n ):\n if math.isnan(estimate) or math.isinf(estimate):\n return\n logging.info(\n f\" Append estimate [{len(self._estimates) + 1}]: \"\n f\"{log}, {estimate}, {ground_truth}\"\n )\n self._logs.append(log)\n self._estimates.append(estimate)\n if ground_truth is not None:\n self._ground_truths.append(ground_truth)\n self._results = None\n\n @property\n def results(self) -> EstimatorResults:\n if self._results is None:\n logs_tensor = torch.tensor(\n self._logs, dtype=torch.float, device=self._device\n )\n estimates_tensor = torch.tensor(\n self._estimates, dtype=torch.float, device=self._device\n )\n if len(self._ground_truths) == len(self._estimates):\n ground_truths_tensor = torch.tensor(\n self._ground_truths, dtype=torch.float, device=self._device\n )\n log_gt_diff = logs_tensor - ground_truths_tensor\n else:\n ground_truths_tensor = None\n log_gt_diff = None\n self._results = EstimatorResults(\n logs_tensor,\n estimates_tensor,\n ground_truths_tensor,\n ResultDiffs(log_gt_diff) if log_gt_diff is not None else None,\n ResultDiffs(estimates_tensor - logs_tensor),\n )\n return self._results\n\n @abstractmethod\n def evaluate(self, input, **kwargs) -> EstimatorResults:\n pass\n\n def __repr__(self):\n return f\"{self.__class__.__name__}{{device[{self._device}]}}\"\n", "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\n\nimport reagent.types as rlt\nimport torch\nfrom reagent.gym.types import GaussianSamplerScore, Sampler\n\n\nclass GaussianSampler(Sampler):\n def __init__(self, actor_network):\n self.actor_network = actor_network\n\n def _sample_action(self, loc: torch.Tensor, scale_log: torch.Tensor):\n r = torch.randn_like(scale_log, device=scale_log.device)\n # pyre-fixme[16]: `Tensor` has no attribute `exp`.\n action = torch.tanh(loc + r * scale_log.exp())\n # Since each dim are independent, log-prob is simply sum\n log_prob = self.actor_network._log_prob(r, scale_log)\n squash_correction = self.actor_network._squash_correction(action)\n log_prob = torch.sum(log_prob - squash_correction, dim=1)\n return action, log_prob\n\n @torch.no_grad()\n def sample_action(self, scores: GaussianSamplerScore) -> rlt.ActorOutput:\n self.actor_network.eval()\n unscaled_actions, log_prob = self._sample_action(scores.loc, scores.scale_log)\n self.actor_network.train()\n\n return rlt.ActorOutput(action=unscaled_actions, log_prob=log_prob)\n\n def _log_prob(\n self, loc: torch.Tensor, scale_log: torch.Tensor, squashed_action: torch.Tensor\n ):\n # This is not getting exported; we can use it\n # pyre-fixme[16]: `Tensor` has no attribute `exp`.\n n = torch.distributions.Normal(loc, scale_log.exp())\n raw_action = self.actor_network._atanh(squashed_action)\n log_prob = n.log_prob(raw_action)\n squash_correction = self.actor_network._squash_correction(squashed_action)\n log_prob = torch.sum(log_prob - squash_correction, dim=1)\n return log_prob\n\n @torch.no_grad()\n # pyre-fixme[14]: `log_prob` overrides method defined in `Sampler` inconsistently.\n def log_prob(\n self, scores: GaussianSamplerScore, squashed_action: torch.Tensor\n ) -> torch.Tensor:\n self.actor_network.eval()\n # pyre-fixme[20]: Argument `squashed_action` expected.\n log_prob = self._log_prob(scores.loc, scores.scale_log)\n self.actor_network.train()\n return log_prob\n", "#!/usr/bin/env python3\n\nimport unittest\nfrom typing import Tuple, Union\n\nimport numpy as np\nimport torch\nfrom reagent.ope.estimators.types import Distribution, Items, TypeWrapper, Values\nfrom torch import Tensor\n\n\nclass TestTypes(unittest.TestCase):\n TestType = Union[int, Tuple[int], float, Tuple[float], np.ndarray, Tensor]\n TestClass = TypeWrapper[TestType]\n\n def setUp(self) -> None:\n self._test_list = [0, 1, 2, 3, 5]\n\n def test_int_type(self):\n int_val = TestTypes.TestClass(3)\n self.assertEqual(self._test_list[int_val], 3)\n self.assertEqual(hash(int_val), hash(3))\n int_val_other = TestTypes.TestClass(3)\n self.assertEqual(int_val, int_val_other)\n int_val_other = TestTypes.TestClass(4)\n self.assertNotEqual(int_val, int_val_other)\n\n def test_float_type(self):\n float_val = TestTypes.TestClass(3.2)\n self.assertEqual(self._test_list[float_val], 3)\n self.assertEqual(hash(float_val), hash(3.2))\n float_val_other = TestTypes.TestClass(3.2)\n self.assertEqual(float_val, float_val_other)\n float_val_other = TestTypes.TestClass(4.3)\n self.assertNotEqual(float_val, float_val_other)\n\n def test_tuple_int_type(self):\n tuple_int_val = TestTypes.TestClass((1, 2, 3))\n with self.assertRaises(ValueError):\n self._test_list[tuple_int_val] = 1\n self.assertEqual(hash(tuple_int_val), hash((1, 2, 3)))\n tuple_int_val_other = TestTypes.TestClass((1, 2, 3))\n self.assertEqual(tuple_int_val, tuple_int_val_other)\n tuple_int_val_other = TestTypes.TestClass((2, 3, 1))\n self.assertNotEqual(tuple_int_val, tuple_int_val_other)\n\n def test_tuple_float_type(self):\n tuple_float_val = TestTypes.TestClass((1.1, 2.2, 3.3))\n with self.assertRaises(ValueError):\n self._test_list[tuple_float_val] = 1\n self.assertEqual(hash(tuple_float_val), hash((1.1, 2.2, 3.3)))\n tuple_float_val_other = TestTypes.TestClass((1.1, 2.2, 3.3))\n self.assertEqual(tuple_float_val, tuple_float_val_other)\n tuple_float_val_other = TestTypes.TestClass((2.2, 3.3, 1.1))\n self.assertNotEqual(tuple_float_val, tuple_float_val_other)\n\n def test_ndarray_type(self):\n ndarray_val = TestTypes.TestClass(np.array(3))\n self.assertEqual(self._test_list[ndarray_val], 3)\n self.assertEqual(hash(ndarray_val), hash((3,)))\n ndarray_val_other = TestTypes.TestClass(np.array(3))\n self.assertEqual(ndarray_val, ndarray_val_other)\n int_val_other = TestTypes.TestClass(3)\n self.assertEqual(ndarray_val, int_val_other)\n ndarray_val_other = TestTypes.TestClass(np.array(4))\n self.assertNotEqual(ndarray_val, ndarray_val_other)\n ndarray_val = TestTypes.TestClass(np.array(((1, 2), (3, 4))))\n with self.assertRaises(ValueError):\n self._test_list[ndarray_val] = 1\n self.assertEqual(hash(ndarray_val), hash((1, 2, 3, 4)))\n ndarray_val_other = TestTypes.TestClass(((1, 2), (3, 4)))\n self.assertEqual(ndarray_val, ndarray_val_other)\n ndarray_val_other = TestTypes.TestClass(np.ndarray((1, 2, 3, 4)))\n self.assertNotEqual(ndarray_val, ndarray_val_other)\n\n def test_tensor_type(self):\n tensor_val = TestTypes.TestClass(torch.tensor(3))\n self.assertEqual(self._test_list[tensor_val], 3)\n self.assertEqual(hash(tensor_val), hash((3,)))\n tensor_val_other = TestTypes.TestClass(torch.tensor(3))\n self.assertEqual(tensor_val, tensor_val_other)\n int_val_other = TestTypes.TestClass(3)\n with self.assertRaises(TypeError):\n _ = tensor_val == int_val_other\n tensor_val_other = TestTypes.TestClass(torch.tensor(4))\n self.assertNotEqual(tensor_val, tensor_val_other)\n tensor_val = TestTypes.TestClass(torch.tensor(((1, 2), (3, 4))))\n with self.assertRaises(ValueError):\n self._test_list[tensor_val] = 1\n self.assertEqual(hash(tensor_val), hash((1, 2, 3, 4)))\n tensor_val_other = TestTypes.TestClass(torch.tensor((1, 2, 3, 4)))\n self.assertNotEqual(tensor_val, tensor_val_other)\n\n\nclass TestValues(unittest.TestCase):\n TestIntType = TypeWrapper[int]\n TestTupleFloatType = TypeWrapper[Tuple[float]]\n\n class TestIntKeyValues(Values[TestIntType]):\n def _new_key(self, k: int):\n return TestValues.TestIntType(k)\n\n class TestTupleFloatKeyValues(Values[TestTupleFloatType]):\n def _new_key(self, k: int):\n raise TypeError(\n f\"value {k} invalid for \" f\"{TestValues.TestTupleFloatType.__name__}\"\n )\n\n def setUp(self) -> None:\n self._int_float_values = TestValues.TestIntKeyValues([2.2, 4.4, 1.1, 3.3])\n self._tuple_float_float_values = TestValues.TestTupleFloatKeyValues(\n {\n TestValues.TestTupleFloatType((1.0, 2.0)): 2.2,\n TestValues.TestTupleFloatType((3.0, 4.0)): 4.4,\n TestValues.TestTupleFloatType((5.0, 6.0)): 1.1,\n TestValues.TestTupleFloatType((7.0, 8.0)): 3.3,\n }\n )\n self._int_array_values = TestValues.TestIntKeyValues(\n np.array((2.2, 4.4, 1.1, 3.3))\n )\n self._int_tensor_values = TestValues.TestIntKeyValues(\n torch.tensor((2.2, 4.4, 1.1, 3.3))\n )\n\n def test_indexing(self):\n self.assertEqual(self._int_float_values[2], 1.1)\n self.assertEqual(self._int_float_values[TestValues.TestIntType(2)], 1.1)\n self.assertEqual(\n self._tuple_float_float_values[TestValues.TestTupleFloatType((3.0, 4.0))],\n 4.4,\n )\n\n def test_sort(self):\n keys, values = self._int_float_values.sort()\n self.assertEqual(\n keys,\n [\n TestValues.TestIntType(1),\n TestValues.TestIntType(3),\n TestValues.TestIntType(0),\n TestValues.TestIntType(2),\n ],\n )\n self.assertEqual(values, [4.4, 3.3, 2.2, 1.1])\n keys, values = self._tuple_float_float_values.sort()\n self.assertEqual(\n keys,\n [\n TestValues.TestTupleFloatType((3.0, 4.0)),\n TestValues.TestTupleFloatType((7.0, 8.0)),\n TestValues.TestTupleFloatType((1.0, 2.0)),\n TestValues.TestTupleFloatType((5.0, 6.0)),\n ],\n )\n self.assertEqual(values, [4.4, 3.3, 2.2, 1.1])\n keys, values = self._int_array_values.sort()\n self.assertEqual(\n keys,\n [\n TestValues.TestIntType(1),\n TestValues.TestIntType(3),\n TestValues.TestIntType(0),\n TestValues.TestIntType(2),\n ],\n )\n self.assertTrue(np.array_equal(values, np.array([4.4, 3.3, 2.2, 1.1])))\n keys, values = self._int_tensor_values.sort()\n self.assertEqual(\n keys,\n [\n TestValues.TestIntType(1),\n TestValues.TestIntType(3),\n TestValues.TestIntType(0),\n TestValues.TestIntType(2),\n ],\n )\n self.assertTrue(torch.equal(values, torch.tensor([4.4, 3.3, 2.2, 1.1])))\n\n def test_unzip(self):\n items = self._int_float_values.items\n values = self._int_float_values.values\n self.assertEqual(\n items,\n [\n TestValues.TestIntType(0),\n TestValues.TestIntType(1),\n TestValues.TestIntType(2),\n TestValues.TestIntType(3),\n ],\n )\n self.assertEqual(values, [2.2, 4.4, 1.1, 3.3])\n items = self._tuple_float_float_values.items\n values = self._tuple_float_float_values.values\n self.assertEqual(\n items,\n [\n TestValues.TestTupleFloatType((1.0, 2.0)),\n TestValues.TestTupleFloatType((3.0, 4.0)),\n TestValues.TestTupleFloatType((5.0, 6.0)),\n TestValues.TestTupleFloatType((7.0, 8.0)),\n ],\n )\n self.assertEqual(values, [2.2, 4.4, 1.1, 3.3])\n items = self._int_array_values.items\n values = self._int_array_values.values\n self.assertEqual(\n items,\n [\n TestValues.TestIntType(0),\n TestValues.TestIntType(1),\n TestValues.TestIntType(2),\n TestValues.TestIntType(3),\n ],\n )\n self.assertTrue(np.array_equal(values, np.array([2.2, 4.4, 1.1, 3.3])))\n items = self._int_tensor_values.items\n values = self._int_tensor_values.values\n self.assertEqual(\n items,\n [\n TestValues.TestIntType(0),\n TestValues.TestIntType(1),\n TestValues.TestIntType(2),\n TestValues.TestIntType(3),\n ],\n )\n self.assertTrue(torch.equal(values, torch.tensor([2.2, 4.4, 1.1, 3.3])))\n\n def test_copy(self):\n copy = self._int_float_values.copy()\n for i, c in zip(self._int_float_values, copy):\n self.assertEqual(i, c)\n copy[1] = 2.1\n self.assertNotEqual(copy[1], self._int_float_values[1])\n copy = self._tuple_float_float_values.copy()\n for i, c in zip(self._tuple_float_float_values, copy):\n self.assertEqual(i, c)\n key = TestValues.TestTupleFloatType((3.0, 4.0))\n copy[key] = 2.1\n self.assertNotEqual(copy[key], self._tuple_float_float_values[key])\n copy = self._int_array_values.copy()\n for i, c in zip(self._int_array_values, copy):\n self.assertEqual(i, c)\n copy[1] = 2.1\n self.assertNotEqual(copy[1], self._int_array_values[1])\n copy = self._int_tensor_values.copy()\n for i, c in zip(self._int_tensor_values, copy):\n self.assertEqual(i, c)\n copy[1] = 2.1\n self.assertNotEqual(copy[1], self._int_tensor_values[1])\n\n def test_conversion(self):\n float_list_val = [1.1, 2.2, 3.3]\n tensor_val = torch.tensor([1.1, 2.2, 3.3], dtype=torch.double)\n array_val = np.array([1.1, 2.2, 3.3], dtype=np.float64)\n self.assertTrue(\n torch.equal(\n Values.to_tensor(float_list_val, dtype=torch.double), tensor_val\n )\n )\n self.assertTrue(\n torch.equal(Values.to_tensor(tensor_val, dtype=torch.double), tensor_val)\n )\n self.assertTrue(\n torch.equal(Values.to_tensor(array_val, dtype=torch.double), tensor_val)\n )\n self.assertTrue(np.array_equal(Values.to_ndarray(float_list_val), array_val))\n self.assertTrue(\n np.array_equal(Values.to_ndarray(tensor_val, dtype=np.float64), array_val)\n )\n self.assertTrue(np.array_equal(Values.to_ndarray(array_val), array_val))\n self.assertEqual(Values.to_sequence(float_list_val), float_list_val)\n self.assertEqual(Values.to_sequence(tensor_val), float_list_val)\n self.assertEqual(Values.to_sequence(array_val), float_list_val)\n\n\nclass TestDistribution(unittest.TestCase):\n class TestIntKeyDistribution(Distribution[int]):\n def _new_key(self, k: int):\n return k\n\n def setUp(self) -> None:\n self._tensor_distribution = TestDistribution.TestIntKeyDistribution(\n torch.tensor([1.0, 2.0, 3.0, 4.0])\n )\n self._array_distribution = TestDistribution.TestIntKeyDistribution(\n np.array([1.0, 2.0, 3.0, 4.0])\n )\n self._list_distribution = TestDistribution.TestIntKeyDistribution(\n [1.0, 2.0, 3.0, 4.0]\n )\n self._map_distribution = TestDistribution.TestIntKeyDistribution(\n {0: 1.0, 1: 2.0, 2: 3.0, 3: 4.0}\n )\n\n def test_values(self):\n self.assertTrue(\n torch.equal(\n self._tensor_distribution.values, torch.tensor([0.1, 0.2, 0.3, 0.4])\n )\n )\n self.assertTrue(\n np.array_equal(\n self._array_distribution.values, np.array([0.1, 0.2, 0.3, 0.4])\n )\n )\n self.assertEqual(self._list_distribution.values, [0.1, 0.2, 0.3, 0.4])\n self.assertTrue(self._map_distribution.values, [0.1, 0.2, 0.3, 0.4])\n\n def _test_sample(self, distribution: Distribution):\n counts = [0] * 4\n total = 100000\n for _ in range(total):\n counts[distribution.sample()] += 1\n self.assertAlmostEqual(counts[0] / total, 0.1, places=2)\n self.assertAlmostEqual(counts[1] / total, 0.2, places=2)\n self.assertAlmostEqual(counts[2] / total, 0.3, places=2)\n self.assertAlmostEqual(counts[3] / total, 0.4, places=2)\n\n def test_sample(self):\n self._test_sample(self._tensor_distribution)\n self.assertEqual(self._tensor_distribution.greedy(4), [3, 2, 1, 0])\n self._test_sample(self._array_distribution)\n self.assertEqual(self._array_distribution.greedy(4), [3, 2, 1, 0])\n self._test_sample(self._list_distribution)\n self.assertEqual(self._list_distribution.greedy(4), [3, 2, 1, 0])\n self._test_sample(self._map_distribution)\n self.assertEqual(self._map_distribution.greedy(4), [3, 2, 1, 0])\n\n\nif __name__ == \"__main__\":\n np.random.seed(1234)\n torch.random.manual_seed(1234)\n\n unittest.main()\n" ]
[ [ "torch.ones", "torch.zeros", "torch.full_like", "torch.distributions.Categorical", "torch.no_grad", "torch.nn.functional.one_hot", "torch.ones_like" ], [ "torch.tensor" ], [ "torch.randn_like", "torch.sum", "torch.no_grad" ], [ "numpy.random.seed", "torch.random.manual_seed", "numpy.ndarray", "torch.tensor", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tudo-sfb876/book2-plots
[ "5e49cd1ec9a5ea565a6ddb4054dbefb2544dddc8" ]
[ "inverse-problems/open_crab_sample_unfolding.py" ]
[ "from fact.io import read_h5py\nfrom fact.analysis.statistics import li_ma_significance\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom functools import lru_cache, partial\nfrom scipy.optimize import minimize\nfrom numdifftools import Hessian\n\nINVALID = np.finfo(np.float32).max\nEPS = 1e-10\n\n# mc information\nscatter_radius = 270 # Maximaler simulierter Abstand der Schauer zum Teleskope\nsample_fraction = 0.7 # Anteil des Testdatensatzer an der Gesamtzahl simulierten Schauer\narea = np.pi * scatter_radius**2\n\n# binning\nn_bins_true = 5\nn_bins_est = 10\n\ne_min_est = 700\ne_min_true = 700\ne_max_est = 15e3\ne_max_true = 15e3\n\n\n@lru_cache()\ndef C_matrix(n):\n I = np.eye(n)\n C = 2.0 * I - np.roll(I, 1) - np.roll(I, -1)\n return C\n\n\ndef llh_poisson(f_est, A, g, b):\n if np.any(f_est < 0):\n return INVALID\n\n lambda_ = A @ f_est + b\n\n return np.sum(lambda_ - g * np.log(lambda_ + EPS))\n\n\ndef tikhonov_reg(f_est, tau, effective_area):\n # we ignore under and overflow for the regularization\n C = C_matrix(len(f_est) - 2)\n\n # we regularize on the log of f with acceptance correction,\n # since only that is expected to be flat\n return tau * np.sum((C @ np.log(f_est[1:-1] / effective_area[1:-1] + EPS)) ** 2)\n\ndef llh_poisson_tikhonov(f_est, A, g, b, tau, effective_area):\n if np.any(f_est < 0):\n return INVALID\n\n return llh_poisson(f_est, A, g, b) + tikhonov_reg(f_est, tau, effective_area)\n\n\ndef mean_correlation(cov):\n cov_inv = np.linalg.inv(cov)\n return np.mean(\n np.sqrt(1 - 1 / (np.diag(cov) * np.diag(cov_inv)))\n )\n\n\ndef unfold(A, g, b, tau, a_eff):\n # allow only positive values\n bounds = [[1e-15, None] for _ in range(len(a_eff))]\n\n # uniform initial guess\n initial_guess = np.full(len(a_eff), 50)\n\n nllh = partial(\n llh_poisson_tikhonov,\n A=A, g=g, b=b,\n tau=tau, effective_area=a_eff\n )\n\n result = minimize(nllh, x0=initial_guess, bounds=bounds)\n hesse = Hessian(nllh)\n\n cov = np.linalg.inv(hesse(result.x))\n\n assert result.success\n return result.x, cov\n\n\n\nif __name__ == '__main__':\n bins_e_true = np.logspace(np.log10(e_min_true), np.log10(e_max_true), n_bins_true + 1)\n bins_e_est = np.logspace(np.log10(e_min_est), np.log10(e_max_est), n_bins_est + 1)\n bins_e_true = np.concatenate([[-np.inf], bins_e_true, [np.inf]])\n bins_e_est = np.concatenate([[-np.inf], bins_e_est, [np.inf]])\n\n bin_centers = 0.5 * (bins_e_true[1:-2] + bins_e_true[2:-1])\n bin_width = np.diff(bins_e_true)[1:-1]\n\n\n print('Reading in data')\n gammas = read_h5py('build/inverse-problems/gamma_test_dl3.hdf5', key='events', columns=[\n 'gamma_energy_prediction',\n 'gamma_prediction',\n 'theta_deg',\n 'corsika_event_header_event_number',\n 'corsika_event_header_total_energy',\n ])\n\n\n gammas_corsika = read_h5py(\n 'build/inverse-problems/gamma_corsika_headers.hdf5',\n key='corsika_events',\n columns=['total_energy'],\n )\n\n\n crab_events = read_h5py('build/inverse-problems/open_crab_sample_dl3.hdf5', key='events', columns=[\n 'gamma_prediction',\n 'gamma_energy_prediction',\n 'theta_deg',\n 'theta_deg_off_1',\n 'theta_deg_off_2',\n 'theta_deg_off_3',\n 'theta_deg_off_4',\n 'theta_deg_off_5',\n ])\n\n crab_runs = read_h5py('build/inverse-problems/open_crab_sample_dl3.hdf5', key='runs')\n\n\n print('Applying event selection')\n on_time = crab_runs['ontime'].sum()\n prediction_threshold = 0.8\n theta_cut = np.sqrt(0.025)\n\n on_query = f'gamma_prediction > {prediction_threshold} and theta_deg <= {theta_cut}'\n gammas = gammas.query(on_query).copy()\n crab_on = crab_events.query(on_query).copy()\n\n # concancenate each of the off regions\n crab_off = []\n for i in range(1, 6):\n off_query = f'gamma_prediction > {prediction_threshold} and theta_deg_off_{i} <= {theta_cut}'\n crab_off.append(crab_events.query(off_query))\n\n crab_off = pd.concat(crab_off)\n off_weights = np.full(len(crab_off), 0.2)\n\n n_on = len(crab_on)\n n_off = len(crab_off)\n\n print(f\"n_on={n_on}, n_off={n_off}, σ={li_ma_significance(n_on, n_off, 0.2):.1f}\")\n\n\n print('Calculating response')\n M, _, _ = np.histogram2d(\n gammas['gamma_energy_prediction'],\n gammas['corsika_event_header_total_energy'],\n bins=[bins_e_est, bins_e_true],\n )\n\n M = M / M.sum(axis=0)\n\n print('Calculating effective area')\n n_detected, _ = np.histogram(gammas['corsika_event_header_total_energy'], bins=bins_e_true)\n n_simulated, _ = np.histogram(gammas_corsika['total_energy'], bins=bins_e_true)\n a_eff = (n_detected / sample_fraction) / n_simulated * area\n\n\n print('Plotting response')\n fig, (ax1, ax2) = plt.subplots(1, 2)\n img = ax1.matshow(M, cmap='inferno')\n ax1.set_xlabel(r'$E$-bin')\n ax1.xaxis.set_label_position('top')\n ax1.set_ylabel(r'$\\hat{E}$-bin')\n fig.colorbar(img, ax=ax1)\n\n ax2.errorbar(bin_centers, a_eff[1:-1], xerr=bin_width / 2, linestyle='')\n ax2.set_xscale('log')\n ax2.set_yscale('log')\n ax2.set_ylabel(r'$A_\\text{eff} \\mathbin{\\si{\\meter\\squared}}')\n ax2.set_xlabel(r'$E \\mathbin{/} \\si{\\GeV}$')\n ax2.set_ylim(1e3, 1e5)\n\n fig.savefig('build/inverse-problems/fact_response.pdf')\n plt.close('all')\n\n g, _ = np.histogram(crab_on['gamma_energy_prediction'], bins=bins_e_est)\n b, _ = np.histogram(crab_off['gamma_energy_prediction'], bins=bins_e_est, weights=np.full(n_off, 0.2))\n\n print('Unfolding for many taus to find best')\n taus = np.logspace(-1.5, 1.5, 100)\n correlations = []\n results = []\n covs = []\n\n for tau in taus:\n f, cov = unfold(M, g, b, tau, a_eff)\n\n results.append(f)\n covs.append(cov)\n correlations.append(mean_correlation(cov))\n\n\n # best_index = np.argmin(np.abs(taus - 0.1))\n best_index = np.argmin(correlations)\n f = results[best_index]\n cov = covs[best_index]\n\n\n\n print('plotting best result')\n fig, ax = plt.subplots()\n ax.plot(taus, correlations, '.')\n ax.axvline(taus[best_index], color='C1')\n ax.set_xlabel(r'$\\tau$')\n ax.set_ylabel('Mean Correlation')\n ax.set_xscale('log')\n fig.savefig('build/inverse-problems/tau_vs_correlation.pdf')\n plt.close('all')\n\n\n\n norm = 1 / (a_eff[1:-1] * 1e4) / on_time / (bin_width / 1000)\n e_plot = np.logspace(2.7, 4.2, 100)\n\n fig, ax = plt.subplots()\n\n ax.plot(\n e_plot,\n 3.23e-11 * (e_plot / 1000)**(-2.47 - 0.24 * np.log10(e_plot / 1000)),\n label='MAGIC, JHEAP 2015',\n color='k'\n )\n\n ax.errorbar(\n bin_centers,\n f[1:-1] * norm,\n xerr=bin_width / 2,\n yerr=np.sqrt(np.diag(cov))[1:-1] * norm,\n ls='none',\n label='Unfolding',\n zorder=10,\n )\n\n ax.legend()\n ax.set_xlabel('E / GeV')\n ax.set_ylabel('Flux / (cm⁻² s⁻¹ GeV⁻¹)')\n ax.set_yscale('log')\n ax.set_xscale('log')\n fig.savefig('build/inverse-problems/fact_unfolding.pdf')\n" ]
[ [ "numpy.diag", "numpy.sqrt", "numpy.concatenate", "numpy.argmin", "numpy.any", "numpy.histogram", "numpy.roll", "numpy.eye", "numpy.finfo", "numpy.full", "numpy.diff", "matplotlib.pyplot.close", "pandas.concat", "numpy.log", "numpy.linalg.inv", "numpy.logspace", "numpy.log10", "scipy.optimize.minimize", "numpy.histogram2d", "matplotlib.pyplot.subplots" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] } ]
eighttails/kraken
[ "6e3b7d6e86d673acf5633e6e23292cb82f1a114e", "6e3b7d6e86d673acf5633e6e23292cb82f1a114e" ]
[ "tests/test_layers.py", "kraken/pageseg.py" ]
[ "# -*- coding: utf-8 -*-\nimport unittest\n\nfrom nose.tools import raises\n\nimport torch\nfrom kraken.lib import layers\n\n\nclass TestLayers(unittest.TestCase):\n\n \"\"\"\n Testing custom layer implementations.\n \"\"\"\n def setUp(self):\n torch.set_grad_enabled(False)\n\n def test_maxpool(self):\n \"\"\"\n Test maximum pooling layer.\n \"\"\"\n mp = layers.MaxPool((3, 3), (2, 2))\n o = mp(torch.randn(1, 2, 32, 64))\n self.assertEqual(o.shape, (1, 2, 15, 31))\n\n def test_1d_dropout(self):\n \"\"\"\n Test 1d dropout layer.\n \"\"\"\n do = layers.Dropout(0.2, 1)\n o = do(torch.randn(1, 2, 32, 64))\n self.assertEqual(o.shape, (1, 2, 32, 64))\n\n def test_2d_dropout(self):\n \"\"\"\n Test 2d dropout layer.\n \"\"\"\n do = layers.Dropout(0.2, 2)\n o = do(torch.randn(1, 2, 32, 64))\n self.assertEqual(o.shape, (1, 2, 32, 64))\n\n def test_forward_rnn_layer_x(self):\n \"\"\"\n Test unidirectional RNN layer in x-dimension.\n \"\"\"\n rnn = layers.TransposedSummarizingRNN(10, 2, 'f', False, False)\n o = rnn(torch.randn(1, 10, 32, 64))\n self.assertEqual(o.shape, (1, 2, 32, 64))\n\n def test_forward_rnn_layer_y(self):\n \"\"\"\n Test unidirectional RNN layer in y-dimension.\n \"\"\"\n rnn = layers.TransposedSummarizingRNN(10, 2, 'f', True, False)\n o = rnn(torch.randn(1, 10, 32, 64))\n self.assertEqual(o.shape, (1, 2, 32, 64))\n\n def test_forward_rnn_layer_x_summarize(self):\n \"\"\"\n Test unidirectional summarizing RNN layer in x-dimension.\n \"\"\"\n rnn = layers.TransposedSummarizingRNN(10, 2, 'f', False, True)\n o = rnn(torch.randn(1, 10, 32, 64))\n self.assertEqual(o.shape, (1, 2, 32, 1))\n\n def test_forward_rnn_layer_y_summarize(self):\n \"\"\"\n Test unidirectional summarizing RNN layer in y-dimension.\n \"\"\"\n rnn = layers.TransposedSummarizingRNN(10, 2, 'f', True, True)\n o = rnn(torch.randn(1, 10, 32, 64))\n self.assertEqual(o.shape, (1, 2, 1, 64))\n\n def test_bidi_rnn_layer_x(self):\n \"\"\"\n Test bidirectional RNN layer in x-dimension.\n \"\"\"\n rnn = layers.TransposedSummarizingRNN(10, 2, 'b', False, False)\n o = rnn(torch.randn(1, 10, 32, 64))\n self.assertEqual(o.shape, (1, 4, 32, 64))\n\n def test_bidi_rnn_layer_y(self):\n \"\"\"\n Test bidirectional RNN layer in y-dimension.\n \"\"\"\n rnn = layers.TransposedSummarizingRNN(10, 2, 'b', True, False)\n o = rnn(torch.randn(1, 10, 32, 64))\n self.assertEqual(o.shape, (1, 4, 32, 64))\n\n def test_bidi_rnn_layer_x_summarize(self):\n \"\"\"\n Test bidirectional summarizing RNN layer in x-dimension.\n \"\"\"\n rnn = layers.TransposedSummarizingRNN(10, 2, 'b', False, True)\n o = rnn(torch.randn(1, 10, 32, 64))\n self.assertEqual(o.shape, (1, 4, 32, 1))\n\n def test_bidi_rnn_layer_y_summarize(self):\n \"\"\"\n Test bidirectional summarizing RNN layer in y-dimension.\n \"\"\"\n rnn = layers.TransposedSummarizingRNN(10, 2, 'b', True, True)\n o = rnn(torch.randn(1, 10, 32, 64))\n self.assertEqual(o.shape, (1, 4, 1, 64))\n\n def test_linsoftmax(self):\n \"\"\"\n Test basic function of linear layer.\n \"\"\"\n lin = layers.LinSoftmax(20, 10)\n o = lin(torch.randn(1, 20, 12, 24))\n self.assertEqual(o.shape, (1, 10, 12, 24))\n\n def test_linsoftmax_train(self):\n \"\"\"\n Test function of linear layer in training mode (log_softmax)\n \"\"\"\n lin = layers.LinSoftmax(20, 10).train()\n o = lin(torch.randn(1, 20, 12, 24))\n self.assertLess(o.max(), 0)\n\n def test_linsoftmax_test(self):\n \"\"\"\n Test function of linear layer in eval mode (softmax)\n \"\"\"\n lin = layers.LinSoftmax(20, 10).eval()\n o = lin(torch.randn(1, 20, 12, 24))\n self.assertGreaterEqual(o.min(), 0)\n\n def test_linsoftmax_aug(self):\n \"\"\"\n Test basic function of linear layer with 1-augmentation.\n \"\"\"\n lin = layers.LinSoftmax(20, 10, True)\n o = lin(torch.randn(1, 20, 12, 24))\n self.assertEqual(o.shape, (1, 10, 12, 24))\n\n def test_linsoftmax_aug_train(self):\n \"\"\"\n Test function of linear layer in training mode (log_softmax) with 1-augmentation\n \"\"\"\n lin = layers.LinSoftmax(20, 10, True).train()\n o = lin(torch.randn(1, 20, 12, 24))\n self.assertLess(o.max(), 0)\n\n def test_linsoftmax_aug_test(self):\n \"\"\"\n Test function of linear layer in eval mode (softmax) with 1-augmentation\n \"\"\"\n lin = layers.LinSoftmax(20, 10, True).eval()\n o = lin(torch.randn(1, 20, 12, 24))\n self.assertGreaterEqual(o.min(), 0)\n\n def test_actconv2d_lin(self):\n \"\"\"\n Test convolutional layer without activation.\n \"\"\"\n conv = layers.ActConv2D(5, 12, (3, 3), (1, 1), 'l')\n o = conv(torch.randn(1, 5, 24, 12))\n self.assertEqual(o.shape, (1, 12, 24, 12))\n\n def test_actconv2d_sigmoid(self):\n \"\"\"\n Test convolutional layer with sigmoid activation.\n \"\"\"\n conv = layers.ActConv2D(5, 12, (3, 3), (1, 1), 's')\n o = conv(torch.randn(1, 5, 24, 12))\n self.assertTrue(0 <= o.min() <= 1)\n self.assertTrue(0 <= o.max() <= 1)\n\n def test_actconv2d_tanh(self):\n \"\"\"\n Test convolutional layer with tanh activation.\n \"\"\"\n conv = layers.ActConv2D(5, 12, (3, 3), (1, 1), 't')\n o = conv(torch.randn(1, 5, 24, 12))\n self.assertTrue(-1 <= o.min() <= 1)\n self.assertTrue(-1 <= o.max() <= 1)\n\n def test_actconv2d_softmax(self):\n \"\"\"\n Test convolutional layer with softmax activation.\n \"\"\"\n conv = layers.ActConv2D(5, 12, (3, 3), (1, 1), 'm')\n o = conv(torch.randn(1, 5, 24, 12))\n self.assertTrue(0 <= o.min() <= 1)\n self.assertTrue(0 <= o.max() <= 1)\n\n def test_actconv2d_relu(self):\n \"\"\"\n Test convolutional layer with relu activation.\n \"\"\"\n conv = layers.ActConv2D(5, 12, (3, 3), (1, 1), 'r')\n o = conv(torch.randn(1, 5, 24, 12))\n self.assertLessEqual(0, o.min())\n self.assertLessEqual(0, o.max())\n", "# -*- coding: utf-8 -*-\n#\n# Copyright 2015 Benjamin Kiessling\n# 2014 Thomas M. Breuel\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\n# or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\"\"\"\nkraken.pageseg\n~~~~~~~~~~~~~~\n\nLayout analysis and script detection methods.\n\"\"\"\nfrom itertools import groupby\n\nimport json\nimport logging\nimport numpy as np\nimport pkg_resources\n\nfrom typing import Tuple, List, Callable, Optional, Dict, Any\nfrom scipy.ndimage.filters import (gaussian_filter, uniform_filter,\n maximum_filter)\n\nfrom kraken.lib import models\nfrom kraken.lib import morph, sl\nfrom kraken.lib.util import pil2array, is_bitonal, get_im_str\nfrom kraken.lib.exceptions import KrakenInputException\nfrom kraken.lib.segmentation import reading_order, topsort\n\nfrom kraken.rpred import rpred\nfrom kraken.serialization import max_bbox\n\n__all__ = ['segment']\n\nlogger = logging.getLogger(__name__)\n\n\nclass record(object):\n \"\"\"\n Simple dict-like object.\n \"\"\"\n def __init__(self, **kw):\n self.__dict__.update(kw)\n self.label = 0 # type: int\n self.bounds = [] # type: List\n self.mask = None # type: np.array\n\n\ndef find(condition):\n \"Return the indices where ravel(condition) is true\"\n res, = np.nonzero(np.ravel(condition))\n return res\n\n\ndef binary_objects(binary: np.array) -> np.array:\n \"\"\"\n Labels features in an array and segments them into objects.\n \"\"\"\n labels, _ = morph.label(binary)\n objects = morph.find_objects(labels)\n return objects\n\n\ndef estimate_scale(binary: np.array) -> float:\n \"\"\"\n Estimates image scale based on number of connected components.\n \"\"\"\n objects = binary_objects(binary)\n bysize = sorted(objects, key=sl.area)\n scalemap = np.zeros(binary.shape)\n for o in bysize:\n if np.amax(scalemap[o]) > 0:\n continue\n scalemap[o] = sl.area(o)**0.5\n scale = np.median(scalemap[(scalemap > 3) & (scalemap < 100)])\n return scale\n\n\ndef compute_boxmap(binary: np.array, scale: float,\n threshold: Tuple[float, int] = (.5, 4),\n dtype: str = 'i') -> np.array:\n \"\"\"\n Returns grapheme cluster-like boxes based on connected components.\n \"\"\"\n objects = binary_objects(binary)\n bysize = sorted(objects, key=sl.area)\n boxmap = np.zeros(binary.shape, dtype)\n for o in bysize:\n if sl.area(o)**.5 < threshold[0]*scale:\n continue\n if sl.area(o)**.5 > threshold[1]*scale:\n continue\n boxmap[o] = 1\n return boxmap\n\n\ndef compute_lines(segmentation, scale):\n \"\"\"Given a line segmentation map, computes a list\n of tuples consisting of 2D slices and masked images.\"\"\"\n logger.debug('Convert segmentation to lines')\n lobjects = morph.find_objects(segmentation)\n lines = []\n for i, o in enumerate(lobjects):\n if o is None:\n continue\n if sl.dim1(o) < 2*scale or sl.dim0(o) < scale:\n continue\n mask = (segmentation[o] == i+1)\n if np.amax(mask) == 0:\n continue\n result = record()\n result.label = i+1\n result.bounds = o\n result.mask = mask\n lines.append(result)\n return lines\n\n\ndef compute_separators_morph(binary: np.array, scale: float, sepwiden: int = 10, maxcolseps: int = 2) -> np.array:\n \"\"\"Finds vertical black lines corresponding to column separators.\"\"\"\n logger.debug('Finding vertical black column lines')\n d0 = int(max(5, scale/4))\n d1 = int(max(5, scale)) + sepwiden\n thick = morph.r_dilation(binary, (d0, d1))\n vert = morph.rb_opening(thick, (10*scale, 1))\n vert = morph.r_erosion(vert, (d0//2, sepwiden))\n vert = morph.select_regions(vert, sl.dim1, min=3, nbest=2*maxcolseps)\n vert = morph.select_regions(vert, sl.dim0, min=20*scale, nbest=maxcolseps)\n return vert\n\n\ndef compute_colseps_conv(binary: np.array, scale: float = 1.0,\n minheight: int = 10, maxcolseps: int = 2) -> np.array:\n \"\"\"Find column separators by convolution and thresholding.\n\n Args:\n binary (numpy.array):\n scale (float):\n minheight (int):\n maxcolseps (int):\n\n Returns:\n Separators\n \"\"\"\n logger.debug('Finding column separators')\n # find vertical whitespace by thresholding\n smoothed = gaussian_filter(1.0*binary, (scale, scale*0.5))\n smoothed = uniform_filter(smoothed, (5.0*scale, 1))\n thresh = (smoothed < np.amax(smoothed)*0.1)\n # find column edges by filtering\n grad = gaussian_filter(1.0*binary, (scale, scale*0.5), order=(0, 1))\n grad = uniform_filter(grad, (10.0*scale, 1))\n grad = (grad > 0.5*np.amax(grad))\n # combine edges and whitespace\n seps = np.minimum(thresh, maximum_filter(grad, (int(scale), int(5*scale))))\n seps = maximum_filter(seps, (int(2*scale), 1))\n # select only the biggest column separators\n seps = morph.select_regions(seps, sl.dim0, min=minheight*scale,\n nbest=maxcolseps)\n return seps\n\n\ndef compute_black_colseps(binary: np.array, scale: float, maxcolseps: int) -> Tuple[np.array, np.array]:\n \"\"\"\n Computes column separators from vertical black lines.\n\n Args:\n binary (numpy.array): Numpy array of the binary image\n scale (float):\n\n Returns:\n (colseps, binary):\n \"\"\"\n logger.debug('Extract vertical black column separators from lines')\n seps = compute_separators_morph(binary, scale, maxcolseps)\n colseps = np.maximum(compute_colseps_conv(binary, scale, maxcolseps), seps)\n binary = np.minimum(binary, 1-seps)\n return colseps, binary\n\n\ndef compute_white_colseps(binary: np.array, scale: float, maxcolseps: int) -> Tuple[np.array, np.array]:\n \"\"\"\n Computes column separators either from vertical black lines or whitespace.\n\n Args:\n binary (numpy.array): Numpy array of the binary image\n scale (float):\n\n Returns:\n colseps:\n \"\"\"\n return compute_colseps_conv(binary, scale, maxcolseps)\n\n\ndef norm_max(v: np.array) -> np.array:\n \"\"\"\n Normalizes the input array by maximum value.\n \"\"\"\n return v/np.amax(v)\n\n\ndef compute_gradmaps(binary: np.array, scale: float, gauss: bool = False):\n \"\"\"\n Use gradient filtering to find baselines\n\n Args:\n binary (numpy.array):\n scale (float):\n gauss (bool): Use gaussian instead of uniform filtering\n\n Returns:\n (bottom, top, boxmap)\n \"\"\"\n # use gradient filtering to find baselines\n logger.debug('Computing gradient maps')\n boxmap = compute_boxmap(binary, scale)\n cleaned = boxmap*binary\n if gauss:\n grad = gaussian_filter(1.0*cleaned, (0.3*scale, 6*scale), order=(1, 0))\n else:\n grad = gaussian_filter(1.0*cleaned, (max(4, 0.3*scale),\n scale), order=(1, 0))\n grad = uniform_filter(grad, (1, 6*scale))\n bottom = norm_max((grad < 0)*(-grad))\n top = norm_max((grad > 0)*grad)\n return bottom, top, boxmap\n\n\ndef compute_line_seeds(binary: np.array, bottom: np.array, top: np.array,\n colseps: np.array, scale: float, threshold: float = 0.2) -> np.array:\n \"\"\"\n Base on gradient maps, computes candidates for baselines and xheights.\n Then, it marks the regions between the two as a line seed.\n \"\"\"\n logger.debug('Finding line seeds')\n vrange = int(scale)\n bmarked = maximum_filter(bottom == maximum_filter(bottom, (vrange, 0)),\n (2, 2))\n bmarked = bmarked * (bottom > threshold*np.amax(bottom)*threshold)*(1-colseps)\n tmarked = maximum_filter(top == maximum_filter(top, (vrange, 0)), (2, 2))\n tmarked = tmarked * (top > threshold*np.amax(top)*threshold/2)*(1-colseps)\n tmarked = maximum_filter(tmarked, (1, 20))\n seeds = np.zeros(binary.shape, 'i')\n delta = max(3, int(scale/2))\n for x in range(bmarked.shape[1]):\n transitions = sorted([(y, 1) for y in find(bmarked[:, x])] +\n [(y, 0) for y in find(tmarked[:, x])])[::-1]\n transitions += [(0, 0)]\n for l in range(len(transitions)-1):\n y0, s0 = transitions[l]\n if s0 == 0:\n continue\n seeds[y0-delta:y0, x] = 1\n y1, s1 = transitions[l+1]\n if s1 == 0 and (y0-y1) < 5*scale:\n seeds[y1:y0, x] = 1\n seeds = maximum_filter(seeds, (1, int(1+scale)))\n seeds = seeds * (1-colseps)\n seeds, _ = morph.label(seeds)\n return seeds\n\n\ndef remove_hlines(binary: np.array, scale: float, maxsize: int = 10) -> np.array:\n \"\"\"\n Removes horizontal black lines that only interfere with page segmentation.\n\n Args:\n binary (numpy.array):\n scale (float):\n maxsize (int): maximum size of removed lines\n\n Returns:\n numpy.array containing the filtered image.\n\n \"\"\"\n logger.debug('Filtering horizontal lines')\n labels, _ = morph.label(binary)\n objects = morph.find_objects(labels)\n for i, b in enumerate(objects):\n if sl.width(b) > maxsize*scale:\n labels[b][labels[b] == i+1] = 0\n return np.array(labels != 0, 'B')\n\n\ndef rotate_lines(lines: np.array, angle: float, offset: int) -> np.array:\n \"\"\"\n Rotates line bounding boxes around the origin and adding and offset.\n \"\"\"\n logger.debug(f'Rotate line coordinates by {angle} with offset {offset}')\n angle = np.radians(angle)\n r = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])\n p = np.array(lines).reshape((-1, 2))\n offset = np.array([2*offset])\n p = p.dot(r).reshape((-1, 4)).astype(int) + offset\n x = np.sort(p[:, [0, 2]])\n y = np.sort(p[:, [1, 3]])\n return np.column_stack((x.flatten(), y.flatten())).reshape(-1, 4)\n\n\ndef segment(im, text_direction: str = 'horizontal-lr',\n scale: Optional[float] = None,\n maxcolseps: float = 2,\n black_colseps: bool = False,\n no_hlines: bool = True,\n pad: int = 0,\n mask: Optional[np.array] = None,\n reading_order_fn: Callable = reading_order) -> Dict[str, Any]:\n \"\"\"\n Segments a page into text lines.\n\n Segments a page into text lines and returns the absolute coordinates of\n each line in reading order.\n\n Args:\n im (PIL.Image): A bi-level page of mode '1' or 'L'\n text_direction (str): Principal direction of the text\n (horizontal-lr/rl/vertical-lr/rl)\n scale (float): Scale of the image\n maxcolseps (int): Maximum number of whitespace column separators\n black_colseps (bool): Whether column separators are assumed to be\n vertical black lines or not\n no_hlines (bool): Switch for horizontal line removal\n pad (int or tuple): Padding to add to line bounding boxes. If int the\n same padding is used both left and right. If a\n 2-tuple, uses (padding_left, padding_right).\n mask (PIL.Image): A bi-level mask image of the same size as `im` where\n 0-valued regions are ignored for segmentation\n purposes. Disables column detection.\n reading_order_fn (Callable): Function to call to order line output.\n Callable accepting a list of slices (y, x)\n and a text direction in (`rl`, `lr`).\n\n Returns:\n {'text_direction': '$dir', 'boxes': [(x1, y1, x2, y2),...]}: A\n dictionary containing the text direction and a list of reading order\n sorted bounding boxes under the key 'boxes'.\n\n Raises:\n KrakenInputException if the input image is not binarized or the text\n direction is invalid.\n \"\"\"\n im_str = get_im_str(im)\n logger.info(f'Segmenting {im_str}')\n\n if im.mode != '1' and not is_bitonal(im):\n logger.error(f'Image {im_str} is not bi-level')\n raise KrakenInputException(f'Image {im_str} is not bi-level')\n\n # rotate input image for vertical lines\n if text_direction.startswith('horizontal'):\n angle = 0\n offset = (0, 0)\n elif text_direction == 'vertical-lr':\n angle = 270\n offset = (0, im.size[1])\n elif text_direction == 'vertical-rl':\n angle = 90\n offset = (im.size[0], 0)\n else:\n logger.error(f'Invalid text direction \\'{text_direction}\\'')\n raise KrakenInputException(f'Invalid text direction {text_direction}')\n\n logger.debug(f'Rotating input image by {angle} degrees')\n im = im.rotate(angle, expand=True)\n\n a = pil2array(im)\n binary = np.array(a > 0.5*(np.amin(a) + np.amax(a)), 'i')\n binary = 1 - binary\n\n if not scale:\n scale = estimate_scale(binary)\n\n if no_hlines:\n binary = remove_hlines(binary, scale)\n # emptyish images wll cause exceptions here.\n\n try:\n if mask:\n if mask.mode != '1' and not is_bitonal(mask):\n logger.error('Mask is not bitonal')\n raise KrakenInputException('Mask is not bitonal')\n mask = mask.convert('1')\n if mask.size != im.size:\n logger.error(f'Mask size {mask.size} doesn\\'t match image size {im.size}')\n raise KrakenInputException(f'Mask size {mask.size} doesn\\'t match image size {im.size}')\n logger.info('Masking enabled in segmenter. Disabling column detection.')\n mask = mask.rotate(angle, expand=True)\n colseps = pil2array(mask)\n elif black_colseps:\n colseps, binary = compute_black_colseps(binary, scale, maxcolseps)\n else:\n colseps = compute_white_colseps(binary, scale, maxcolseps)\n except ValueError:\n logger.warning(f'Exception in column finder (probably empty image) for {im_str}')\n return {'text_direction': text_direction, 'boxes': []}\n\n bottom, top, boxmap = compute_gradmaps(binary, scale)\n seeds = compute_line_seeds(binary, bottom, top, colseps, scale)\n llabels = morph.propagate_labels(boxmap, seeds, conflict=0)\n spread = morph.spread_labels(seeds, maxdist=scale)\n llabels = np.where(llabels > 0, llabels, spread*binary)\n segmentation = llabels*binary\n\n lines = compute_lines(segmentation, scale)\n order = reading_order_fn([l.bounds for l in lines], text_direction[-2:])\n lsort = topsort(order)\n lines = [lines[i].bounds for i in lsort]\n lines = [(s2.start, s1.start, s2.stop, s1.stop) for s1, s2 in lines]\n\n if isinstance(pad, int):\n pad = (pad, pad)\n lines = [(max(x[0]-pad[0], 0), x[1], min(x[2]+pad[1], im.size[0]), x[3]) for x in lines]\n\n return {'text_direction': text_direction, 'boxes': rotate_lines(lines, 360-angle, offset).tolist(), 'script_detection': False}\n" ]
[ [ "torch.randn", "torch.set_grad_enabled" ], [ "numpy.amax", "scipy.ndimage.filters.maximum_filter", "numpy.minimum", "numpy.radians", "numpy.amin", "numpy.median", "numpy.ravel", "numpy.cos", "numpy.sort", "numpy.sin", "scipy.ndimage.filters.gaussian_filter", "scipy.ndimage.filters.uniform_filter", "numpy.array", "numpy.zeros", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "0.15", "1.4", "0.10", "1.3", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16" ], "tensorflow": [] } ]
robvincen/robot_gradet
[ "a39e3c772c72806dfc99e4d24d8787e0d1bdeef5" ]
[ "models/dense_attention.py" ]
[ "import torch\r\nimport math\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\n\r\nclass DenseAttenGraspNet(nn.Module):\r\n\r\n def __init__(self, input_channels=1, dropout=False, prob=0.0, bottleneck=True):\r\n super(DenseAttenGraspNet, self).__init__()\r\n\r\n if bottleneck == True:\r\n block = BottleneckBlock\r\n else:\r\n block = BasicBlock\r\n\r\n self.conv1 = nn.Conv2d(input_channels, 32, kernel_size=9, stride=3, padding=3)\r\n self.bn1 = nn.BatchNorm2d(32)\r\n\r\n self.conv2 = nn.Conv2d(32, 64, kernel_size=5, stride=2, padding=2)\r\n self.bn2 = nn.BatchNorm2d(64)\r\n\r\n self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1)\r\n self.bn3 = nn.BatchNorm2d(128)\r\n\r\n nb_layers = 16 # 16 layers can be much more now the best is 16\r\n input_channels = 128\r\n growth_rate = 24 # 12 now the best is 24\r\n self.block = DenseBlock(block, nb_layers=nb_layers, input_channels=input_channels, growth_rate=growth_rate, dropRate=prob)\r\n\r\n self.change_channel = nn.Conv2d(input_channels + nb_layers * growth_rate, 128, kernel_size=1)\r\n\r\n self.channel_attention1 = ChannelAttention(in_planes=128)\r\n self.spatial_attention1 = SpatialAttention()\r\n\r\n # self.gam_attention1 = GAM_Attention(128, 128)\r\n\r\n self.attention1 = Self_Attn(128)\r\n\r\n self.conv4 = nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1, output_padding=1)\r\n self.bn4 = nn.BatchNorm2d(64)\r\n self.attention2 = Self_Attn(64)\r\n\r\n self.channel_attention2 = ChannelAttention(in_planes=64)\r\n self.spatial_attention2 = SpatialAttention()\r\n\r\n # self.gam_attention2 = GAM_Attention(64, 64)\r\n\r\n\r\n self.conv5 = nn.ConvTranspose2d(64, 32, kernel_size=5, stride=2, padding=2, output_padding=1)\r\n self.bn5 = nn.BatchNorm2d(32)\r\n self.attention3 = Self_Attn(32)\r\n\r\n self.channel_attention3 = ChannelAttention(in_planes=32)\r\n self.spatial_attention3 = SpatialAttention()\r\n\r\n # self.gam_attention3 = GAM_Attention(32, 32)\r\n\r\n\r\n self.conv6 = nn.ConvTranspose2d(32, 32, kernel_size=9, stride=3, padding=3, output_padding=1)\r\n\r\n self.pos_output = nn.Conv2d(32, 1, kernel_size=2)\r\n self.cos_output = nn.Conv2d(32, 1, kernel_size=2)\r\n self.sin_output = nn.Conv2d(32, 1, kernel_size=2)\r\n self.width_output = nn.Conv2d(32, 1, kernel_size=2)\r\n\r\n self.dropout1 = nn.Dropout(p=prob)\r\n\r\n for m in self.modules():\r\n if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d)):\r\n nn.init.xavier_uniform_(m.weight, gain=1)\r\n\r\n def forward(self, x_in):\r\n x = F.relu(self.bn1(self.conv1(x_in)))\r\n query_x3 = x\r\n #100 * 100\r\n x = F.relu(self.bn2(self.conv2(x)))\r\n query_x2 = x\r\n #50 * 50\r\n x = F.relu(self.bn3(self.conv3(x)))\r\n query_x1 = x\r\n #25 * 25\r\n x = F.relu(self.block(x))\r\n x = F.relu(self.change_channel(x))\r\n # attention_x1 = self.attention1(x)\r\n channel_x = F.relu(self.channel_attention1(x))\r\n spatial_x = F.relu(self.spatial_attention1(query_x1))\r\n x = torch.add(channel_x, spatial_x)\r\n # x = F.relu(self.gam_attention1(x))\r\n #25 * 25\r\n # x = F.relu(self.bn4(self.conv4(attention_x1)))\r\n x = F.relu(self.bn4(self.conv4(x)))\r\n channel_x = F.relu(self.channel_attention2(x))\r\n spatial_x = F.relu(self.spatial_attention2(query_x2))\r\n x = torch.add(channel_x, spatial_x)\r\n # x = F.relu(self.gam_attention2(x))\r\n\r\n # attention_x2 = F.relu(self.attention2(x))\r\n # attention_x2 = self.attention2(x)\r\n #50 * 50\r\n x = F.relu(self.bn5(self.conv5(x)))\r\n # attention_x3 = F.relu(self.attention3(x, query_x3))\r\n # attention_x3 = self.attention3(x)\r\n channel_x = F.relu(self.channel_attention3(x))\r\n spatial_x = F.relu(self.spatial_attention3(query_x3))\r\n x = torch.add(channel_x, spatial_x)\r\n # x = F.relu(self.gam_attention3(x))\r\n\r\n #100 * 100\r\n x = self.conv6(x)\r\n\r\n pos_output = self.pos_output(self.dropout1(x))\r\n cos_output = self.cos_output(self.dropout1(x))\r\n sin_output = self.sin_output(self.dropout1(x))\r\n width_output = self.width_output(self.dropout1(x))\r\n\r\n return pos_output, cos_output, sin_output, width_output\r\n\r\n def compute_loss(self, xc, yc):\r\n y_pos, y_cos, y_sin, y_width = yc\r\n pos_pred, cos_pred, sin_pred, width_pred = self(xc)\r\n\r\n p_loss = F.mse_loss(pos_pred, y_pos)\r\n cos_loss = F.mse_loss(cos_pred, y_cos)\r\n sin_loss = F.mse_loss(sin_pred, y_sin)\r\n width_loss = F.mse_loss(width_pred, y_width)\r\n # p_loss = F.smooth_l1_loss(pos_pred, y_pos)\r\n # cos_loss = F.smooth_l1_loss(cos_pred, y_cos)\r\n # sin_loss = F.smooth_l1_loss(sin_pred, y_sin)\r\n # width_loss = F.smooth_l1_loss(width_pred, y_width)\r\n\r\n return {\r\n 'loss': p_loss + cos_loss + sin_loss + width_loss,\r\n 'losses': {\r\n 'p_loss': p_loss,\r\n 'cos_loss': cos_loss,\r\n 'sin_loss': sin_loss,\r\n 'width_loss': width_loss\r\n },\r\n 'pred': {\r\n 'pos': pos_pred,\r\n 'cos': cos_pred,\r\n 'sin': sin_pred,\r\n 'width': width_pred\r\n }\r\n }\r\n\r\nclass BasicBlock(nn.Module):\r\n def __init__(self, input_channels, output_channels, dropRate=0.0):\r\n super(BasicBlock, self).__init__()\r\n self.bn1 = nn.BatchNorm2d(input_channels)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.conv1 = nn.Conv2d(input_channels, output_channels, kernel_size=3, stride=1,\r\n padding=1, bias=False)\r\n self.droprate = dropRate\r\n def forward(self, x):\r\n out = self.conv1(self.relu(self.bn1(x)))\r\n if self.droprate > 0:\r\n out = F.dropout(out, p=self.droprate, training=self.training)\r\n return torch.cat([x, out], 1)\r\n\r\nclass BottleneckBlock(nn.Module):\r\n def __init__(self, input_channels, output_channels, dropRate=0.0):\r\n super(BottleneckBlock, self).__init__()\r\n inter_planes = output_channels * 4\r\n self.bn1 = nn.BatchNorm2d(input_channels)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.conv1 = nn.Conv2d(input_channels, inter_planes, kernel_size=1, stride=1,\r\n padding=0, bias=False)\r\n self.bn2 = nn.BatchNorm2d(inter_planes)\r\n self.conv2 = nn.Conv2d(inter_planes, output_channels, kernel_size=3, stride=1,\r\n padding=1, bias=False)\r\n self.droprate = dropRate\r\n def forward(self, x):\r\n out = self.conv1(self.relu(self.bn1(x)))\r\n if self.droprate > 0:\r\n out = F.dropout(out, p=self.droprate, inplace=False, training=self.training)\r\n out = self.conv2(self.relu(self.bn2(out)))\r\n if self.droprate > 0:\r\n out = F.dropout(out, p=self.droprate, inplace=False, training=self.training)\r\n return torch.cat([x, out], 1)\r\n\r\nclass DenseBlock(nn.Module):\r\n def __init__(self, block, nb_layers=8, input_channels=128, growth_rate=16, dropRate=0.0):\r\n super(DenseBlock, self).__init__()\r\n self.layer = self._make_layer(block, input_channels, growth_rate, nb_layers, dropRate)\r\n def _make_layer(self, block, input_channels, growth_rate, nb_layers, dropRate):\r\n layers = []\r\n for i in range(nb_layers):\r\n layers.append(block(input_channels+i*growth_rate, growth_rate, dropRate))\r\n return nn.Sequential(*layers)\r\n def forward(self, x):\r\n return self.layer(x)\r\n\r\n\r\nclass Self_Attn(nn.Module):\r\n \"\"\" Self attention Layer\"\"\"\r\n\r\n def __init__(self, in_dim):\r\n super(Self_Attn, self).__init__()\r\n self.channel_in = in_dim\r\n\r\n self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8, kernel_size=1)\r\n self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim // 8, kernel_size=1)\r\n self.value_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim, kernel_size=1)\r\n self.gamma = nn.Parameter(torch.zeros(1))\r\n\r\n self.softmax = nn.Softmax(dim=-1)\r\n # self.sigmoid = nn.Sigmoid()\r\n\r\n def forward(self, x_input):\r\n \"\"\"\r\n inputs :\r\n x_input : input feature maps( B X C X W X H)\r\n returns :\r\n out : self attention value + input feature\r\n attention: B X N X N (N is Width*Height)\r\n \"\"\"\r\n m_batchsize, C, width, height = x_input.size()\r\n proj_query = self.query_conv(x_input).view(m_batchsize, -1, width * height).permute(0, 2, 1) # B X CX(N)\r\n proj_key = self.key_conv(x_input).view(m_batchsize, -1, width * height) # B X C x (*W*H)\r\n energy = torch.bmm(proj_query, proj_key) # transpose check\r\n attention = self.softmax(energy) # BX (N) X (N)\r\n # attention = self.sigmoid(energy) # BX (N) X (N)\r\n proj_value = self.value_conv(x_input).view(m_batchsize, -1, width * height) # B X C X N\r\n\r\n out = torch.bmm(proj_value, attention.permute(0, 2, 1))\r\n out = out.view(m_batchsize, C, width, height)\r\n\r\n # out = out + x_input\r\n # out = self.gamma * out + x_input\r\n out = self.gamma * out\r\n # return out, attention\r\n return out\r\n\r\n\r\n\r\nclass Attention(nn.Module):\r\n \"\"\" Self attention Layer\"\"\"\r\n\r\n def __init__(self, key_in_dim, query_in_dim):\r\n super(Attention, self).__init__()\r\n self.key_channel_in = key_in_dim\r\n self.query_channel_in = query_in_dim\r\n\r\n self.query_conv = nn.Conv2d(in_channels=query_in_dim, out_channels=query_in_dim // 8, kernel_size=1)\r\n self.key_conv = nn.Conv2d(in_channels=key_in_dim, out_channels=key_in_dim // 8, kernel_size=1)\r\n self.value_conv = nn.Conv2d(in_channels=key_in_dim, out_channels=key_in_dim, kernel_size=1)\r\n self.gamma = nn.Parameter(torch.zeros(1))\r\n\r\n self.softmax = nn.Softmax(dim=-1) #\r\n\r\n def forward(self, x_input, x_query):\r\n \"\"\"\r\n inputs :\r\n x : input feature maps( B X C X W X H)\r\n returns :\r\n out : self attention value + input feature\r\n attention: B X N X N (N is Width*Height)\r\n \"\"\"\r\n m_batchsize, C, width, height = x_input.size()\r\n proj_query = self.query_conv(x_query).view(m_batchsize, -1, width * height).permute(0, 2, 1) # B X CX(N)\r\n proj_key = self.key_conv(x_input).view(m_batchsize, -1, width * height) # B X C x (*W*H)\r\n energy = torch.bmm(proj_query, proj_key) # transpose check\r\n attention = self.softmax(energy) # BX (N) X (N)\r\n proj_value = self.value_conv(x_input).view(m_batchsize, -1, width * height) # B X C X N\r\n\r\n out = torch.bmm(proj_value, attention.permute(0, 2, 1))\r\n out = out.view(m_batchsize, C, width, height)\r\n\r\n out = self.gamma * out + x_input\r\n # return out, attention\r\n return out\r\n\r\nclass SpatialAttention(nn.Module):\r\n\r\n def __init__(self):\r\n super(SpatialAttention, self).__init__()\r\n\r\n self.conv1 = nn.Conv2d(in_channels=2, out_channels=1, kernel_size=3, padding=1, bias=False)\r\n self.sigmoid = nn.Sigmoid()\r\n\r\n def forward(self, x):\r\n\r\n avg_out = torch.mean(x, dim=1, keepdim=True)\r\n max_out, _ = torch.max(x, dim=1, keepdim=True)\r\n\r\n temp_x = torch.cat([avg_out, max_out], dim=1)\r\n temp_x = self.conv1(temp_x)\r\n attention = self.sigmoid(temp_x)\r\n x = attention * x\r\n return x\r\n\r\nclass ChannelAttention(nn.Module):\r\n def __init__(self, in_planes, ratio=16):\r\n super(ChannelAttention, self).__init__()\r\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\r\n self.max_pool = nn.AdaptiveMaxPool2d(1)\r\n self.fc1 = nn.Conv2d(in_planes, in_planes // 16, 1, bias=False)\r\n self.relu1 = nn.ReLU()\r\n self.fc2 = nn.Conv2d(in_planes // 16, in_planes, 1, bias=False)\r\n self.sigmoid = nn.Sigmoid()\r\n\r\n def forward(self, x):\r\n avg_out = self.fc2(self.relu1(self.fc1(self.avg_pool(x))))\r\n max_out = self.fc2(self.relu1(self.fc1(self.max_pool(x))))\r\n out = avg_out + max_out\r\n attention = self.sigmoid(out)\r\n out = attention * x\r\n return out\r\n\r\nclass GAM_Attention(nn.Module):\r\n def __init__(self, in_channels, out_channels, rate=4):\r\n super(GAM_Attention, self).__init__()\r\n\r\n self.channel_attention = nn.Sequential(\r\n nn.Linear(in_channels, int(in_channels / rate)),\r\n nn.ReLU(inplace=True),\r\n nn.Linear(int(in_channels / rate), in_channels)\r\n )\r\n\r\n self.spatial_attention = nn.Sequential(\r\n nn.Conv2d(in_channels, int(in_channels / rate), kernel_size=7, padding=3),\r\n nn.BatchNorm2d(int(in_channels / rate)),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(int(in_channels / rate), out_channels, kernel_size=7, padding=3),\r\n nn.BatchNorm2d(out_channels)\r\n )\r\n\r\n def forward(self, x):\r\n b, c, h, w = x.shape\r\n x_permute = x.permute(0, 2, 3, 1).view(b, -1, c)\r\n x_att_permute = self.channel_attention(x_permute).view(b, h, w, c)\r\n x_channel_att = x_att_permute.permute(0, 3, 1, 2)\r\n\r\n x = x * x_channel_att\r\n\r\n x_spatial_att = self.spatial_attention(x).sigmoid()\r\n out = x * x_spatial_att\r\n\r\n return out" ]
[ [ "torch.nn.Softmax", "torch.mean", "torch.max", "torch.cat", "torch.nn.functional.dropout", "torch.zeros", "torch.nn.Dropout", "torch.nn.AdaptiveMaxPool2d", "torch.add", "torch.nn.Sigmoid", "torch.bmm", "torch.nn.Sequential", "torch.nn.ConvTranspose2d", "torch.nn.Conv2d", "torch.nn.functional.mse_loss", "torch.nn.BatchNorm2d", "torch.nn.AdaptiveAvgPool2d", "torch.nn.init.xavier_uniform_", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dandanelbaz/agents
[ "f8bbc2ea64e71be69f22a7c1d5bf91f02bc87665", "f8bbc2ea64e71be69f22a7c1d5bf91f02bc87665" ]
[ "tf_agents/networks/encoding_network.py", "tf_agents/bandits/policies/linear_thompson_sampling_policy_test.py" ]
[ "# coding=utf-8\n# Copyright 2018 The TF-Agents Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Keras Encoding Network.\n\nImplements a network that will generate the following layers:\n\n [optional]: preprocessing_layers # preprocessing_layers\n [optional]: (Add | Concat(axis=-1) | ...) # preprocessing_combiner\n [optional]: Conv2D # conv_layer_params\n Flatten\n [optional]: Dense # fc_layer_params\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import logging\nimport gin\nimport tensorflow as tf\n\nfrom tf_agents.networks import network\nfrom tf_agents.networks import utils\nfrom tf_agents.utils import nest_utils\n\nfrom tensorflow.python.util import nest # pylint:disable=g-direct-tensorflow-import # TF internal\n\nCONV_TYPE_2D = '2d'\nCONV_TYPE_1D = '1d'\n\n\ndef _copy_layer(layer):\n \"\"\"Create a copy of a Keras layer with identical parameters.\n\n The new layer will not share weights with the old one.\n\n Args:\n layer: An instance of `tf.keras.layers.Layer`.\n\n Returns:\n A new keras layer.\n\n Raises:\n TypeError: If `layer` is not a keras layer.\n ValueError: If `layer` cannot be correctly cloned.\n \"\"\"\n if not isinstance(layer, tf.keras.layers.Layer):\n raise TypeError('layer is not a keras layer: %s' % str(layer))\n\n # pylint:disable=unidiomatic-typecheck\n if type(layer) == tf.compat.v1.keras.layers.DenseFeatures:\n raise ValueError('DenseFeatures V1 is not supported. '\n 'Use tf.compat.v2.keras.layers.DenseFeatures instead.')\n if layer.built:\n logging.warn(\n 'Beware: Copying a layer that has already been built: \\'%s\\'. '\n 'This can lead to subtle bugs because the original layer\\'s weights '\n 'will not be used in the copy.', layer.name)\n # Get a fresh copy so we don't modify an incoming layer in place. Weights\n # will not be shared.\n return type(layer).from_config(layer.get_config())\n\n\[email protected]\nclass EncodingNetwork(network.Network):\n \"\"\"Feed Forward network with CNN and FNN layers.\"\"\"\n\n def __init__(self,\n input_tensor_spec,\n preprocessing_layers=None,\n preprocessing_combiner=None,\n conv_layer_params=None,\n fc_layer_params=None,\n dropout_layer_params=None,\n activation_fn=tf.keras.activations.relu,\n kernel_initializer=None,\n batch_squash=True,\n dtype=tf.float32,\n name='EncodingNetwork',\n conv_type=CONV_TYPE_2D):\n \"\"\"Creates an instance of `EncodingNetwork`.\n\n Network supports calls with shape outer_rank + input_tensor_spec.shape. Note\n outer_rank must be at least 1.\n\n For example an input tensor spec with shape `(2, 3)` will require\n inputs with at least a batch size, the input shape is `(?, 2, 3)`.\n\n Input preprocessing is possible via `preprocessing_layers` and\n `preprocessing_combiner` Layers. If the `preprocessing_layers` nest is\n shallower than `input_tensor_spec`, then the layers will get the subnests.\n For example, if:\n\n ```python\n input_tensor_spec = ([TensorSpec(3)] * 2, [TensorSpec(3)] * 5)\n preprocessing_layers = (Layer1(), Layer2())\n ```\n\n then preprocessing will call:\n\n ```python\n preprocessed = [preprocessing_layers[0](observations[0]),\n preprocessing_layers[1](obsrevations[1])]\n ```\n\n However if\n\n ```python\n preprocessing_layers = ([Layer1() for _ in range(2)],\n [Layer2() for _ in range(5)])\n ```\n\n then preprocessing will call:\n ```python\n preprocessed = [\n layer(obs) for layer, obs in zip(flatten(preprocessing_layers),\n flatten(observations))\n ]\n ```\n\n **NOTE** `preprocessing_layers` and `preprocessing_combiner` are not allowed\n to have already been built. This ensures calls to `network.copy()` in the\n future always have an unbuilt, fresh set of parameters. Furtheremore,\n a shallow copy of the layers is always created by the Network, so the\n layer objects passed to the network are never modified. For more details\n of the semantics of `copy`, see the docstring of\n `tf_agents.networks.Network.copy`.\n\n Args:\n input_tensor_spec: A nest of `tensor_spec.TensorSpec` representing the\n input observations.\n preprocessing_layers: (Optional.) A nest of `tf.keras.layers.Layer`\n representing preprocessing for the different observations. All of these\n layers must not be already built.\n preprocessing_combiner: (Optional.) A keras layer that takes a flat list\n of tensors and combines them. Good options include\n `tf.keras.layers.Add` and `tf.keras.layers.Concatenate(axis=-1)`. This\n layer must not be already built.\n conv_layer_params: Optional list of convolution layers parameters, where\n each item is either a length-three tuple indicating\n `(filters, kernel_size, stride)` or a length-four tuple indicating\n `(filters, kernel_size, stride, dilation_rate)`.\n fc_layer_params: Optional list of fully_connected parameters, where each\n item is the number of units in the layer.\n dropout_layer_params: Optional list of dropout layer parameters, each item\n is the fraction of input units to drop or a dictionary of parameters\n according to the keras.Dropout documentation. The additional parameter\n `permanent', if set to True, allows to apply dropout at inference for\n approximated Bayesian inference. The dropout layers are interleaved with\n the fully connected layers; there is a dropout layer after each fully\n connected layer, except if the entry in the list is None. This list must\n have the same length of fc_layer_params, or be None.\n activation_fn: Activation function, e.g. tf.keras.activations.relu,.\n kernel_initializer: Initializer to use for the kernels of the conv and\n dense layers. If none is provided a default variance_scaling_initializer\n batch_squash: If True the outer_ranks of the observation are squashed into\n the batch dimension. This allow encoding networks to be used with\n observations with shape [BxTx...].\n dtype: The dtype to use by the convolution and fully connected layers.\n name: A string representing name of the network.\n conv_type: string, '1d' or '2d'. Convolution layers will be 1d or 2D\n respectively\n\n Raises:\n ValueError: If any of `preprocessing_layers` is already built.\n ValueError: If `preprocessing_combiner` is already built.\n ValueError: If the number of dropout layer parameters does not match the\n number of fully connected layer parameters.\n ValueError: If conv_layer_params tuples do not have 3 or 4 elements each.\n \"\"\"\n if preprocessing_layers is None:\n flat_preprocessing_layers = None\n else:\n flat_preprocessing_layers = [\n _copy_layer(layer) for layer in tf.nest.flatten(preprocessing_layers)\n ]\n # Assert shallow structure is the same. This verifies preprocessing\n # layers can be applied on expected input nests.\n input_nest = input_tensor_spec\n # Given the flatten on preprocessing_layers above we need to make sure\n # input_tensor_spec is a sequence for the shallow_structure check below\n # to work.\n if not nest.is_sequence(input_tensor_spec):\n input_nest = [input_tensor_spec]\n nest.assert_shallow_structure(\n preprocessing_layers, input_nest, check_types=False)\n\n if (len(tf.nest.flatten(input_tensor_spec)) > 1 and\n preprocessing_combiner is None):\n raise ValueError(\n 'preprocessing_combiner layer is required when more than 1 '\n 'input_tensor_spec is provided.')\n\n if preprocessing_combiner is not None:\n preprocessing_combiner = _copy_layer(preprocessing_combiner)\n\n if not kernel_initializer:\n kernel_initializer = tf.compat.v1.variance_scaling_initializer(\n scale=2.0, mode='fan_in', distribution='truncated_normal')\n\n layers = []\n\n if conv_layer_params:\n if conv_type == '2d':\n conv_layer_type = tf.keras.layers.Conv2D\n elif conv_type == '1d':\n conv_layer_type = tf.keras.layers.Conv1D\n else:\n raise ValueError('unsupported conv type of %s. Use 1d or 2d' % (\n conv_type))\n\n for config in conv_layer_params:\n if len(config) == 4:\n (filters, kernel_size, strides, dilation_rate) = config\n elif len(config) == 3:\n (filters, kernel_size, strides) = config\n dilation_rate = (1, 1) if conv_type == '2d' else (1,)\n else:\n raise ValueError(\n 'only 3 or 4 elements permitted in conv_layer_params tuples')\n layers.append(\n conv_layer_type(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n dilation_rate=dilation_rate,\n activation=activation_fn,\n kernel_initializer=kernel_initializer,\n dtype=dtype,\n name='%s/conv%s' % (name, conv_type)))\n\n layers.append(tf.keras.layers.Flatten())\n\n if fc_layer_params:\n if dropout_layer_params is None:\n dropout_layer_params = [None] * len(fc_layer_params)\n else:\n if len(dropout_layer_params) != len(fc_layer_params):\n raise ValueError('Dropout and fully connected layer parameter lists'\n 'have different lengths (%d vs. %d.)' %\n (len(dropout_layer_params), len(fc_layer_params)))\n for num_units, dropout_params in zip(fc_layer_params,\n dropout_layer_params):\n layers.append(\n tf.keras.layers.Dense(\n num_units,\n activation=activation_fn,\n kernel_initializer=kernel_initializer,\n dtype=dtype,\n name='%s/dense' % name))\n if not isinstance(dropout_params, dict):\n dropout_params = {'rate': dropout_params} if dropout_params else None\n\n if dropout_params is not None:\n layers.append(utils.maybe_permanent_dropout(**dropout_params))\n\n super(EncodingNetwork, self).__init__(\n input_tensor_spec=input_tensor_spec, state_spec=(), name=name)\n\n # Pull out the nest structure of the preprocessing layers. This avoids\n # saving the original kwarg layers as a class attribute which Keras would\n # then track.\n self._preprocessing_nest = tf.nest.map_structure(lambda l: None,\n preprocessing_layers)\n self._flat_preprocessing_layers = flat_preprocessing_layers\n self._preprocessing_combiner = preprocessing_combiner\n self._postprocessing_layers = layers\n self._batch_squash = batch_squash\n\n def call(self, observation, step_type=None, network_state=()):\n del step_type # unused.\n\n if self._batch_squash:\n outer_rank = nest_utils.get_outer_rank(\n observation, self.input_tensor_spec)\n batch_squash = utils.BatchSquash(outer_rank)\n observation = tf.nest.map_structure(batch_squash.flatten, observation)\n\n if self._flat_preprocessing_layers is None:\n processed = observation\n else:\n processed = []\n for obs, layer in zip(\n nest.flatten_up_to(\n self._preprocessing_nest, observation, check_types=False),\n self._flat_preprocessing_layers):\n processed.append(layer(obs))\n if len(processed) == 1 and self._preprocessing_combiner is None:\n # If only one observation is passed and the preprocessing_combiner\n # is unspecified, use the preprocessed version of this observation.\n processed = processed[0]\n\n states = processed\n\n if self._preprocessing_combiner is not None:\n states = self._preprocessing_combiner(states)\n\n for layer in self._postprocessing_layers:\n states = layer(states)\n\n if self._batch_squash:\n states = tf.nest.map_structure(batch_squash.unflatten, states)\n\n return states, network_state\n", "# coding=utf-8\n# Copyright 2018 The TF-Agents Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for tf_agents.bandits.policies.lin_ucb_policy.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport numpy as np\nimport tensorflow as tf\nfrom tf_agents.bandits.policies import linear_thompson_sampling_policy as lin_ts\nfrom tf_agents.specs import tensor_spec\nfrom tf_agents.trajectories import time_step as ts\nfrom tf_agents.utils import test_utils\nfrom tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import # TF internal\n\n\ndef test_cases():\n return parameterized.named_parameters(\n {\n 'testcase_name': 'batch1',\n 'batch_size': 1,\n 'num_actions': 2,\n }, {\n 'testcase_name': 'batch4',\n 'batch_size': 4,\n 'num_actions': 3,\n })\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass LinearThompsonSamplingPolicyTest(parameterized.TestCase,\n test_utils.TestCase):\n\n def setUp(self):\n super(LinearThompsonSamplingPolicyTest, self).setUp()\n self._obs_dim = 2\n self._obs_spec = tensor_spec.TensorSpec((self._obs_dim), tf.float32)\n self._time_step_spec = ts.time_step_spec(self._obs_spec)\n\n def _weight_covariance_matrices(self, num_actions):\n return [\n tf.constant(\n list(range(4 * i, 4 * (i + 1))), shape=[2, 2], dtype=tf.float32)\n for i in range(num_actions)\n ]\n\n def _parameter_estimators(self, num_actions):\n return [\n tf.constant(\n list(range(2 * i, 2 * (i + 1))), shape=[2], dtype=tf.float32)\n for i in list(range(num_actions))\n ]\n\n def _time_step_batch(self, batch_size, num_actions):\n observation = tf.constant(\n np.array(range(batch_size * self._obs_dim)),\n dtype=tf.float32,\n shape=[batch_size, self._obs_dim],\n name='observation')\n return ts.restart(observation, batch_size=batch_size)\n\n @test_cases()\n def testActionBatch(self, batch_size, num_actions):\n action_spec = tensor_spec.BoundedTensorSpec(\n shape=(),\n minimum=0,\n maximum=num_actions - 1,\n dtype=tf.int32,\n name='action')\n policy = lin_ts.LinearThompsonSamplingPolicy(\n action_spec, self._weight_covariance_matrices(num_actions),\n self._parameter_estimators(num_actions), self._time_step_spec)\n\n action_step = policy.action(self._time_step_batch(batch_size, num_actions))\n\n self.assertEqual(action_step.action.shape.as_list(), [batch_size])\n self.assertEqual(action_step.action.dtype, tf.int32)\n actions = self.evaluate(action_step.action)\n self.assertAllGreaterEqual(actions, 0)\n self.assertAllLessEqual(actions, num_actions - 1)\n\n def testCorrectEstimates(self):\n parameter_estimators = tf.unstack(\n tf.constant([[1, 2], [30, 40]], dtype=tf.float32))\n weight_covariance_matrices = tf.unstack(\n tf.constant([[[1, 0], [0, 1]], [[.5, 0], [0, .5]]], dtype=tf.float32))\n batch_size = 7\n observation = tf.constant(\n [6, 7] * batch_size,\n dtype=tf.float32,\n shape=[batch_size, 2],\n name='observation')\n expected_means = [[20, 920]] * batch_size\n means, variances = lin_ts._get_means_and_variances(\n parameter_estimators, weight_covariance_matrices, observation)\n self.assertAllEqual(self.evaluate(tf.stack(means, axis=-1)), expected_means)\n expected_variances = [[85, 170]] * batch_size\n self.assertAllEqual(\n self.evaluate(tf.stack(variances, axis=-1)), expected_variances)\n\n\nif __name__ == '__main__':\n tf.test.main()\n" ]
[ [ "tensorflow.python.util.nest.assert_shallow_structure", "tensorflow.python.util.nest.is_sequence", "tensorflow.keras.layers.Dense", "tensorflow.compat.v1.variance_scaling_initializer", "tensorflow.nest.flatten", "tensorflow.keras.layers.Flatten", "tensorflow.nest.map_structure", "tensorflow.python.util.nest.flatten_up_to" ], [ "tensorflow.stack", "tensorflow.constant", "tensorflow.test.main" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yao-zhao/EDGAN
[ "b3164fb9d5d9b571b52328b7dd187b748d5a304d" ]
[ "transfer/convert_resnet.py" ]
[ "from __future__ import division\nfrom __future__ import print_function\n\nimport sys\nsys.path.append('/home/yz/caffe2/python')\nimport caffe\nimport numpy as np\nimport tensorflow as tf\nimport model\n\nFLAGS = tf.app.flags.FLAGS\n\n# tensorflow name to caffename\n# output:\n# caffename\n# caffe blob id\n# reshape vector\ndef _get_caffename_from_tf(tfname):\n tags = tfname.split('/')\n conv_reshape = [2, 3, 1, 0]\n if tags[0] == '1':\n if 'weights' in tags[-1]:\n return 'conv1', 0, conv_reshape\n if 'scale' in tags[-1]:\n return 'scale_conv1', 0, None\n if 'bias' in tags[-1]:\n return 'scale_conv1', 1, None\n elif tags[0] in ['1','2','3','4','5']:\n blockid = tags[0]\n stackid = tags[1]\n branchid = tags[2]\n bottleid = tags[3]\n sufix = blockid+stackid+'_'+branchid\n if branchid == 'branch2':\n sufix = sufix+bottleid\n if 'weights' in tags[-1]:\n return 'res'+sufix, 0, conv_reshape\n if 'scale' in tags[-1]:\n return 'scale'+sufix, 0, None\n if 'bias' in tags[-1]:\n return 'scale'+sufix, 1, None\n else:\n return None, None, None\n \n# assign values from caffe to tensorflow\ndef transfer_from_caffenet(\\\n model_def = 'models/resnet/ResNet-50-deploy.prototxt',\n model_weights = 'models/resnet/ResNet-50-model.caffemodel',\n checkpoint_file = 'models/resnet/ResNet-50-transfer.ckpt',\n num_output = 80):\n with tf.Graph().as_default():\n with tf.device('/cpu:0'):\n # load inference model\n images = tf.placeholder(\"float32\", [None, 224, 224, 3], name=\"images\")\n model.inference_resnet(images)\n #begin session\n sess = tf.Session()\n sess.run(tf.initialize_all_variables())\n print('tensorflow model initialized')\n # load caffenet\n caffe.set_mode_cpu()\n net = None\n net = caffe.Net(model_def, model_weights, caffe.TEST)\n print('caffe net loaded')\n # get assign ops\n assign_ops = []\n vars_to_save = []\n for var in tf.trainable_variables():\n caffename, blobid, reshape = _get_caffename_from_tf(var.name)\n if caffename in net.params.keys():\n blobdata = net.params[caffename][blobid].data\n if reshape is not None:\n blobdata = np.transpose(blobdata, reshape)\n # assert tf.Dimension(blobdata.shape) == var.get_shape()\n print('found',var.name, var.get_shape(),'->',\n caffename, blobdata.shape)\n assign_ops.append(var.assign(blobdata))\n vars_to_save.append(var)\n else:\n print('not found', var.name, '->', caffename)\n # assign values\n sess.run(assign_ops)\n print('values transfered')\n # save\n saver = tf.train.Saver(vars_to_save)\n saver.save(sess, checkpoint_file, write_meta_graph=False)\n print('model saved')\n\ndef main(argv=None): # pylint: disable=unused-argument\n transfer_from_caffenet(num_output=80)\n\nif __name__ == '__main__':\n tf.app.run()\n" ]
[ [ "tensorflow.device", "tensorflow.Graph", "tensorflow.placeholder", "tensorflow.initialize_all_variables", "tensorflow.Session", "numpy.transpose", "tensorflow.trainable_variables", "tensorflow.train.Saver", "tensorflow.app.run" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
beyondcoin-project/electrum-bynd
[ "b113e9b01db2b0b5f123f579457332f0b95f63e9" ]
[ "electrum_bynd/plot.py" ]
[ "import datetime\nfrom collections import defaultdict\n\nimport matplotlib\nmatplotlib.use('Qt5Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as md\n\nfrom .i18n import _\nfrom .bitcoin import COIN\n\n\nclass NothingToPlotException(Exception):\n def __str__(self):\n return _(\"Nothing to plot.\")\n\n\ndef plot_history(history):\n if len(history) == 0:\n raise NothingToPlotException()\n hist_in = defaultdict(int)\n hist_out = defaultdict(int)\n for item in history:\n if not item['confirmations']:\n continue\n if item['timestamp'] is None:\n continue\n value = item['value'].value/COIN\n date = item['date']\n datenum = int(md.date2num(datetime.date(date.year, date.month, 1)))\n if value > 0:\n hist_in[datenum] += value\n else:\n hist_out[datenum] -= value\n\n f, axarr = plt.subplots(2, sharex=True)\n plt.subplots_adjust(bottom=0.2)\n plt.xticks( rotation=25 )\n ax = plt.gca()\n plt.ylabel('BYND')\n plt.xlabel('Month')\n xfmt = md.DateFormatter('%Y-%m-%d')\n ax.xaxis.set_major_formatter(xfmt)\n axarr[0].set_title('Monthly Volume')\n xfmt = md.DateFormatter('%Y-%m')\n ax.xaxis.set_major_formatter(xfmt)\n width = 20\n\n r1 = None\n r2 = None\n dates_values = list(zip(*sorted(hist_in.items())))\n if dates_values and len(dates_values) == 2:\n dates, values = dates_values\n r1 = axarr[0].bar(dates, values, width, label='incoming')\n axarr[0].legend(loc='upper left')\n dates_values = list(zip(*sorted(hist_out.items())))\n if dates_values and len(dates_values) == 2:\n dates, values = dates_values\n r2 = axarr[1].bar(dates, values, width, color='r', label='outgoing')\n axarr[1].legend(loc='upper left')\n if r1 is None and r2 is None:\n raise NothingToPlotException()\n return plt\n" ]
[ [ "matplotlib.pyplot.gca", "matplotlib.dates.DateFormatter", "matplotlib.use", "matplotlib.pyplot.subplots", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
SinghShreya05/sktime
[ "9c7806204bcdad3d496660ddeeea84099ef0f3ee" ]
[ "sktime/transformations/series/detrend/_detrend.py" ]
[ "#!/usr/bin/env python3 -u\n# -*- coding: utf-8 -*-\n# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)\n\n__all__ = [\"Detrender\"]\n__author__ = [\"Markus Löning\"]\n\nfrom sklearn.base import clone\n\nfrom sktime.forecasting.base._fh import ForecastingHorizon\nfrom sktime.transformations.base import _SeriesToSeriesTransformer\nfrom sktime.utils.validation.series import check_series\n\n\nclass Detrender(_SeriesToSeriesTransformer):\n \"\"\"\n Remove a trend from a series.\n This transformer uses any forecaster and returns the in-sample residuals\n of the forecaster's predicted values.\n\n The Detrender works by first fitting the forecaster to the input data.\n To transform data, it uses the fitted forecaster to generate\n forecasts for the time points of the passed data and returns the residuals\n of the forecasts.\n Depending on the passed data, this will require it to generate in-sample\n or out-of-sample forecasts.\n\n The detrender also works in a pipeline as a form of boosting,\n by first detrending a time series and then fitting another forecaster on\n the residuals.\n\n For example, to remove the linear trend of a time series:\n forecaster = PolynomialTrendForecaster(degree=1)\n transformer = Detrender(forecaster=forecaster)\n yt = transformer.fit_transform(y_train)\n\n Parameters\n ----------\n forecaster : estimator object\n The forecasting model to remove the trend with\n (e.g. PolynomialTrendForecaster)\n\n Attributes\n ----------\n forecaster_ : estimator object\n Model that defines the trend in the series\n\n Example\n ----------\n >>> from sktime.transformations.series.detrend import Detrender\n >>> from sktime.forecasting.trend import PolynomialTrendForecaster\n >>> from sktime.datasets import load_airline\n >>> y = load_airline()\n >>> transformer = Detrender(forecaster=PolynomialTrendForecaster(degree=1))\n >>> y_hat = transformer.fit_transform(y)\n \"\"\"\n\n _required_parameters = [\"forecaster\"]\n _tags = {\"transform-returns-same-time-index\": True, \"univariate-only\": True}\n\n def __init__(self, forecaster):\n self.forecaster = forecaster\n self.forecaster_ = None\n super(Detrender, self).__init__()\n\n def fit(self, Z, X=None):\n \"\"\"\n Compute the trend in the series\n\n Parameters\n ----------\n Y : pd.Series\n Endogenous time series to fit a trend to.\n X : pd.DataFrame, optional (default=None)\n Exogenous variables\n\n Returns\n -------\n self : an instance of self\n \"\"\"\n z = check_series(Z, enforce_univariate=True)\n forecaster = clone(self.forecaster)\n self.forecaster_ = forecaster.fit(z, X)\n self._is_fitted = True\n return self\n\n def transform(self, Z, X=None):\n \"\"\"\n Remove trend from the data.\n\n Parameters\n ----------\n y : pd.Series\n Time series to be detrended\n X : pd.DataFrame, optional (default=False)\n Exogenous variables\n\n Returns\n -------\n y_hat : pd.Series\n De-trended series\n \"\"\"\n self.check_is_fitted()\n z = check_series(Z, enforce_univariate=True)\n fh = ForecastingHorizon(z.index, is_relative=False)\n z_pred = self.forecaster_.predict(fh, X)\n return z - z_pred\n\n def inverse_transform(self, Z, X=None):\n \"\"\"\n Add trend back to a time series\n\n Parameters\n ----------\n y : pd.Series, list\n Detrended time series to revert\n X : pd.DataFrame, optional (default=False)\n Exogenous variables\n\n Returns\n -------\n y_hat : pd.Series\n Series with the trend\n \"\"\"\n self.check_is_fitted()\n z = check_series(Z, enforce_univariate=True)\n fh = ForecastingHorizon(z.index, is_relative=False)\n z_pred = self.forecaster_.predict(fh, X)\n return z + z_pred\n\n def update(self, Z, X=None, update_params=True):\n \"\"\"\n Update the parameters of the detrending estimator with new data\n\n Parameters\n ----------\n y_new : pd.Series\n New time series\n update_params : bool, optional (default=True)\n Update the parameters of the detrender model with\n\n Returns\n -------\n self : an instance of self\n \"\"\"\n z = check_series(Z, enforce_univariate=True, allow_empty=True)\n self.forecaster_.update(z, X, update_params=update_params)\n return self\n" ]
[ [ "sklearn.base.clone" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Yu-Group/adaptive-wavelets
[ "e67f726e741d83c94c3aee3ed97a772db4ce0bb3", "e67f726e741d83c94c3aee3ed97a772db4ce0bb3" ]
[ "notebooks/cifar10/util.py", "awave/data/resize_imgs.py" ]
[ "import torch\nfrom os.path import join as oj\nimport os\n\ndef train_epoch(model, device, train_loader, optimizer, epoch, criterion):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n outputs = model(data)\n loss = criterion(outputs, target)\n \n loss.backward()\n optimizer.step()\n if batch_idx % 50 == 0:\n print('\\rTrain Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()), end='')\n\ndef test_epoch(model, device, test_loader, criterion):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss = criterion(output, target)\n pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n return test_loss\n \ndef train(model, device, train_loader, test_loader, optimizer, num_epochs, criterion, save_dir=None):\n print('training...')\n \n if save_dir is not None:\n os.makedirs(save_dir, exist_ok=True)\n \n best_loss = 1e10\n test_losses = []\n for epoch in range(num_epochs):\n train_epoch(model, device, train_loader, optimizer, epoch+1, criterion)\n test_loss = test_epoch(model, device, test_loader, criterion)\n test_losses.append(test_loss)\n \n # saving\n if test_loss < best_loss:\n best_loss = test_loss\n if save_dir is not None:\n torch.save(model.state_dict(),\n oj(save_dir, f'checkpoint_{epoch}.pth'))\n\n ", "import os\n\nimport numpy as np\n\nopj = os.path.join\nfrom astropy.io import fits\n\ndata_path = '../../data/cosmology'\n\n\ndef downsample(parameter_file, root_dir, resize=64, nsamples=30000, ncosmo=10):\n '''\n downsample cosmolgy image\n '''\n print('preprocessing...')\n img_size = 256\n params_ = np.loadtxt(parameter_file)[:ncosmo]\n\n image = []\n params = []\n for idx in range(nsamples):\n img_name = opj(root_dir, 'model%03d/WLconv_z1.00_%04dr.fits' % (idx % len(params_), idx // len(params_)))\n start1 = np.random.randint(0, img_size - resize - 1, 1)[0]\n start2 = np.random.randint(0, img_size - resize - 1, 1)[0]\n end1 = start1 + resize\n end2 = start2 + resize\n hdu_list = fits.open(img_name, memmap=False)\n img_data = hdu_list[0].data\n image.append(img_data[start1:end1, start2:end2])\n hdu_list.close()\n params.append(params_[idx % len(params_), 1:-1])\n print('\\r idx: {}/{}'.format(idx, nsamples), end='')\n\n image = np.stack(image, axis=0)\n params = np.stack(params, axis=0)\n # save\n np.savez(opj(data_path, 'cosmo_resize_{}.npz'.format(resize)), imgs=image, params=params)\n\n\nif __name__ == '__main__':\n parameter_file = opj(data_path, 'cosmological_parameters.txt')\n root_dir = opj(data_path, 'z1_256')\n resize = 64\n\n # save\n downsample(parameter_file, root_dir, resize)\n\n # load\n dataset_zip = np.load(opj(data_path, 'cosmo_resize_{}.npz'.format(resize)))\n imgs = dataset_zip['imgs']\n params = dataset_zip['params']\n print(imgs.shape, params.shape)\n" ]
[ [ "torch.no_grad" ], [ "numpy.loadtxt", "numpy.stack", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
llove-y/self_driving_scenario_designer
[ "b97cfbd0595cebe3fe705220b9ffbe01875f23bb" ]
[ "line_fitting_helpers/bspline_path.py" ]
[ "#!/usr/bin/python3.5\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.interpolate as si\n\n# parameter\nN = 3 # B Spline order\n\ndef bspline_planning(points, sn):\n x = []\n y = []\n for point in points:\n x.append(point[0])\n y.append(point[1])\n fit_points = []\n #print(points)\n if len(points) > 4:\n t = range(len(x))\n x_tup = si.splrep(t, x, k=N)\n y_tup = si.splrep(t, y, k=N)\n x_list = list(x_tup)\n #xl = x.tolist()\n x_list[1] = x + [0.0, 0.0, 0.0, 0.0]\n y_list = list(y_tup)\n #yl = y.tolist()\n y_list[1] = y + [0.0, 0.0, 0.0, 0.0]\n\n ipl_t = np.linspace(0.0, len(x) - 1, sn)\n rx = si.splev(ipl_t, x_list)\n ry = si.splev(ipl_t, y_list)\n for i in range(len(rx)):\n point = [rx[i],ry[i]]\n fit_points.append(point)\n else:\n print(\"please continue click, you must have more than 4 points to draw a B_spline\")\n return fit_points\n\ndef main():\n print(__file__ + \" start!!\")\n # way points\n points = [[1,2],[2,3],[4,5],[5,7]]\n print(points)\n x = []\n y = []\n for point in points:\n x.append(point[0])\n y.append(point[1])\n print(x)\n print(y)\n sn = 100 # sampling number\n\n rx, ry = bspline_planning(points, sn)\n\n # show results\n plt.plot(x, y, '-og', label=\"Waypoints\")\n plt.plot(rx, ry, '-r', label=\"B-Spline path\")\n plt.grid(True)\n plt.legend()\n plt.axis(\"equal\")\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "matplotlib.pyplot.legend", "scipy.interpolate.splrep", "scipy.interpolate.splev", "matplotlib.pyplot.plot", "matplotlib.pyplot.grid", "matplotlib.pyplot.axis", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "1.3", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16", "1.8" ], "tensorflow": [] } ]
wtberry/CSCI4911
[ "c988b2949d5b81e797d90d8c2ff9e015eb4c044f", "c988b2949d5b81e797d90d8c2ff9e015eb4c044f" ]
[ "cipher/torch_seq_name.py", "cipher/single_layer_mul_batch_lstm.py" ]
[ "# Lab 12 RNN\nfrom string import ascii_uppercase\nfrom collections import OrderedDict\nfrom itertools import count\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\nimport pre_process as pre\n\n'''\nTHis is a practice for using torch to implement simple, one cell RNN.\nIt takes sequence of alphabet letters as input (here, my name) and \noutputs/predicts next letter based on the input. \nSo... Name: Wataru Takahashi, Input: Wataru Takahashi, Label: ataru Takahashi\n'''\n\n'''\nInput is encoded as one-hot matrix based on index number from 0-26\n'''\n\n\ntorch.manual_seed(777) # reproducibility\n\n\nidx2char = [letter for letter in ascii_uppercase]\nidx2char.append(' ')\nname = 'Wataru Takahashi'\n\ncipher = pre.data() # importing the dataframe of cipher txt\nkey_cipher = cipher.iloc[0].key + cipher.iloc[0].cipher\nkey_length = cipher.iloc[0].key\nplain = cipher.iloc[0].plantxt\n\nod = OrderedDict(zip(ascii_uppercase, count(0)))\nod.update({' ': 26}) # adding white space as leters\n\ndef encode(text):\n ## strip white space and \"'\" in the string, and convert it into numbers\n return [od[letter] for letter in text.replace(' ', '').strip(\"\").upper()]\n\nx_data = [encode(name[:-1])] # encoding the x string data, here, my name\n# Wataru Takahashi\n\nx_cipher = [encode(key_cipher)]\ny_plain = [encode(plain)]\n\ndef one_hot(data):\n # creating empty nested list to store one-hot\n empty = [[0 for n in range(0, len(od))] for N in range(0, len(data[0]))]\n\n for n in enumerate(data[0]):\n empty[n[0]][n[1]] = 1\n return empty\n# Teach Wataru Takahash -> ataru Takahashi\nx_one_hot = one_hot(x_data)\n\ny_data = encode(name[1:]) # label, ataru Takahashi\n\ncipher_one_hot = one_hot(x_cipher)\n\n## enclosing the data inside of list, for dimensionality of input\nx_one_hot = [x_one_hot]\ny_data = y_data\n\ncipher_one_hot = [cipher_one_hot]\ny_plain = y_plain[0]\n\n# As we have one batch of samples, we will change them to variables only once\ninputs = Variable(torch.Tensor(x_one_hot))\nlabels = Variable(torch.LongTensor(y_data))\n\ninputs_cipher = Variable(torch.Tensor(cipher_one_hot))\nlabels_plain = Variable(torch.LongTensor(y_plain))\n\nnum_classes = 27\ninput_size = 27 # one-hot size\nhidden_size = 27 # output from the LSTM. 5 to directly predict one-hot\nbatch_size = 1 # one sentence\nsequence_length = inputs_cipher.shape[1] # |ihello| == 6\nnum_layers = 1 # one-layer rnn\n\n\nclass RNN(nn.Module):\n\n def __init__(self, num_classes, input_size, hidden_size, num_layers):\n super(RNN, self).__init__()\n\n self.num_classes = num_classes\n self.num_layers = num_layers\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.sequence_length = sequence_length\n\n self.rnn = nn.RNN(input_size=input_size, hidden_size=hidden_size, batch_first=True)\n\n def forward(self, x):\n # Initialize hidden and cell states\n # (batch, num_layers * num_directions, hidden_size) for batch_first=True\n h_0 = Variable(torch.zeros(\n x.size(0), self.num_layers, self.hidden_size))\n\n # Reshape input\n x.view(x.size(0), self.sequence_length, self.input_size)\n\n # Propagate input through RNN\n # Input: (batch, seq_len, input_size)\n # h_0: (batch, num_layers * num_directions, hidden_size)\n\n out, _ = self.rnn(x, h_0)\n return out.view(-1, num_classes)\n\n\n# Instantiate RNN model\nrnn = RNN(num_classes, input_size, hidden_size, num_layers)\nprint(rnn)\n\n# Set loss and optimizer function\n# CrossEntropyLoss = LogSoftmax + NLLLoss\ncriterion = torch.nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(rnn.parameters(), lr=0.003)\n\n# Train the model\nfor epoch in range(3000):\n outputs = rnn(inputs_cipher)\n optimizer.zero_grad()\n loss = criterion(outputs[7:, :], labels_plain)\n loss.backward()\n optimizer.step()\n _, idx = outputs.max(1)\n idx = idx.data.numpy()\n result_str = [idx2char[c] for c in idx.squeeze()]\n print(\"epoch: %d, loss: %1.3f\" % (epoch + 1, loss.data[0]))\n print(\"Predicted string: \", ''.join(result_str))\n\nprint(\"Learning finished!\")\n\n", "# Lab 12 RNN\nfrom string import ascii_uppercase\nfrom collections import OrderedDict\nfrom itertools import count\n\nfrom logger import Logger\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\nimport pre_process as pre\n\n'''\nTHis is a practice for using torch to implement simple, one cell RNN.\nIt takes sequence of alphabet letters as input (here, my name) and \noutputs/predicts next letter based on the input. \nSo... Name: Wataru Takahashi, Input: Wataru Takahashi, Label: ataru Takahashi\n'''\n\n'''\nInput is encoded as one-hot matrix based on index number from 0-26\n'''\n\n\ntorch.manual_seed(777) # reproducibility\n\n\n# Sequece number N, how long the texts are.. for now, 380\nN = 20\nnum_classes = 27\ninput_size = 27 # one-hot size\nhidden_size = 27 # output from the LSTM. 5 to directly predict one-hot\nbatch_size = 500 # number of sentence\nsequence_length = N+8# text + key\nnum_layers = 1 # one-layer lstm\n\nidx2char = [letter for letter in ascii_uppercase]\nidx2char.append(' ')\n\n\ncipher = pre.data() # importing the dataframe of cipher txt\n#key_cipher = cipher.iloc[0].key + cipher.iloc[0].cipher\n## creating list of strings of all the texts\nkey_cipher = [[cipher.iloc[i].key + cipher.iloc[i].cipher.replace(' ', '')[:N]] for i in range(batch_size)]\n#plain = cipher.iloc[0].key + cipher.iloc[0].plantxt\nplain = [[cipher.iloc[i].key + cipher.iloc[i].plantxt[:N]] for i in range(batch_size)]\n\nkey_length = len(cipher.iloc[0].key)\nod = OrderedDict(zip(ascii_uppercase, count(0)))\nod.update({'-': 26}) # adding white space as leters\n\ndef encode(text):\n ## strip white space and \"'\" in the string, and convert it into numbers\n return [[od[letter] for letter in line[0].replace(' ', '').strip(\"\").upper()] for line in text]\n\ndef to_np(x):\n return x.data.cpu().numpy()\n\n# Wataru Takahashi\n\nx_cipher = encode(key_cipher)\ny_plain = encode(plain)\n\ndef one_hot(data):\n # creating empty nested list to store one-hot\n empty = [[[0 for n in range(0, len(od))] for l in range(N+key_length)] for i in range(len(key_cipher))]\n\n for i, one_batch in enumerate(data):\n for c, n in enumerate(one_batch):\n empty[i][c][n] = 1\n return empty\n# Teach Wataru Takahash -> ataru Takahashi\n\n\ncipher_one_hot = one_hot(x_cipher)\n\n## enclosing the data inside of list, for dimensionality of input\n\n# As we have one batch of samples, we will change them to variables only once\n\ninputs_cipher = Variable(torch.Tensor(cipher_one_hot))\nlabels_plain = Variable(torch.LongTensor(y_plain))\n\n\nclass LSTM(nn.Module):\n\n def __init__(self, num_classes, input_size, hidden_size, num_layers):\n super(LSTM, self).__init__()\n\n self.num_classes = num_classes\n self.num_layers = num_layers\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.sequence_length = sequence_length\n\n # layer1 lstm\n self.lstm1= nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=True)\n# # layer2 lstm\n# self.lstm2= nn.LSTM(input_size=input_size, hidden_size=hidden_size, batch_first=True)\n # fully connected linear layer\n self.linear1 = nn.Linear(num_classes, num_classes)\n\n def forward(self, x):\n # Initialize hidden and cell states\n # (num_layers * num_directions, batch hidden_size) for batch_first=True\n h_1 = (Variable(torch.randn(self.num_layers, x.size(0), self.hidden_size)), \n Variable(torch.randn(self.num_layers, x.size(0), self.hidden_size)))\n\n# h_2 = (Variable(torch.randn(x.size(0), self.num_layers, self.hidden_size)), Variable(torch.randn(x.size(0), self.num_layers, self.hidden_size)))\n\n #print('h_o', h_0)\n\n # Reshape input\n x.view(x.size(0), self.sequence_length, self.input_size)\n\n # Propagate input through RNN\n # Input: (batch, seq_len, input_size)\n # h_0: (batch, num_layers * num_directions, hidden_size)\n out, _ = self.lstm1(x, h_1)\n out = out.contiguous().view(-1, num_classes)\n\n # Fully Connected layer\n p1 = self.linear1(out)\n return p1\n\n\n# Instantiate RNN model\nlstm = LSTM(num_classes, input_size, hidden_size, num_layers)\nprint(lstm)\n\n# set logger directory\nLOG_PATH = '/home/wataru/Uni/4911/cipher/new_logs/'\nLOG_DIR= 'Layer_'+ str(num_layers)+'_lr_'+str(lr)+'_epoch_'+str(num_iter)\n# set logger\nlogger = Logger(LOG_PATH+LOG_DIR)\n\n\n# Set loss and optimizer function\n# CrossEntropyLoss = LogSoftmax + NLLLoss\ncriterion = torch.nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(lstm.parameters(), lr=0.003)\n\n# Train the model\nfor epoch in range(10000):\n outputs = lstm(inputs_cipher)\n optimizer.zero_grad()\n # \"Flattening the labels vector so that it can be fed into loss function\"\n loss = criterion(outputs, labels_plain.view(sequence_length*batch_size))\n loss.backward()\n optimizer.step()\n #if epoch%10 == 0:\n\n if (epoch+1)%10==0:\n\n _, idx = outputs.max(1)\n idx = idx.data.numpy()[:sequence_length] # printing out only one sentence\n idx_label = labels_plain[0].data.numpy()\n result_str = [idx2char[c] for c in idx.squeeze()]\n label_str = [idx2char[c] for c in idx_label.squeeze()]\n print()\n print(\"epoch: %d, loss: %1.3f\" % (epoch + 1, loss.data[0]))\n print(\"Predicted string: \", ''.join(result_str))\n print(\"Label string: \", ''.join(label_str))\n ##### Tensorboard logging\n # 1. log the scalar values\n info = {\n 'loss': loss.data[0]\n }\n \n for tag, value in info.items():\n logger.scalar_summary(tag, value, epoch+1)\n \n \n # 2. Log values and gradients of the parameters (histogram)\n for tag, value in lstm.named_parameters():\n tag = tag.replace('.', '/')\n logger.histo_summary(tag, to_np(value), epoch+1)\n logger.histo_summary(tag+'/grad', to_np(value.grad), epoch+1)\nprint(\"Learning finished!\")\n\ndef accuracy(prediction, labels):\n _, idx = prediction.max(1)\n idx_label = labels.view(sequence_length*batch_size)\n compare = idx == idx_label\n compare = compare.float() # converting bol to float of 1/0\n return compare.mean() * 100\n\nprediction = lstm(inputs_cipher)\nacc = accuracy(prediction, labels_plain)\nprint(\"Training set Accuracy: %1.1f\" % (acc), \"%\")\n\n\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.LongTensor", "torch.Tensor", "torch.manual_seed", "torch.nn.RNN" ], [ "torch.nn.CrossEntropyLoss", "torch.LongTensor", "torch.Tensor", "torch.nn.LSTM", "torch.manual_seed", "torch.nn.Linear" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
paulodder/quantifier_complexity
[ "c46743f2ba9b63c40bff27e15d58f7e9c59b5a4b" ]
[ "src/operators.py" ]
[ "# from SetPlaceholders import SetPlaceholder\n\nimport numpy as np\nimport math\nfrom collections import namedtuple\nfrom itertools import chain\n\nvectorized_isclose = np.vectorize(math.isclose)\nvectorized_round = np.vectorize(round)\n\nOperator = namedtuple(\"Operator\", \"name func input_types output_type\")\nSetPlaceholder = namedtuple(\"Operator\", \"name func input_types output_type\")\n\nOperator.__repr__ = lambda self: self.name\nOperator.__str__ = lambda self: self.name\n\n## ff hardcode\nSIZE2RANGE = {\n 1: (0, 4),\n 2: (4, 20),\n 3: (20, 84),\n 4: (84, 340),\n 5: (340, 1364),\n 6: (1364, 5460),\n 7: (5460, 21844),\n 8: (21844, 87380),\n 9: (87380, 349524),\n 10: (349524, 1398100),\n 11: (1398100, 5592404),\n 12: (5592404, 22369620),\n 13: (22369620, 89478484),\n 14: (89478484, 357913940),\n 15: (357913940, 1431655764),\n 16: (1431655764, 5726623060),\n 17: (5726623060, 22906492244),\n 18: (22906492244, 91625968980),\n 19: (91625968980, 366503875924),\n 20: (366503875924, 1466015503700),\n}\n\n\ndef index_func(i, set_repr, SIZE2RANGE):\n \"\"\"Return a set representation of taking the ith index of the given set\n representation\"\"\"\n out = []\n for size_minus_one, set_repr_size in enumerate(set_repr):\n size = size_minus_one + 1\n rel_range = SIZE2RANGE[size]\n to_compare = i[rel_range[0] : rel_range[1]]\n result = np.zeros_like(set_repr_size)\n c = set_repr_size.cumsum(0)\n nonzero_x_idxs, nonzero_y_idxs = np.where(c == to_compare)\n x_idxs, mask = np.unique(nonzero_y_idxs, return_index=True)\n result[nonzero_x_idxs[mask], x_idxs] = 1\n out.append(result)\n return out\n\n\n# def index_func(i, set_repr):\n# global SIZE2RANGE\n# out = []\n# i = i.astype(np.uint8)\n# # print(\"HERE\", i)\n# if all(i == 0): # no zero based indexing for normal humans\n# return [\n# np.zeros(set_repr_size.shape, dtype=np.uint8)\n# for set_repr_size in set_repr\n# ]\n# for size_minus_one, set_repr_size in enumerate(set_repr):\n# size = size_minus_one + 1\n# rel_range = SIZE2RANGE[size]\n# to_compare = np.repeat(\n# [i[rel_range[0] : rel_range[1]]], set_repr_size.shape[0], axis=0\n# )\n\n# x, y = np.where(set_repr_size.cumsum(0) == to_compare)\n# new_repr = np.zeros(set_repr_size.shape)\n# new_repr[x, y] = 1\n# out.append(new_repr.astype(np.uint8))\n# return out\n\n\ndef subset_func(set_repr_0, set_repr_1):\n out = np.array([])\n for size, (set_0, set_1) in enumerate(zip(set_repr_0, set_repr_1)):\n subset = (\n np.apply_along_axis(max, 0, (set_0 & (1 - set_1))) == 0\n ) # no instances of 0 1\n # print(subset)\n # prevent vacous satisfcation of the subset relation\n at_least_one = np.apply_along_axis(sum, 0, set_0) > 0\n # print(at_least_one)\n out = np.append(out, (subset & at_least_one))\n # out = np.append(out, subset)\n return out.astype(bool)\n\n\ndef diff_func(set_repr_0, set_repr_1):\n out = []\n for size, (set_0, set_1) in enumerate(zip(set_repr_0, set_repr_1)):\n # print(set_0, set_1)\n out.append(set_0 & (1 - set_1))\n # [np.append(out, )\n return out\n\n\ndef mod_func(x, y):\n zero_indices = y <= 0\n y_with_ones = np.array(y[:], copy=True)\n y_with_ones[zero_indices] = 1\n out = x % y_with_ones\n out[zero_indices] = 0\n return out\n\n\ndef div_func(x, y):\n zero_indices = y <= 0\n y_with_ones = np.array(y[:], copy=True)\n y_with_ones[zero_indices] = 1\n out = x / y_with_ones\n out[zero_indices] = 0\n return vectorized_round(out, 2)\n\n\ndef init_operators(max_model_size, number_of_subsets=4):\n cur_cumul = 0\n SIZE2RANGE = dict()\n for size in range(1, max_model_size + 1):\n SIZE2RANGE[size] = (\n sum(number_of_subsets ** s for s in range(1, size)),\n sum(number_of_subsets ** s for s in range(1, size + 1)),\n )\n return {\n \"index\": Operator(\n \"index\",\n lambda i, s, size2range=SIZE2RANGE: index_func(i, s, size2range),\n (int, set),\n set,\n ),\n \"diff\": Operator(\n \"diff\",\n diff_func, # (s1.get_set(model) - s2.get_set(model))\n (set, set),\n set,\n ),\n \"subset\": Operator(\"subset\", subset_func, (set, set), bool),\n \">f\": Operator(\">f\", lambda x, y: x > y, (float, float), bool),\n \"=f\": Operator(\n \"=f\", lambda x, y: vectorized_isclose(x, y), (float, float), bool\n ),\n \">\": Operator(\">\", lambda x, y: x > y, (int, int), bool),\n \">=\": Operator(\">=\", lambda x, y: x >= y, (int, int), bool),\n \"=\": Operator(\"=\", lambda x, y: x == y, (int, int), bool),\n \"/\": Operator(\"/\", div_func, (int, int), float),\n \"-\": Operator(\n \"-\", lambda x, y: x.astype(int) - y.astype(int), (int, int), int\n ),\n \"+\": Operator(\n \"+\", lambda x, y: x.astype(int) + y.astype(int), (int, int), int\n ),\n \"card\": Operator(\n \"card\",\n lambda set_repr_all: np.array(\n list(\n chain.from_iterable(\n np.apply_along_axis(sum, 0, set_repr)\n for set_repr in set_repr_all\n )\n )\n ),\n (set,),\n int,\n ),\n \"intersection\": Operator(\n \"intersection\",\n lambda x_repr, y_repr: [x & y for x, y in zip(x_repr, y_repr)],\n # lambda model, x, y: tuple(\n # x.char_func(obj) and y.char_func(obj) for obj in model\n # ),\n (set, set),\n set,\n ),\n \"union\": Operator(\n \"union\",\n lambda x_repr, y_repr: [x | y for x, y in zip(x_repr, y_repr)],\n (set, set),\n set,\n ),\n \"and\": Operator(\"and\", lambda x, y: x & y, (bool, bool), bool),\n \"or\": Operator(\"or\", lambda x, y: x | y, (bool, bool), bool),\n \"not\": Operator(\"not\", lambda x: np.invert(x), (bool,), bool),\n \"%\": Operator(\"%\", mod_func, (int, int), int),\n }\n\n\nOPERATORS = {\n \"index\": Operator(\"index\", index_func, (int, set), set),\n \"diff\": Operator(\n \"diff\",\n diff_func, # (s1.get_set(model) - s2.get_set(model))\n (set, set),\n set,\n ),\n \"subset\": Operator(\"subset\", subset_func, (set, set), bool),\n \">f\": Operator(\">f\", lambda x, y: x > y, (float, float), bool),\n \"=f\": Operator(\n \"=f\", lambda x, y: vectorized_isclose(x, y), (float, float), bool\n ),\n \">\": Operator(\">\", lambda x, y: x > y, (int, int), bool),\n \">=\": Operator(\">=\", lambda x, y: x >= y, (int, int), bool),\n \"=\": Operator(\"=\", lambda x, y: x == y, (int, int), bool),\n \"/\": Operator(\"/\", div_func, (int, int), float),\n \"-\": Operator(\n \"-\", lambda x, y: x.astype(int) - y.astype(int), (int, int), int\n ),\n \"+\": Operator(\n \"+\", lambda x, y: x.astype(int) + y.astype(int), (int, int), int\n ),\n \"card\": Operator(\n \"card\",\n lambda set_repr_all: np.array(\n list(\n chain.from_iterable(\n np.apply_along_axis(sum, 0, set_repr)\n for set_repr in set_repr_all\n )\n )\n ),\n (set,),\n int,\n ),\n \"intersection\": Operator(\n \"intersection\",\n lambda x_repr, y_repr: [x & y for x, y in zip(x_repr, y_repr)],\n # lambda model, x, y: tuple(\n # x.char_func(obj) and y.char_func(obj) for obj in model\n # ),\n (set, set),\n set,\n ),\n \"union\": Operator(\n \"union\",\n lambda x_repr, y_repr: [x | y for x, y in zip(x_repr, y_repr)],\n (set, set),\n set,\n ),\n \"and\": Operator(\"and\", lambda x, y: x & y, (bool, bool), bool),\n \"or\": Operator(\"or\", lambda x, y: x | y, (bool, bool), bool),\n \"not\": Operator(\"not\", lambda x: np.invert(x), (bool,), bool),\n # \"empty\": Operator(\n # lambda model, x: get_cardinality(model, x) is 0,\n # (set,),\n # bool,\n # ),\n # \"nonempty\": Operator(\n # lambda model, x: len(x.get_set(model)) > 0, (set,), bool\n # ),\n # \"proportion\": Operator(\n # lambda model, X, Y, q: get_cardinality(model, X)\n # / get_cardinality(model, Y)\n # > q\n # if get_cardinality(model, Y) > 0\n # else 0,\n # (set, set, float),\n # bool,\n # )\n # ,\n \"%\": Operator(\"%\", mod_func, (int, int), int),\n}\n" ]
[ [ "numpy.invert", "numpy.unique", "numpy.append", "numpy.vectorize", "numpy.zeros_like", "numpy.apply_along_axis", "numpy.array", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jakubdabek/lightweight-effectiveness
[ "d6dd7d4cd96f22074a57ee1a36f534f8540438bf" ]
[ "effectiveness/mutation/mutation_calc.py" ]
[ "from __future__ import division\n\nimport sys\n\nimport pandas as pd\n\n\ndef calc_coverage(csv_file):\n \"\"\"Return the mutation coverage from the csv output of pitest\n Arguments\n -------------\n - csv_file: the path of the csv file storing the result of the mutation\n \"\"\"\n frame = pd.read_csv(\n csv_file, names=['class', 'name', 'mutation', 'operation', 'line', 'killed', 'test']\n )\n mutations = len(frame)\n if mutations == 0:\n return None\n are_killed = frame.killed.str.contains('KILLED').sum(0) > 1\n if are_killed:\n killed = frame.killed.value_counts()['KILLED']\n else:\n return 0\n return killed / mutations\n\n\ndef get_number_mutation(csv_file):\n \"\"\"Return the number of mutations done for a class\n Arguments\n -------------\n - csv_file: the path of the csv file storing the result of the mutation\n \"\"\"\n frame = pd.read_csv(\n csv_file, names=['class', 'name', 'mutation', 'operation', 'line', 'killed', 'test']\n )\n return len(frame)\n\n\nif __name__ == '__main__':\n path = sys.argv[1]\n coverage = calc_coverage(path)\n print('Mutation coverage computed = {}'.format(coverage))\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
imabackstabber/mmcv
[ "b272c09b463f00fd7fdd455f7bd4a055f9995521", "b272c09b463f00fd7fdd455f7bd4a055f9995521", "b272c09b463f00fd7fdd455f7bd4a055f9995521", "b272c09b463f00fd7fdd455f7bd4a055f9995521", "b272c09b463f00fd7fdd455f7bd4a055f9995521", "b272c09b463f00fd7fdd455f7bd4a055f9995521" ]
[ "mmcv/cnn/bricks/non_local.py", "tests/test_ops/test_tensorrt.py", "mmcv/cnn/bricks/transformer.py", "mmcv/device/ipu/utils.py", "mmcv/visualization/optflow.py", "mmcv/image/colorspace.py" ]
[ "# Copyright (c) OpenMMLab. All rights reserved.\nfrom abc import ABCMeta\n\nimport torch\nimport torch.nn as nn\n\nfrom ..utils import constant_init, normal_init\nfrom .conv_module import ConvModule\nfrom .registry import PLUGIN_LAYERS\n\n\nclass _NonLocalNd(nn.Module, metaclass=ABCMeta):\n \"\"\"Basic Non-local module.\n\n This module is proposed in\n \"Non-local Neural Networks\"\n Paper reference: https://arxiv.org/abs/1711.07971\n Code reference: https://github.com/AlexHex7/Non-local_pytorch\n\n Args:\n in_channels (int): Channels of the input feature map.\n reduction (int): Channel reduction ratio. Default: 2.\n use_scale (bool): Whether to scale pairwise_weight by\n `1/sqrt(inter_channels)` when the mode is `embedded_gaussian`.\n Default: True.\n conv_cfg (None | dict): The config dict for convolution layers.\n If not specified, it will use `nn.Conv2d` for convolution layers.\n Default: None.\n norm_cfg (None | dict): The config dict for normalization layers.\n Default: None. (This parameter is only applicable to conv_out.)\n mode (str): Options are `gaussian`, `concatenation`,\n `embedded_gaussian` and `dot_product`. Default: embedded_gaussian.\n \"\"\"\n\n def __init__(self,\n in_channels,\n reduction=2,\n use_scale=True,\n conv_cfg=None,\n norm_cfg=None,\n mode='embedded_gaussian',\n **kwargs):\n super().__init__()\n self.in_channels = in_channels\n self.reduction = reduction\n self.use_scale = use_scale\n self.inter_channels = max(in_channels // reduction, 1)\n self.mode = mode\n\n if mode not in [\n 'gaussian', 'embedded_gaussian', 'dot_product', 'concatenation'\n ]:\n raise ValueError(\"Mode should be in 'gaussian', 'concatenation', \"\n f\"'embedded_gaussian' or 'dot_product', but got \"\n f'{mode} instead.')\n\n # g, theta, phi are defaulted as `nn.ConvNd`.\n # Here we use ConvModule for potential usage.\n self.g = ConvModule(\n self.in_channels,\n self.inter_channels,\n kernel_size=1,\n conv_cfg=conv_cfg,\n act_cfg=None)\n self.conv_out = ConvModule(\n self.inter_channels,\n self.in_channels,\n kernel_size=1,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n act_cfg=None)\n\n if self.mode != 'gaussian':\n self.theta = ConvModule(\n self.in_channels,\n self.inter_channels,\n kernel_size=1,\n conv_cfg=conv_cfg,\n act_cfg=None)\n self.phi = ConvModule(\n self.in_channels,\n self.inter_channels,\n kernel_size=1,\n conv_cfg=conv_cfg,\n act_cfg=None)\n\n if self.mode == 'concatenation':\n self.concat_project = ConvModule(\n self.inter_channels * 2,\n 1,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=False,\n act_cfg=dict(type='ReLU'))\n\n self.init_weights(**kwargs)\n\n def init_weights(self, std=0.01, zeros_init=True):\n if self.mode != 'gaussian':\n for m in [self.g, self.theta, self.phi]:\n normal_init(m.conv, std=std)\n else:\n normal_init(self.g.conv, std=std)\n if zeros_init:\n if self.conv_out.norm_cfg is None:\n constant_init(self.conv_out.conv, 0)\n else:\n constant_init(self.conv_out.norm, 0)\n else:\n if self.conv_out.norm_cfg is None:\n normal_init(self.conv_out.conv, std=std)\n else:\n normal_init(self.conv_out.norm, std=std)\n\n def gaussian(self, theta_x, phi_x):\n # NonLocal1d pairwise_weight: [N, H, H]\n # NonLocal2d pairwise_weight: [N, HxW, HxW]\n # NonLocal3d pairwise_weight: [N, TxHxW, TxHxW]\n pairwise_weight = torch.matmul(theta_x, phi_x)\n pairwise_weight = pairwise_weight.softmax(dim=-1)\n return pairwise_weight\n\n def embedded_gaussian(self, theta_x, phi_x):\n # NonLocal1d pairwise_weight: [N, H, H]\n # NonLocal2d pairwise_weight: [N, HxW, HxW]\n # NonLocal3d pairwise_weight: [N, TxHxW, TxHxW]\n pairwise_weight = torch.matmul(theta_x, phi_x)\n if self.use_scale:\n # theta_x.shape[-1] is `self.inter_channels`\n pairwise_weight /= theta_x.shape[-1]**0.5\n pairwise_weight = pairwise_weight.softmax(dim=-1)\n return pairwise_weight\n\n def dot_product(self, theta_x, phi_x):\n # NonLocal1d pairwise_weight: [N, H, H]\n # NonLocal2d pairwise_weight: [N, HxW, HxW]\n # NonLocal3d pairwise_weight: [N, TxHxW, TxHxW]\n pairwise_weight = torch.matmul(theta_x, phi_x)\n pairwise_weight /= pairwise_weight.shape[-1]\n return pairwise_weight\n\n def concatenation(self, theta_x, phi_x):\n # NonLocal1d pairwise_weight: [N, H, H]\n # NonLocal2d pairwise_weight: [N, HxW, HxW]\n # NonLocal3d pairwise_weight: [N, TxHxW, TxHxW]\n h = theta_x.size(2)\n w = phi_x.size(3)\n theta_x = theta_x.repeat(1, 1, 1, w)\n phi_x = phi_x.repeat(1, 1, h, 1)\n\n concat_feature = torch.cat([theta_x, phi_x], dim=1)\n pairwise_weight = self.concat_project(concat_feature)\n n, _, h, w = pairwise_weight.size()\n pairwise_weight = pairwise_weight.view(n, h, w)\n pairwise_weight /= pairwise_weight.shape[-1]\n\n return pairwise_weight\n\n def forward(self, x):\n # Assume `reduction = 1`, then `inter_channels = C`\n # or `inter_channels = C` when `mode=\"gaussian\"`\n\n # NonLocal1d x: [N, C, H]\n # NonLocal2d x: [N, C, H, W]\n # NonLocal3d x: [N, C, T, H, W]\n n = x.size(0)\n\n # NonLocal1d g_x: [N, H, C]\n # NonLocal2d g_x: [N, HxW, C]\n # NonLocal3d g_x: [N, TxHxW, C]\n g_x = self.g(x).view(n, self.inter_channels, -1)\n g_x = g_x.permute(0, 2, 1)\n\n # NonLocal1d theta_x: [N, H, C], phi_x: [N, C, H]\n # NonLocal2d theta_x: [N, HxW, C], phi_x: [N, C, HxW]\n # NonLocal3d theta_x: [N, TxHxW, C], phi_x: [N, C, TxHxW]\n if self.mode == 'gaussian':\n theta_x = x.view(n, self.in_channels, -1)\n theta_x = theta_x.permute(0, 2, 1)\n if self.sub_sample:\n phi_x = self.phi(x).view(n, self.in_channels, -1)\n else:\n phi_x = x.view(n, self.in_channels, -1)\n elif self.mode == 'concatenation':\n theta_x = self.theta(x).view(n, self.inter_channels, -1, 1)\n phi_x = self.phi(x).view(n, self.inter_channels, 1, -1)\n else:\n theta_x = self.theta(x).view(n, self.inter_channels, -1)\n theta_x = theta_x.permute(0, 2, 1)\n phi_x = self.phi(x).view(n, self.inter_channels, -1)\n\n pairwise_func = getattr(self, self.mode)\n # NonLocal1d pairwise_weight: [N, H, H]\n # NonLocal2d pairwise_weight: [N, HxW, HxW]\n # NonLocal3d pairwise_weight: [N, TxHxW, TxHxW]\n pairwise_weight = pairwise_func(theta_x, phi_x)\n\n # NonLocal1d y: [N, H, C]\n # NonLocal2d y: [N, HxW, C]\n # NonLocal3d y: [N, TxHxW, C]\n y = torch.matmul(pairwise_weight, g_x)\n # NonLocal1d y: [N, C, H]\n # NonLocal2d y: [N, C, H, W]\n # NonLocal3d y: [N, C, T, H, W]\n y = y.permute(0, 2, 1).contiguous().reshape(n, self.inter_channels,\n *x.size()[2:])\n\n output = x + self.conv_out(y)\n\n return output\n\n\nclass NonLocal1d(_NonLocalNd):\n \"\"\"1D Non-local module.\n\n Args:\n in_channels (int): Same as `NonLocalND`.\n sub_sample (bool): Whether to apply max pooling after pairwise\n function (Note that the `sub_sample` is applied on spatial only).\n Default: False.\n conv_cfg (None | dict): Same as `NonLocalND`.\n Default: dict(type='Conv1d').\n \"\"\"\n\n def __init__(self,\n in_channels,\n sub_sample=False,\n conv_cfg=dict(type='Conv1d'),\n **kwargs):\n super().__init__(in_channels, conv_cfg=conv_cfg, **kwargs)\n\n self.sub_sample = sub_sample\n\n if sub_sample:\n max_pool_layer = nn.MaxPool1d(kernel_size=2)\n self.g = nn.Sequential(self.g, max_pool_layer)\n if self.mode != 'gaussian':\n self.phi = nn.Sequential(self.phi, max_pool_layer)\n else:\n self.phi = max_pool_layer\n\n\n@PLUGIN_LAYERS.register_module()\nclass NonLocal2d(_NonLocalNd):\n \"\"\"2D Non-local module.\n\n Args:\n in_channels (int): Same as `NonLocalND`.\n sub_sample (bool): Whether to apply max pooling after pairwise\n function (Note that the `sub_sample` is applied on spatial only).\n Default: False.\n conv_cfg (None | dict): Same as `NonLocalND`.\n Default: dict(type='Conv2d').\n \"\"\"\n\n _abbr_ = 'nonlocal_block'\n\n def __init__(self,\n in_channels,\n sub_sample=False,\n conv_cfg=dict(type='Conv2d'),\n **kwargs):\n super().__init__(in_channels, conv_cfg=conv_cfg, **kwargs)\n\n self.sub_sample = sub_sample\n\n if sub_sample:\n max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2))\n self.g = nn.Sequential(self.g, max_pool_layer)\n if self.mode != 'gaussian':\n self.phi = nn.Sequential(self.phi, max_pool_layer)\n else:\n self.phi = max_pool_layer\n\n\nclass NonLocal3d(_NonLocalNd):\n \"\"\"3D Non-local module.\n\n Args:\n in_channels (int): Same as `NonLocalND`.\n sub_sample (bool): Whether to apply max pooling after pairwise\n function (Note that the `sub_sample` is applied on spatial only).\n Default: False.\n conv_cfg (None | dict): Same as `NonLocalND`.\n Default: dict(type='Conv3d').\n \"\"\"\n\n def __init__(self,\n in_channels,\n sub_sample=False,\n conv_cfg=dict(type='Conv3d'),\n **kwargs):\n super().__init__(in_channels, conv_cfg=conv_cfg, **kwargs)\n self.sub_sample = sub_sample\n\n if sub_sample:\n max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2))\n self.g = nn.Sequential(self.g, max_pool_layer)\n if self.mode != 'gaussian':\n self.phi = nn.Sequential(self.phi, max_pool_layer)\n else:\n self.phi = max_pool_layer\n", "# Copyright (c) OpenMMLab. All rights reserved.\nimport os\nfrom functools import partial\nfrom typing import Callable\n\nimport numpy as np\nimport onnx\nimport pytest\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\ntry:\n from mmcv.tensorrt import (TRTWrapper, is_tensorrt_plugin_loaded, onnx2trt,\n save_trt_engine)\nexcept ImportError:\n pytest.skip(\n 'TensorRT should be installed from source.', allow_module_level=True)\n\nif not torch.cuda.is_available():\n pytest.skip(\n 'CUDA is required for this test module', allow_module_level=True)\n\nif not is_tensorrt_plugin_loaded():\n pytest.skip(\n 'Test requires to complie TensorRT plugins in mmcv',\n allow_module_level=True)\n\n\nclass WrapFunction(nn.Module):\n\n def __init__(self, wrapped_function):\n super().__init__()\n self.wrapped_function = wrapped_function\n\n def forward(self, *args, **kwargs):\n return self.wrapped_function(*args, **kwargs)\n\n\nonnx_file = 'tmp.onnx'\ntrt_file = 'tmp.engine'\n\n\ndef test_roialign():\n try:\n from mmcv.ops import RoIAlign\n except (ImportError, ModuleNotFoundError):\n pytest.skip('test requires compilation')\n\n # trt config\n fp16_mode = False\n max_workspace_size = 1 << 30\n\n # roi align config\n pool_h = 2\n pool_w = 2\n spatial_scale = 1.0\n sampling_ratio = 2\n\n inputs = [([[[[1., 2.], [3., 4.]]]], [[0., 0., 0., 1., 1.]]),\n ([[[[1., 2.], [3., 4.]], [[4., 3.],\n [2., 1.]]]], [[0., 0., 0., 1., 1.]]),\n ([[[[1., 2., 5., 6.], [3., 4., 7., 8.], [9., 10., 13., 14.],\n [11., 12., 15., 16.]]]], [[0., 0., 0., 3., 3.]])]\n\n wrapped_model = RoIAlign((pool_w, pool_h), spatial_scale, sampling_ratio,\n 'avg', True).cuda()\n for case in inputs:\n np_input = np.array(case[0], dtype=np.float32)\n np_rois = np.array(case[1], dtype=np.float32)\n input = torch.from_numpy(np_input).cuda()\n rois = torch.from_numpy(np_rois).cuda()\n\n with torch.no_grad():\n torch.onnx.export(\n wrapped_model, (input, rois),\n onnx_file,\n export_params=True,\n keep_initializers_as_inputs=True,\n input_names=['input', 'rois'],\n output_names=['roi_feat'],\n opset_version=11)\n onnx_model = onnx.load(onnx_file)\n\n # create trt engine and wrapper\n opt_shape_dict = {\n 'input': [list(input.shape),\n list(input.shape),\n list(input.shape)],\n 'rois': [list(rois.shape),\n list(rois.shape),\n list(rois.shape)]\n }\n trt_engine = onnx2trt(\n onnx_model,\n opt_shape_dict,\n fp16_mode=fp16_mode,\n max_workspace_size=max_workspace_size)\n save_trt_engine(trt_engine, trt_file)\n trt_model = TRTWrapper(trt_file, ['input', 'rois'], ['roi_feat'])\n\n with torch.no_grad():\n trt_outputs = trt_model({'input': input, 'rois': rois})\n trt_roi_feat = trt_outputs['roi_feat']\n\n # compute pytorch_output\n with torch.no_grad():\n pytorch_roi_feat = wrapped_model(input, rois)\n\n # allclose\n if os.path.exists(onnx_file):\n os.remove(onnx_file)\n if os.path.exists(trt_file):\n os.remove(trt_file)\n assert torch.allclose(pytorch_roi_feat, trt_roi_feat)\n\n\ndef test_nms():\n try:\n import mmcv\n from mmcv.ops import nms\n except (ImportError, ModuleNotFoundError):\n pytest.skip('test requires compilation')\n os.environ['ONNX_BACKEND'] = 'MMCVTensorRT'\n # trt config\n fp16_mode = False\n max_workspace_size = 1 << 30\n data = mmcv.load('./tests/data/batched_nms_data.pkl')\n boxes = torch.from_numpy(data['boxes']).cuda()\n scores = torch.from_numpy(data['scores']).cuda()\n nms = partial(\n nms, iou_threshold=0.7, offset=0, score_threshold=0.1, max_num=100)\n wrapped_model = WrapFunction(nms)\n wrapped_model.cpu().eval()\n with torch.no_grad():\n torch.onnx.export(\n wrapped_model, (boxes.detach().cpu(), scores.detach().cpu()),\n onnx_file,\n export_params=True,\n keep_initializers_as_inputs=True,\n input_names=['boxes', 'scores'],\n output_names=['dets', 'inds'],\n opset_version=11)\n onnx_model = onnx.load(onnx_file)\n\n # create trt engine and wrapper\n opt_shape_dict = {\n 'boxes': [list(boxes.shape),\n list(boxes.shape),\n list(boxes.shape)],\n 'scores': [list(scores.shape),\n list(scores.shape),\n list(scores.shape)]\n }\n trt_engine = onnx2trt(\n onnx_model,\n opt_shape_dict,\n fp16_mode=fp16_mode,\n max_workspace_size=max_workspace_size)\n save_trt_engine(trt_engine, trt_file)\n trt_model = TRTWrapper(trt_file, ['boxes', 'scores'], ['dets', 'inds'])\n\n with torch.no_grad():\n trt_outputs = trt_model({'boxes': boxes, 'scores': scores})\n trt_dets = trt_outputs['dets']\n trt_inds = trt_outputs['inds']\n trt_inds = trt_inds.long()\n\n # compute pytorch_output\n with torch.no_grad():\n pytorch_outputs = wrapped_model(boxes, scores)\n pytorch_dets, pytorch_inds = pytorch_outputs\n\n # allclose\n if os.path.exists(onnx_file):\n os.remove(onnx_file)\n if os.path.exists(trt_file):\n os.remove(trt_file)\n num_boxes = pytorch_dets.shape[0]\n trt_dets = trt_dets[:num_boxes, ...]\n trt_inds = trt_inds[:num_boxes]\n trt_scores = trt_dets[:, 4]\n pytorch_scores = pytorch_dets[:, 4]\n os.environ.pop('ONNX_BACKEND')\n assert torch.allclose(pytorch_scores, trt_scores, atol=1e-3)\n assert torch.equal(pytorch_inds, trt_inds)\n\n\ndef test_batched_nms():\n try:\n import mmcv\n from mmcv.ops import batched_nms\n except (ImportError, ModuleNotFoundError):\n pytest.skip('test requires compilation')\n\n # trt config\n os.environ['ONNX_BACKEND'] = 'MMCVTensorRT'\n fp16_mode = False\n max_workspace_size = 1 << 30\n data = mmcv.load('./tests/data/batched_nms_data.pkl')\n nms_cfg = dict(type='nms', iou_threshold=0.7, score_threshold=0.1)\n boxes = torch.from_numpy(data['boxes']).cuda()\n scores = torch.from_numpy(data['scores']).cuda()\n idxs = torch.from_numpy(data['idxs']).cuda()\n class_agnostic = False\n\n nms = partial(batched_nms, nms_cfg=nms_cfg, class_agnostic=class_agnostic)\n wrapped_model = WrapFunction(nms)\n wrapped_model.cpu().eval()\n input_data = (boxes.detach().cpu(), scores.detach().cpu(),\n idxs.detach().cpu())\n input_names = ['boxes', 'scores', 'idxs']\n output_names = ['dets', 'inds']\n with torch.no_grad():\n torch.onnx.export(\n wrapped_model,\n input_data,\n onnx_file,\n export_params=True,\n keep_initializers_as_inputs=True,\n input_names=input_names,\n output_names=output_names,\n opset_version=11)\n onnx_model = onnx.load(onnx_file)\n # create trt engine and wrapper\n opt_shape_dict = {\n 'boxes': [list(boxes.shape),\n list(boxes.shape),\n list(boxes.shape)],\n 'scores': [list(scores.shape),\n list(scores.shape),\n list(scores.shape)],\n 'idxs': [list(idxs.shape),\n list(idxs.shape),\n list(idxs.shape)]\n }\n trt_engine = onnx2trt(\n onnx_model,\n opt_shape_dict,\n fp16_mode=fp16_mode,\n max_workspace_size=max_workspace_size)\n save_trt_engine(trt_engine, trt_file)\n trt_model = TRTWrapper(trt_file, input_names, output_names)\n\n with torch.no_grad():\n trt_outputs = trt_model({\n 'boxes': boxes,\n 'scores': scores,\n 'idxs': idxs\n })\n trt_dets = trt_outputs['dets']\n trt_inds = trt_outputs['inds']\n trt_inds = trt_inds.long()\n\n # compute pytorch_output\n with torch.no_grad():\n pytorch_outputs = wrapped_model(boxes, scores, idxs)\n pytorch_dets, pytorch_inds = pytorch_outputs\n # allclose\n if os.path.exists(onnx_file):\n os.remove(onnx_file)\n if os.path.exists(trt_file):\n os.remove(trt_file)\n num_boxes = pytorch_dets.shape[0]\n trt_dets = trt_dets[:num_boxes, ...]\n trt_inds = trt_inds[:num_boxes]\n trt_scores = trt_dets[:, 4]\n pytorch_scores = pytorch_dets[:, 4]\n\n os.environ.pop('ONNX_BACKEND')\n assert torch.allclose(pytorch_scores, trt_scores)\n assert torch.equal(pytorch_inds, trt_inds)\n\n\ndef test_scatternd():\n\n def func(data):\n data[:, :-2] += 1\n data[:2, :] -= 1\n return data\n\n data = torch.zeros(4, 4).cuda()\n wrapped_model = WrapFunction(func).eval().cuda()\n\n input_names = ['input']\n output_names = ['output']\n\n with torch.no_grad():\n torch.onnx.export(\n wrapped_model, (data.clone(), ),\n onnx_file,\n export_params=True,\n keep_initializers_as_inputs=True,\n input_names=input_names,\n output_names=output_names,\n opset_version=11)\n\n onnx_model = onnx.load(onnx_file)\n\n # create trt engine and wrapper\n opt_shape_dict = {\n 'input': [list(data.shape),\n list(data.shape),\n list(data.shape)],\n }\n # trt config\n fp16_mode = False\n max_workspace_size = 1 << 30\n\n trt_engine = onnx2trt(\n onnx_model,\n opt_shape_dict,\n fp16_mode=fp16_mode,\n max_workspace_size=max_workspace_size)\n\n save_trt_engine(trt_engine, trt_file)\n trt_model = TRTWrapper(trt_file, input_names, output_names)\n\n with torch.no_grad():\n trt_outputs = trt_model({'input': data.clone()})\n trt_results = trt_outputs['output']\n\n # compute pytorch_output\n with torch.no_grad():\n pytorch_results = wrapped_model(data.clone())\n\n # allclose\n if os.path.exists(onnx_file):\n os.remove(onnx_file)\n if os.path.exists(trt_file):\n os.remove(trt_file)\n assert torch.allclose(pytorch_results, trt_results)\n\n\ndef test_deform_conv():\n try:\n from mmcv.ops import DeformConv2dPack\n except (ImportError, ModuleNotFoundError):\n pytest.skip('test requires compilation')\n\n input = [[[[1., 2., 3.], [0., 1., 2.], [3., 5., 2.]]]]\n offset_weight = [[[0.1, 0.4, 0.6, 0.1]], [[0.3, 0.2, 0.1, 0.3]],\n [[0.5, 0.5, 0.2, 0.8]], [[0.8, 0.3, 0.9, 0.1]],\n [[0.3, 0.1, 0.2, 0.5]], [[0.3, 0.7, 0.5, 0.3]],\n [[0.6, 0.2, 0.5, 0.3]], [[0.4, 0.1, 0.8, 0.4]]]\n offset_bias = [0.7, 0.1, 0.8, 0.5, 0.6, 0.5, 0.4, 0.7]\n deform_weight = [[[0.4, 0.2, 0.1, 0.9]]]\n\n c_in = 1\n c_out = 1\n x = torch.Tensor(input).cuda()\n x.requires_grad = True\n model = DeformConv2dPack(c_in, c_out, 2, stride=1, padding=0)\n model.conv_offset.weight.data = torch.nn.Parameter(\n torch.Tensor(offset_weight).reshape(8, 1, 2, 2))\n model.conv_offset.bias.data = torch.nn.Parameter(\n torch.Tensor(offset_bias).reshape(8))\n model.weight.data = torch.nn.Parameter(\n torch.Tensor(deform_weight).reshape(1, 1, 2, 2))\n model.cuda().eval()\n\n input_names = ['input']\n output_names = ['output']\n\n with torch.no_grad():\n torch.onnx.export(\n model, (x.clone(), ),\n onnx_file,\n export_params=True,\n keep_initializers_as_inputs=True,\n input_names=input_names,\n output_names=output_names,\n opset_version=11)\n\n onnx_model = onnx.load(onnx_file)\n\n # create trt engine and wrapper\n opt_shape_dict = {\n 'input': [list(x.shape), list(x.shape),\n list(x.shape)],\n }\n # trt config\n fp16_mode = False\n max_workspace_size = 1 << 30\n\n trt_engine = onnx2trt(\n onnx_model,\n opt_shape_dict,\n fp16_mode=fp16_mode,\n max_workspace_size=max_workspace_size)\n\n save_trt_engine(trt_engine, trt_file)\n trt_model = TRTWrapper(trt_file, input_names, output_names)\n\n with torch.no_grad():\n trt_outputs = trt_model({'input': x.clone()})\n trt_results = trt_outputs['output']\n\n # compute pytorch_output\n with torch.no_grad():\n pytorch_results = model(x.clone())\n\n # allclose\n if os.path.exists(onnx_file):\n os.remove(onnx_file)\n if os.path.exists(trt_file):\n os.remove(trt_file)\n assert torch.allclose(pytorch_results, trt_results)\n\n\[email protected]('with_bias', [True, False])\ndef test_modulated_deform_conv(with_bias):\n try:\n from mmcv.ops import ModulatedDeformConv2dPack\n except (ImportError, ModuleNotFoundError):\n pytest.skip('test requires compilation')\n\n input = [[[[1., 2., 3.], [0., 1., 2.], [3., 5., 2.]]]]\n\n x = torch.Tensor(input).cuda()\n model = ModulatedDeformConv2dPack(\n 1,\n 1,\n kernel_size=(2, 2),\n stride=1,\n padding=1,\n deform_groups=1,\n bias=with_bias)\n model.weight.data.fill_(1.)\n model.type(torch.float32)\n model = model.cuda().eval()\n\n input_names = ['input']\n output_names = ['output']\n\n with torch.no_grad():\n torch.onnx.export(\n model, (x.clone(), ),\n onnx_file,\n export_params=True,\n keep_initializers_as_inputs=True,\n input_names=input_names,\n output_names=output_names,\n opset_version=11)\n\n onnx_model = onnx.load(onnx_file)\n\n # create trt engine and wrapper\n opt_shape_dict = {\n 'input': [list(x.shape), list(x.shape),\n list(x.shape)],\n }\n # trt config\n fp16_mode = False\n max_workspace_size = 1 << 30\n\n trt_engine = onnx2trt(\n onnx_model,\n opt_shape_dict,\n fp16_mode=fp16_mode,\n max_workspace_size=max_workspace_size)\n\n save_trt_engine(trt_engine, trt_file)\n trt_model = TRTWrapper(trt_file, input_names, output_names)\n\n with torch.no_grad():\n trt_outputs = trt_model({'input': x.clone()})\n trt_results = trt_outputs['output']\n\n # compute pytorch_output\n with torch.no_grad():\n pytorch_results = model(x.clone())\n\n # allclose\n if os.path.exists(onnx_file):\n os.remove(onnx_file)\n if os.path.exists(trt_file):\n os.remove(trt_file)\n torch.testing.assert_allclose(pytorch_results, trt_results)\n\n\[email protected]('mode', ['bilinear', 'nearest'])\[email protected]('padding_mode', ['zeros', 'border', 'reflection'])\[email protected]('align_corners', [True, False])\ndef test_grid_sample(mode, padding_mode, align_corners):\n from mmcv.onnx.symbolic import register_extra_symbolics\n\n register_extra_symbolics(11)\n\n input = torch.rand(1, 1, 10, 10).cuda()\n grid = torch.Tensor([[[1, 0, 0], [0, 1, 0]]])\n grid = F.affine_grid(grid, (1, 1, 15, 15)).type_as(input).cuda()\n\n def func(input, grid):\n return F.grid_sample(\n input,\n grid,\n mode=mode,\n padding_mode=padding_mode,\n align_corners=align_corners)\n\n wrapped_model = WrapFunction(func).eval().cuda()\n\n input_names = ['input', 'grid']\n output_names = ['output']\n\n with torch.no_grad():\n torch.onnx.export(\n wrapped_model, (input.clone(), grid.clone()),\n onnx_file,\n export_params=True,\n keep_initializers_as_inputs=True,\n input_names=input_names,\n output_names=output_names,\n opset_version=11)\n\n onnx_model = onnx.load(onnx_file)\n\n # create trt engine and wrapper\n opt_shape_dict = {\n 'input': [list(input.shape),\n list(input.shape),\n list(input.shape)],\n 'grid': [list(grid.shape),\n list(grid.shape),\n list(grid.shape)],\n }\n # trt config\n fp16_mode = False\n max_workspace_size = 1 << 30\n\n trt_engine = onnx2trt(\n onnx_model,\n opt_shape_dict,\n fp16_mode=fp16_mode,\n max_workspace_size=max_workspace_size)\n\n save_trt_engine(trt_engine, trt_file)\n trt_model = TRTWrapper(trt_file, input_names, output_names)\n\n with torch.no_grad():\n trt_outputs = trt_model({'input': input.clone(), 'grid': grid.clone()})\n trt_results = trt_outputs['output']\n\n # compute pytorch_output\n with torch.no_grad():\n pytorch_results = wrapped_model(input.clone(), grid.clone())\n\n # allclose\n if os.path.exists(onnx_file):\n os.remove(onnx_file)\n if os.path.exists(trt_file):\n os.remove(trt_file)\n assert torch.allclose(pytorch_results, trt_results)\n\n\[email protected]('func', [torch.cummax, torch.cummin])\ndef test_cummin_cummax(func: Callable):\n # Note generally `cummax` or `cummin` is exportable to ONNX\n # as long as the pytorch version >= 1.5.0, since `torch.cummax`\n # is only supported with torch >= 1.5.0.\n # But when `cummax` or `cummin` serves as an intermediate component\n # whose outputs is used as inputs for another modules, it's expected\n # that pytorch version must be >= 1.7.0. Otherwise error appears like:\n # `RuntimeError: tuple appears in op that does not forward tuples,\n # unsupported 'kind: prim::PythonOp`.\n from packaging import version\n if version.parse(torch.__version__) < version.parse('1.7.0'):\n pytest.skip('test_cummax_cummin should be ran with pytorch >= 1.7.0')\n\n opset = 11\n # register custom op `mmcv::cummax` and `mmcv::cummin`\n from mmcv.onnx.symbolic import register_extra_symbolics\n register_extra_symbolics(opset)\n\n input_list = [\n # arbitrary shape, e.g. 1-D, 2-D, 3-D, ...\n torch.rand((2, 3, 4, 1, 5)).cuda(),\n torch.rand(1).cuda()\n ]\n\n input_names = ['input']\n output_names = ['output', 'indices']\n\n for input in input_list:\n ndims = input.dim()\n # valid dim range is [-ndims, ndims-1]\n # test for all `dim` value which is valid\n for dim in range(-ndims, ndims):\n cummax_func = partial(func, dim=dim)\n wrapped_model = WrapFunction(cummax_func).eval().cuda()\n\n with torch.no_grad():\n torch.onnx.export(\n wrapped_model,\n input,\n onnx_file,\n export_params=True,\n keep_initializers_as_inputs=False,\n input_names=input_names,\n output_names=output_names,\n opset_version=opset)\n\n onnx_model = onnx.load(onnx_file)\n\n # create trt engine and wrapper\n opt_shape_dict = {\n 'input':\n [list(input.shape),\n list(input.shape),\n list(input.shape)]\n }\n # trt config\n fp16_mode = False\n max_workspace_size = 1 << 30\n\n trt_engine = onnx2trt(\n onnx_model,\n opt_shape_dict,\n fp16_mode=fp16_mode,\n max_workspace_size=max_workspace_size)\n\n # remove ONNX model after conversion\n if os.path.exists(onnx_file):\n os.remove(onnx_file)\n\n # save TensorRT model\n save_trt_engine(trt_engine, trt_file)\n\n # load and wrap TensorRT model\n trt_model = TRTWrapper(trt_file)\n\n # remove trt model after loading\n if os.path.exists(trt_file):\n os.remove(trt_file)\n\n # compute trt output\n with torch.no_grad():\n trt_results = trt_model({'input': input.contiguous().clone()})\n trt_output = trt_results['output']\n trt_indices = trt_results['indices']\n\n # compute pytorch output\n with torch.no_grad():\n pytorch_results = wrapped_model(input.clone())\n pytorch_output = pytorch_results[0]\n pytorch_indices = pytorch_results[1]\n\n torch.testing.assert_allclose(trt_output, pytorch_output)\n torch.testing.assert_allclose(trt_indices, pytorch_indices)\n\n\[email protected]('dynamic_export', [True, False])\[email protected]('fp16_mode', [True, False])\ndef test_instance_norm(dynamic_export, fp16_mode):\n\n n, c, h, w = 2, 3, 10, 10\n data = torch.randn(n, c, h, w).cuda()\n norm = nn.InstanceNorm2d(c, affine=True)\n\n wrapped_model = WrapFunction(norm).eval().cuda()\n\n input_names = ['input']\n output_names = ['output']\n dynamic_axes = None\n if dynamic_export:\n dynamic_axes = {\n 'input': {\n 0: 'n',\n 2: 'h',\n 3: 'w',\n },\n 'output': {\n 0: 'n',\n 2: 'h',\n 3: 'w',\n },\n }\n with torch.no_grad():\n torch.onnx.export(\n wrapped_model, (data.clone(), ),\n onnx_file,\n export_params=True,\n keep_initializers_as_inputs=True,\n input_names=input_names,\n output_names=output_names,\n dynamic_axes=dynamic_axes,\n opset_version=11)\n\n onnx_model = onnx.load(onnx_file)\n\n # create trt engine and wrapper\n if dynamic_export:\n opt_shape_dict = {\n 'input':\n [list(data.shape),\n list(data.shape), [2 * n, c, 2 * h, 2 * w]],\n }\n else:\n opt_shape_dict = {\n 'input': [list(data.shape),\n list(data.shape),\n list(data.shape)],\n }\n # trt config\n max_workspace_size = 1 << 30\n\n trt_engine = onnx2trt(\n onnx_model,\n opt_shape_dict,\n fp16_mode=fp16_mode,\n max_workspace_size=max_workspace_size)\n\n save_trt_engine(trt_engine, trt_file)\n trt_model = TRTWrapper(trt_file, input_names, output_names)\n\n with torch.no_grad():\n trt_outputs = trt_model({'input': data.clone()})\n trt_results = trt_outputs['output']\n\n # compute pytorch_output\n with torch.no_grad():\n pytorch_results = wrapped_model(data.clone())\n\n # allclose\n if os.path.exists(onnx_file):\n os.remove(onnx_file)\n if os.path.exists(trt_file):\n os.remove(trt_file)\n assert torch.allclose(pytorch_results, trt_results)\n\n\[email protected]('mode', ['top', 'bottom', 'left', 'right'])\ndef test_corner_pool(mode):\n try:\n from mmcv.ops import CornerPool\n except (ImportError, ModuleNotFoundError):\n pytest.skip('test requires compilation')\n\n opset = 11\n # register custom op `mmcv::MMCVCornerPool`\n from mmcv.onnx.symbolic import register_extra_symbolics\n register_extra_symbolics(opset)\n\n # trt config\n fp16_mode = False\n max_workspace_size = 1 << 30\n\n inputs = [\n # (n, c, h, w)\n torch.rand((2, 3, 5, 5)),\n torch.rand((1, 2, 4, 6)),\n torch.rand((2, 1, 3, 2)),\n ]\n\n class CornerPoolWrapper(CornerPool):\n\n def __init__(self, mode):\n super().__init__(mode)\n\n def forward(self, x):\n # no use `torch.cummax`, instead `corner_pool` is used\n # for various torch version\n return self.corner_pool.apply(x)\n\n wrapped_model = CornerPoolWrapper(mode).cuda()\n for input in inputs:\n input = input.cuda()\n\n with torch.no_grad():\n torch.onnx.export(\n wrapped_model, (input, ),\n onnx_file,\n export_params=True,\n keep_initializers_as_inputs=True,\n input_names=['input'],\n output_names=['output'],\n opset_version=opset)\n onnx_model = onnx.load(onnx_file)\n\n # create trt engine and wrapper\n opt_shape_dict = {\n 'input': [list(input.shape),\n list(input.shape),\n list(input.shape)],\n }\n trt_engine = onnx2trt(\n onnx_model,\n opt_shape_dict,\n fp16_mode=fp16_mode,\n max_workspace_size=max_workspace_size)\n save_trt_engine(trt_engine, trt_file)\n trt_model = TRTWrapper(trt_file, ['input'], ['output'])\n\n with torch.no_grad():\n trt_outputs = trt_model({'input': input})\n trt_pool_feat = trt_outputs['output']\n\n # compute pytorch_output\n with torch.no_grad():\n pytorch_pool_feat = wrapped_model(input)\n\n # allclose\n if os.path.exists(onnx_file):\n os.remove(onnx_file)\n if os.path.exists(trt_file):\n os.remove(trt_file)\n assert torch.allclose(pytorch_pool_feat, trt_pool_feat, atol=1e-5)\n", "# Copyright (c) OpenMMLab. All rights reserved.\nimport copy\nimport math\nimport warnings\nfrom typing import Sequence\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom mmcv.cnn import (Linear, build_activation_layer, build_conv_layer,\n build_norm_layer)\nfrom mmcv.runner.base_module import BaseModule, ModuleList, Sequential\nfrom mmcv.utils import (ConfigDict, build_from_cfg, deprecated_api_warning,\n to_2tuple)\nfrom .drop import build_dropout\nfrom .registry import (ATTENTION, FEEDFORWARD_NETWORK, POSITIONAL_ENCODING,\n TRANSFORMER_LAYER, TRANSFORMER_LAYER_SEQUENCE)\n\n# Avoid BC-breaking of importing MultiScaleDeformableAttention from this file\ntry:\n from mmcv.ops.multi_scale_deform_attn import \\\n MultiScaleDeformableAttention # noqa F401\n warnings.warn(\n ImportWarning(\n '``MultiScaleDeformableAttention`` has been moved to '\n '``mmcv.ops.multi_scale_deform_attn``, please change original path ' # noqa E501\n '``from mmcv.cnn.bricks.transformer import MultiScaleDeformableAttention`` ' # noqa E501\n 'to ``from mmcv.ops.multi_scale_deform_attn import MultiScaleDeformableAttention`` ' # noqa E501\n ))\n\nexcept ImportError:\n warnings.warn('Fail to import ``MultiScaleDeformableAttention`` from '\n '``mmcv.ops.multi_scale_deform_attn``, '\n 'You should install ``mmcv-full`` if you need this module. ')\n\n\ndef build_positional_encoding(cfg, default_args=None):\n \"\"\"Builder for Position Encoding.\"\"\"\n return build_from_cfg(cfg, POSITIONAL_ENCODING, default_args)\n\n\ndef build_attention(cfg, default_args=None):\n \"\"\"Builder for attention.\"\"\"\n return build_from_cfg(cfg, ATTENTION, default_args)\n\n\ndef build_feedforward_network(cfg, default_args=None):\n \"\"\"Builder for feed-forward network (FFN).\"\"\"\n return build_from_cfg(cfg, FEEDFORWARD_NETWORK, default_args)\n\n\ndef build_transformer_layer(cfg, default_args=None):\n \"\"\"Builder for transformer layer.\"\"\"\n return build_from_cfg(cfg, TRANSFORMER_LAYER, default_args)\n\n\ndef build_transformer_layer_sequence(cfg, default_args=None):\n \"\"\"Builder for transformer encoder and transformer decoder.\"\"\"\n return build_from_cfg(cfg, TRANSFORMER_LAYER_SEQUENCE, default_args)\n\n\nclass AdaptivePadding(nn.Module):\n \"\"\"Applies padding adaptively to the input.\n\n This module can make input get fully covered by filter\n you specified. It support two modes \"same\" and \"corner\". The\n \"same\" mode is same with \"SAME\" padding mode in TensorFlow, pad\n zero around input. The \"corner\" mode would pad zero\n to bottom right.\n\n Args:\n kernel_size (int | tuple): Size of the kernel. Default: 1.\n stride (int | tuple): Stride of the filter. Default: 1.\n dilation (int | tuple): Spacing between kernel elements.\n Default: 1.\n padding (str): Support \"same\" and \"corner\", \"corner\" mode\n would pad zero to bottom right, and \"same\" mode would\n pad zero around input. Default: \"corner\".\n\n Example:\n >>> kernel_size = 16\n >>> stride = 16\n >>> dilation = 1\n >>> input = torch.rand(1, 1, 15, 17)\n >>> adap_pad = AdaptivePadding(\n >>> kernel_size=kernel_size,\n >>> stride=stride,\n >>> dilation=dilation,\n >>> padding=\"corner\")\n >>> out = adap_pad(input)\n >>> assert (out.shape[2], out.shape[3]) == (16, 32)\n >>> input = torch.rand(1, 1, 16, 17)\n >>> out = adap_pad(input)\n >>> assert (out.shape[2], out.shape[3]) == (16, 32)\n \"\"\"\n\n def __init__(self, kernel_size=1, stride=1, dilation=1, padding='corner'):\n super().__init__()\n assert padding in ('same', 'corner')\n\n kernel_size = to_2tuple(kernel_size)\n stride = to_2tuple(stride)\n dilation = to_2tuple(dilation)\n\n self.padding = padding\n self.kernel_size = kernel_size\n self.stride = stride\n self.dilation = dilation\n\n def get_pad_shape(self, input_shape):\n \"\"\"Calculate the padding size of input.\n\n Args:\n input_shape (:obj:`torch.Size`): arrange as (H, W).\n\n Returns:\n Tuple[int]: The padding size along the\n original H and W directions\n \"\"\"\n input_h, input_w = input_shape\n kernel_h, kernel_w = self.kernel_size\n stride_h, stride_w = self.stride\n output_h = math.ceil(input_h / stride_h)\n output_w = math.ceil(input_w / stride_w)\n pad_h = max((output_h - 1) * stride_h +\n (kernel_h - 1) * self.dilation[0] + 1 - input_h, 0)\n pad_w = max((output_w - 1) * stride_w +\n (kernel_w - 1) * self.dilation[1] + 1 - input_w, 0)\n return pad_h, pad_w\n\n def forward(self, x):\n \"\"\"Add padding to `x`\n\n Args:\n x (Tensor): Input tensor has shape (B, C, H, W).\n\n Returns:\n Tensor: The tensor with adaptive padding\n \"\"\"\n pad_h, pad_w = self.get_pad_shape(x.size()[-2:])\n if pad_h > 0 or pad_w > 0:\n if self.padding == 'corner':\n x = F.pad(x, [0, pad_w, 0, pad_h])\n elif self.padding == 'same':\n x = F.pad(x, [\n pad_w // 2, pad_w - pad_w // 2, pad_h // 2,\n pad_h - pad_h // 2\n ])\n return x\n\n\nclass PatchEmbed(BaseModule):\n \"\"\"Image to Patch Embedding.\n\n We use a conv layer to implement PatchEmbed.\n\n Args:\n in_channels (int): The num of input channels. Default: 3\n embed_dims (int): The dimensions of embedding. Default: 768\n conv_type (str): The type of convolution\n to generate patch embedding. Default: \"Conv2d\".\n kernel_size (int): The kernel_size of embedding conv. Default: 16.\n stride (int): The slide stride of embedding conv.\n Default: 16.\n padding (int | tuple | string): The padding length of\n embedding conv. When it is a string, it means the mode\n of adaptive padding, support \"same\" and \"corner\" now.\n Default: \"corner\".\n dilation (int): The dilation rate of embedding conv. Default: 1.\n bias (bool): Bias of embed conv. Default: True.\n norm_cfg (dict, optional): Config dict for normalization layer.\n Default: None.\n input_size (int | tuple | None): The size of input, which will be\n used to calculate the out size. Only works when `dynamic_size`\n is False. Default: None.\n init_cfg (`mmcv.ConfigDict`, optional): The Config for initialization.\n Default: None.\n \"\"\"\n\n def __init__(self,\n in_channels=3,\n embed_dims=768,\n conv_type='Conv2d',\n kernel_size=16,\n stride=16,\n padding='corner',\n dilation=1,\n bias=True,\n norm_cfg=None,\n input_size=None,\n init_cfg=None):\n super().__init__(init_cfg=init_cfg)\n\n self.embed_dims = embed_dims\n if stride is None:\n stride = kernel_size\n\n kernel_size = to_2tuple(kernel_size)\n stride = to_2tuple(stride)\n dilation = to_2tuple(dilation)\n\n if isinstance(padding, str):\n self.adaptive_padding = AdaptivePadding(\n kernel_size=kernel_size,\n stride=stride,\n dilation=dilation,\n padding=padding)\n # disable the padding of conv\n padding = 0\n else:\n self.adaptive_padding = None\n padding = to_2tuple(padding)\n\n self.projection = build_conv_layer(\n dict(type=conv_type),\n in_channels=in_channels,\n out_channels=embed_dims,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n dilation=dilation,\n bias=bias)\n\n if norm_cfg is not None:\n self.norm = build_norm_layer(norm_cfg, embed_dims)[1]\n else:\n self.norm = None\n\n if input_size:\n input_size = to_2tuple(input_size)\n # `init_out_size` would be used outside to\n # calculate the num_patches\n # e.g. when `use_abs_pos_embed` outside\n self.init_input_size = input_size\n if self.adaptive_padding:\n pad_h, pad_w = self.adaptive_padding.get_pad_shape(input_size)\n input_h, input_w = input_size\n input_h = input_h + pad_h\n input_w = input_w + pad_w\n input_size = (input_h, input_w)\n\n # https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html\n h_out = (input_size[0] + 2 * padding[0] - dilation[0] *\n (kernel_size[0] - 1) - 1) // stride[0] + 1\n w_out = (input_size[1] + 2 * padding[1] - dilation[1] *\n (kernel_size[1] - 1) - 1) // stride[1] + 1\n self.init_out_size = (h_out, w_out)\n else:\n self.init_input_size = None\n self.init_out_size = None\n\n def forward(self, x):\n \"\"\"\n Args:\n x (Tensor): Has shape (B, C, H, W). In most case, C is 3.\n\n Returns:\n tuple: Contains merged results and its spatial shape.\n\n - x (Tensor): Has shape (B, out_h * out_w, embed_dims)\n - out_size (tuple[int]): Spatial shape of x, arrange as\n (out_h, out_w).\n \"\"\"\n\n if self.adaptive_padding:\n x = self.adaptive_padding(x)\n\n x = self.projection(x)\n out_size = (x.shape[2], x.shape[3])\n x = x.flatten(2).transpose(1, 2)\n if self.norm is not None:\n x = self.norm(x)\n return x, out_size\n\n\nclass PatchMerging(BaseModule):\n \"\"\"Merge patch feature map.\n\n This layer groups feature map by kernel_size, and applies norm and linear\n layers to the grouped feature map ((used in Swin Transformer)).\n Our implementation uses `nn.Unfold` to\n merge patches, which is about 25% faster than the original\n implementation. However, we need to modify pretrained\n models for compatibility.\n\n Args:\n in_channels (int): The num of input channels.\n to gets fully covered by filter and stride you specified.\n out_channels (int): The num of output channels.\n kernel_size (int | tuple, optional): the kernel size in the unfold\n layer. Defaults to 2.\n stride (int | tuple, optional): the stride of the sliding blocks in the\n unfold layer. Default: None. (Would be set as `kernel_size`)\n padding (int | tuple | string ): The padding length of\n embedding conv. When it is a string, it means the mode\n of adaptive padding, support \"same\" and \"corner\" now.\n Default: \"corner\".\n dilation (int | tuple, optional): dilation parameter in the unfold\n layer. Default: 1.\n bias (bool, optional): Whether to add bias in linear layer or not.\n Defaults: False.\n norm_cfg (dict, optional): Config dict for normalization layer.\n Default: dict(type='LN').\n init_cfg (dict, optional): The extra config for initialization.\n Default: None.\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size=2,\n stride=None,\n padding='corner',\n dilation=1,\n bias=False,\n norm_cfg=dict(type='LN'),\n init_cfg=None):\n super().__init__(init_cfg=init_cfg)\n self.in_channels = in_channels\n self.out_channels = out_channels\n if stride:\n stride = stride\n else:\n stride = kernel_size\n\n kernel_size = to_2tuple(kernel_size)\n stride = to_2tuple(stride)\n dilation = to_2tuple(dilation)\n\n if isinstance(padding, str):\n self.adaptive_padding = AdaptivePadding(\n kernel_size=kernel_size,\n stride=stride,\n dilation=dilation,\n padding=padding)\n # disable the padding of unfold\n padding = 0\n else:\n self.adaptive_padding = None\n\n padding = to_2tuple(padding)\n self.sampler = nn.Unfold(\n kernel_size=kernel_size,\n dilation=dilation,\n padding=padding,\n stride=stride)\n\n sample_dim = kernel_size[0] * kernel_size[1] * in_channels\n\n if norm_cfg is not None:\n self.norm = build_norm_layer(norm_cfg, sample_dim)[1]\n else:\n self.norm = None\n\n self.reduction = nn.Linear(sample_dim, out_channels, bias=bias)\n\n def forward(self, x, input_size):\n \"\"\"\n Args:\n x (Tensor): Has shape (B, H*W, C_in).\n input_size (tuple[int]): The spatial shape of x, arrange as (H, W).\n Default: None.\n\n Returns:\n tuple: Contains merged results and its spatial shape.\n\n - x (Tensor): Has shape (B, Merged_H * Merged_W, C_out)\n - out_size (tuple[int]): Spatial shape of x, arrange as\n (Merged_H, Merged_W).\n \"\"\"\n B, L, C = x.shape\n assert isinstance(input_size, Sequence), f'Expect ' \\\n f'input_size is ' \\\n f'`Sequence` ' \\\n f'but get {input_size}'\n\n H, W = input_size\n assert L == H * W, 'input feature has wrong size'\n\n x = x.view(B, H, W, C).permute([0, 3, 1, 2]) # B, C, H, W\n\n if self.adaptive_padding:\n x = self.adaptive_padding(x)\n H, W = x.shape[-2:]\n\n # Use nn.Unfold to merge patch. About 25% faster than original method,\n # but need to modify pretrained model for compatibility\n # if kernel_size=2 and stride=2, x should has shape (B, 4*C, H/2*W/2)\n x = self.sampler(x)\n\n out_h = (H + 2 * self.sampler.padding[0] - self.sampler.dilation[0] *\n (self.sampler.kernel_size[0] - 1) -\n 1) // self.sampler.stride[0] + 1\n out_w = (W + 2 * self.sampler.padding[1] - self.sampler.dilation[1] *\n (self.sampler.kernel_size[1] - 1) -\n 1) // self.sampler.stride[1] + 1\n\n output_size = (out_h, out_w)\n x = x.transpose(1, 2) # B, H/2*W/2, 4*C\n x = self.norm(x) if self.norm else x\n x = self.reduction(x)\n return x, output_size\n\n\[email protected]_module()\nclass MultiheadAttention(BaseModule):\n \"\"\"A wrapper for ``torch.nn.MultiheadAttention``.\n\n This module implements MultiheadAttention with identity connection,\n and positional encoding is also passed as input.\n\n Args:\n embed_dims (int): The embedding dimension.\n num_heads (int): Parallel attention heads.\n attn_drop (float): A Dropout layer on attn_output_weights.\n Default: 0.0.\n proj_drop (float): A Dropout layer after `nn.MultiheadAttention`.\n Default: 0.0.\n dropout_layer (obj:`ConfigDict`): The dropout_layer used\n when adding the shortcut.\n init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.\n Default: None.\n batch_first (bool): When it is True, Key, Query and Value are shape of\n (batch, n, embed_dim), otherwise (n, batch, embed_dim).\n Default to False.\n \"\"\"\n\n def __init__(self,\n embed_dims,\n num_heads,\n attn_drop=0.,\n proj_drop=0.,\n dropout_layer=dict(type='Dropout', drop_prob=0.),\n init_cfg=None,\n batch_first=False,\n **kwargs):\n super().__init__(init_cfg)\n if 'dropout' in kwargs:\n warnings.warn(\n 'The arguments `dropout` in MultiheadAttention '\n 'has been deprecated, now you can separately '\n 'set `attn_drop`(float), proj_drop(float), '\n 'and `dropout_layer`(dict) ', DeprecationWarning)\n attn_drop = kwargs['dropout']\n dropout_layer['drop_prob'] = kwargs.pop('dropout')\n\n self.embed_dims = embed_dims\n self.num_heads = num_heads\n self.batch_first = batch_first\n\n self.attn = nn.MultiheadAttention(embed_dims, num_heads, attn_drop,\n **kwargs)\n\n self.proj_drop = nn.Dropout(proj_drop)\n self.dropout_layer = build_dropout(\n dropout_layer) if dropout_layer else nn.Identity()\n\n @deprecated_api_warning({'residual': 'identity'},\n cls_name='MultiheadAttention')\n def forward(self,\n query,\n key=None,\n value=None,\n identity=None,\n query_pos=None,\n key_pos=None,\n attn_mask=None,\n key_padding_mask=None,\n **kwargs):\n \"\"\"Forward function for `MultiheadAttention`.\n\n **kwargs allow passing a more general data flow when combining\n with other operations in `transformerlayer`.\n\n Args:\n query (Tensor): The input query with shape [num_queries, bs,\n embed_dims] if self.batch_first is False, else\n [bs, num_queries embed_dims].\n key (Tensor): The key tensor with shape [num_keys, bs,\n embed_dims] if self.batch_first is False, else\n [bs, num_keys, embed_dims] .\n If None, the ``query`` will be used. Defaults to None.\n value (Tensor): The value tensor with same shape as `key`.\n Same in `nn.MultiheadAttention.forward`. Defaults to None.\n If None, the `key` will be used.\n identity (Tensor): This tensor, with the same shape as x,\n will be used for the identity link.\n If None, `x` will be used. Defaults to None.\n query_pos (Tensor): The positional encoding for query, with\n the same shape as `x`. If not None, it will\n be added to `x` before forward function. Defaults to None.\n key_pos (Tensor): The positional encoding for `key`, with the\n same shape as `key`. Defaults to None. If not None, it will\n be added to `key` before forward function. If None, and\n `query_pos` has the same shape as `key`, then `query_pos`\n will be used for `key_pos`. Defaults to None.\n attn_mask (Tensor): ByteTensor mask with shape [num_queries,\n num_keys]. Same in `nn.MultiheadAttention.forward`.\n Defaults to None.\n key_padding_mask (Tensor): ByteTensor with shape [bs, num_keys].\n Defaults to None.\n\n Returns:\n Tensor: forwarded results with shape\n [num_queries, bs, embed_dims]\n if self.batch_first is False, else\n [bs, num_queries embed_dims].\n \"\"\"\n\n if key is None:\n key = query\n if value is None:\n value = key\n if identity is None:\n identity = query\n if key_pos is None:\n if query_pos is not None:\n # use query_pos if key_pos is not available\n if query_pos.shape == key.shape:\n key_pos = query_pos\n else:\n warnings.warn(f'position encoding of key is'\n f'missing in {self.__class__.__name__}.')\n if query_pos is not None:\n query = query + query_pos\n if key_pos is not None:\n key = key + key_pos\n\n # Because the dataflow('key', 'query', 'value') of\n # ``torch.nn.MultiheadAttention`` is (num_query, batch,\n # embed_dims), We should adjust the shape of dataflow from\n # batch_first (batch, num_query, embed_dims) to num_query_first\n # (num_query ,batch, embed_dims), and recover ``attn_output``\n # from num_query_first to batch_first.\n if self.batch_first:\n query = query.transpose(0, 1)\n key = key.transpose(0, 1)\n value = value.transpose(0, 1)\n\n out = self.attn(\n query=query,\n key=key,\n value=value,\n attn_mask=attn_mask,\n key_padding_mask=key_padding_mask)[0]\n\n if self.batch_first:\n out = out.transpose(0, 1)\n\n return identity + self.dropout_layer(self.proj_drop(out))\n\n\n@FEEDFORWARD_NETWORK.register_module()\nclass FFN(BaseModule):\n \"\"\"Implements feed-forward networks (FFNs) with identity connection.\n\n Args:\n embed_dims (int): The feature dimension. Same as\n `MultiheadAttention`. Defaults: 256.\n feedforward_channels (int): The hidden dimension of FFNs.\n Defaults: 1024.\n num_fcs (int, optional): The number of fully-connected layers in\n FFNs. Default: 2.\n act_cfg (dict, optional): The activation config for FFNs.\n Default: dict(type='ReLU')\n ffn_drop (float, optional): Probability of an element to be\n zeroed in FFN. Default 0.0.\n add_identity (bool, optional): Whether to add the\n identity connection. Default: `True`.\n dropout_layer (obj:`ConfigDict`): The dropout_layer used\n when adding the shortcut.\n init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.\n Default: None.\n \"\"\"\n\n @deprecated_api_warning(\n {\n 'dropout': 'ffn_drop',\n 'add_residual': 'add_identity'\n },\n cls_name='FFN')\n def __init__(self,\n embed_dims=256,\n feedforward_channels=1024,\n num_fcs=2,\n act_cfg=dict(type='ReLU', inplace=True),\n ffn_drop=0.,\n dropout_layer=None,\n add_identity=True,\n init_cfg=None,\n **kwargs):\n super().__init__(init_cfg)\n assert num_fcs >= 2, 'num_fcs should be no less ' \\\n f'than 2. got {num_fcs}.'\n self.embed_dims = embed_dims\n self.feedforward_channels = feedforward_channels\n self.num_fcs = num_fcs\n self.act_cfg = act_cfg\n self.activate = build_activation_layer(act_cfg)\n\n layers = []\n in_channels = embed_dims\n for _ in range(num_fcs - 1):\n layers.append(\n Sequential(\n Linear(in_channels, feedforward_channels), self.activate,\n nn.Dropout(ffn_drop)))\n in_channels = feedforward_channels\n layers.append(Linear(feedforward_channels, embed_dims))\n layers.append(nn.Dropout(ffn_drop))\n self.layers = Sequential(*layers)\n self.dropout_layer = build_dropout(\n dropout_layer) if dropout_layer else torch.nn.Identity()\n self.add_identity = add_identity\n\n @deprecated_api_warning({'residual': 'identity'}, cls_name='FFN')\n def forward(self, x, identity=None):\n \"\"\"Forward function for `FFN`.\n\n The function would add x to the output tensor if residue is None.\n \"\"\"\n out = self.layers(x)\n if not self.add_identity:\n return self.dropout_layer(out)\n if identity is None:\n identity = x\n return identity + self.dropout_layer(out)\n\n\n@TRANSFORMER_LAYER.register_module()\nclass BaseTransformerLayer(BaseModule):\n \"\"\"Base `TransformerLayer` for vision transformer.\n\n It can be built from `mmcv.ConfigDict` and support more flexible\n customization, for example, using any number of `FFN or LN ` and\n use different kinds of `attention` by specifying a list of `ConfigDict`\n named `attn_cfgs`. It is worth mentioning that it supports `prenorm`\n when you specifying `norm` as the first element of `operation_order`.\n More details about the `prenorm`: `On Layer Normalization in the\n Transformer Architecture <https://arxiv.org/abs/2002.04745>`_ .\n\n Args:\n attn_cfgs (list[`mmcv.ConfigDict`] | obj:`mmcv.ConfigDict` | None )):\n Configs for `self_attention` or `cross_attention` modules,\n The order of the configs in the list should be consistent with\n corresponding attentions in operation_order.\n If it is a dict, all of the attention modules in operation_order\n will be built with this config. Default: None.\n ffn_cfgs (list[`mmcv.ConfigDict`] | obj:`mmcv.ConfigDict` | None )):\n Configs for FFN, The order of the configs in the list should be\n consistent with corresponding ffn in operation_order.\n If it is a dict, all of the attention modules in operation_order\n will be built with this config.\n operation_order (tuple[str]): The execution order of operation\n in transformer. Such as ('self_attn', 'norm', 'ffn', 'norm').\n Support `prenorm` when you specifying first element as `norm`.\n Default:None.\n norm_cfg (dict): Config dict for normalization layer.\n Default: dict(type='LN').\n init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.\n Default: None.\n batch_first (bool): Key, Query and Value are shape\n of (batch, n, embed_dim)\n or (n, batch, embed_dim). Default to False.\n \"\"\"\n\n def __init__(self,\n attn_cfgs=None,\n ffn_cfgs=dict(\n type='FFN',\n embed_dims=256,\n feedforward_channels=1024,\n num_fcs=2,\n ffn_drop=0.,\n act_cfg=dict(type='ReLU', inplace=True),\n ),\n operation_order=None,\n norm_cfg=dict(type='LN'),\n init_cfg=None,\n batch_first=False,\n **kwargs):\n\n deprecated_args = dict(\n feedforward_channels='feedforward_channels',\n ffn_dropout='ffn_drop',\n ffn_num_fcs='num_fcs')\n for ori_name, new_name in deprecated_args.items():\n if ori_name in kwargs:\n warnings.warn(\n f'The arguments `{ori_name}` in BaseTransformerLayer '\n f'has been deprecated, now you should set `{new_name}` '\n f'and other FFN related arguments '\n f'to a dict named `ffn_cfgs`. ', DeprecationWarning)\n ffn_cfgs[new_name] = kwargs[ori_name]\n\n super().__init__(init_cfg)\n\n self.batch_first = batch_first\n\n assert set(operation_order) & {\n 'self_attn', 'norm', 'ffn', 'cross_attn'} == \\\n set(operation_order), f'The operation_order of' \\\n f' {self.__class__.__name__} should ' \\\n f'contains all four operation type ' \\\n f\"{['self_attn', 'norm', 'ffn', 'cross_attn']}\"\n\n num_attn = operation_order.count('self_attn') + operation_order.count(\n 'cross_attn')\n if isinstance(attn_cfgs, dict):\n attn_cfgs = [copy.deepcopy(attn_cfgs) for _ in range(num_attn)]\n else:\n assert num_attn == len(attn_cfgs), f'The length ' \\\n f'of attn_cfg {num_attn} is ' \\\n f'not consistent with the number of attention' \\\n f'in operation_order {operation_order}.'\n\n self.num_attn = num_attn\n self.operation_order = operation_order\n self.norm_cfg = norm_cfg\n self.pre_norm = operation_order[0] == 'norm'\n self.attentions = ModuleList()\n\n index = 0\n for operation_name in operation_order:\n if operation_name in ['self_attn', 'cross_attn']:\n if 'batch_first' in attn_cfgs[index]:\n assert self.batch_first == attn_cfgs[index]['batch_first']\n else:\n attn_cfgs[index]['batch_first'] = self.batch_first\n attention = build_attention(attn_cfgs[index])\n # Some custom attentions used as `self_attn`\n # or `cross_attn` can have different behavior.\n attention.operation_name = operation_name\n self.attentions.append(attention)\n index += 1\n\n self.embed_dims = self.attentions[0].embed_dims\n\n self.ffns = ModuleList()\n num_ffns = operation_order.count('ffn')\n if isinstance(ffn_cfgs, dict):\n ffn_cfgs = ConfigDict(ffn_cfgs)\n if isinstance(ffn_cfgs, dict):\n ffn_cfgs = [copy.deepcopy(ffn_cfgs) for _ in range(num_ffns)]\n assert len(ffn_cfgs) == num_ffns\n for ffn_index in range(num_ffns):\n if 'embed_dims' not in ffn_cfgs[ffn_index]:\n ffn_cfgs[ffn_index]['embed_dims'] = self.embed_dims\n else:\n assert ffn_cfgs[ffn_index]['embed_dims'] == self.embed_dims\n self.ffns.append(\n build_feedforward_network(ffn_cfgs[ffn_index],\n dict(type='FFN')))\n\n self.norms = ModuleList()\n num_norms = operation_order.count('norm')\n for _ in range(num_norms):\n self.norms.append(build_norm_layer(norm_cfg, self.embed_dims)[1])\n\n def forward(self,\n query,\n key=None,\n value=None,\n query_pos=None,\n key_pos=None,\n attn_masks=None,\n query_key_padding_mask=None,\n key_padding_mask=None,\n **kwargs):\n \"\"\"Forward function for `TransformerDecoderLayer`.\n\n **kwargs contains some specific arguments of attentions.\n\n Args:\n query (Tensor): The input query with shape\n [num_queries, bs, embed_dims] if\n self.batch_first is False, else\n [bs, num_queries embed_dims].\n key (Tensor): The key tensor with shape [num_keys, bs,\n embed_dims] if self.batch_first is False, else\n [bs, num_keys, embed_dims] .\n value (Tensor): The value tensor with same shape as `key`.\n query_pos (Tensor): The positional encoding for `query`.\n Default: None.\n key_pos (Tensor): The positional encoding for `key`.\n Default: None.\n attn_masks (List[Tensor] | None): 2D Tensor used in\n calculation of corresponding attention. The length of\n it should equal to the number of `attention` in\n `operation_order`. Default: None.\n query_key_padding_mask (Tensor): ByteTensor for `query`, with\n shape [bs, num_queries]. Only used in `self_attn` layer.\n Defaults to None.\n key_padding_mask (Tensor): ByteTensor for `query`, with\n shape [bs, num_keys]. Default: None.\n\n Returns:\n Tensor: forwarded results with shape [num_queries, bs, embed_dims].\n \"\"\"\n\n norm_index = 0\n attn_index = 0\n ffn_index = 0\n identity = query\n if attn_masks is None:\n attn_masks = [None for _ in range(self.num_attn)]\n elif isinstance(attn_masks, torch.Tensor):\n attn_masks = [\n copy.deepcopy(attn_masks) for _ in range(self.num_attn)\n ]\n warnings.warn(f'Use same attn_mask in all attentions in '\n f'{self.__class__.__name__} ')\n else:\n assert len(attn_masks) == self.num_attn, f'The length of ' \\\n f'attn_masks {len(attn_masks)} must be equal ' \\\n f'to the number of attention in ' \\\n f'operation_order {self.num_attn}'\n\n for layer in self.operation_order:\n if layer == 'self_attn':\n temp_key = temp_value = query\n query = self.attentions[attn_index](\n query,\n temp_key,\n temp_value,\n identity if self.pre_norm else None,\n query_pos=query_pos,\n key_pos=query_pos,\n attn_mask=attn_masks[attn_index],\n key_padding_mask=query_key_padding_mask,\n **kwargs)\n attn_index += 1\n identity = query\n\n elif layer == 'norm':\n query = self.norms[norm_index](query)\n norm_index += 1\n\n elif layer == 'cross_attn':\n query = self.attentions[attn_index](\n query,\n key,\n value,\n identity if self.pre_norm else None,\n query_pos=query_pos,\n key_pos=key_pos,\n attn_mask=attn_masks[attn_index],\n key_padding_mask=key_padding_mask,\n **kwargs)\n attn_index += 1\n identity = query\n\n elif layer == 'ffn':\n query = self.ffns[ffn_index](\n query, identity if self.pre_norm else None)\n ffn_index += 1\n\n return query\n\n\n@TRANSFORMER_LAYER_SEQUENCE.register_module()\nclass TransformerLayerSequence(BaseModule):\n \"\"\"Base class for TransformerEncoder and TransformerDecoder in vision\n transformer.\n\n As base-class of Encoder and Decoder in vision transformer.\n Support customization such as specifying different kind\n of `transformer_layer` in `transformer_coder`.\n\n Args:\n transformerlayer (list[obj:`mmcv.ConfigDict`] |\n obj:`mmcv.ConfigDict`): Config of transformerlayer\n in TransformerCoder. If it is obj:`mmcv.ConfigDict`,\n it would be repeated `num_layer` times to a\n list[`mmcv.ConfigDict`]. Default: None.\n num_layers (int): The number of `TransformerLayer`. Default: None.\n init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.\n Default: None.\n \"\"\"\n\n def __init__(self, transformerlayers=None, num_layers=None, init_cfg=None):\n super().__init__(init_cfg)\n if isinstance(transformerlayers, dict):\n transformerlayers = [\n copy.deepcopy(transformerlayers) for _ in range(num_layers)\n ]\n else:\n assert isinstance(transformerlayers, list) and \\\n len(transformerlayers) == num_layers\n self.num_layers = num_layers\n self.layers = ModuleList()\n for i in range(num_layers):\n self.layers.append(build_transformer_layer(transformerlayers[i]))\n self.embed_dims = self.layers[0].embed_dims\n self.pre_norm = self.layers[0].pre_norm\n\n def forward(self,\n query,\n key,\n value,\n query_pos=None,\n key_pos=None,\n attn_masks=None,\n query_key_padding_mask=None,\n key_padding_mask=None,\n **kwargs):\n \"\"\"Forward function for `TransformerCoder`.\n\n Args:\n query (Tensor): Input query with shape\n `(num_queries, bs, embed_dims)`.\n key (Tensor): The key tensor with shape\n `(num_keys, bs, embed_dims)`.\n value (Tensor): The value tensor with shape\n `(num_keys, bs, embed_dims)`.\n query_pos (Tensor): The positional encoding for `query`.\n Default: None.\n key_pos (Tensor): The positional encoding for `key`.\n Default: None.\n attn_masks (List[Tensor], optional): Each element is 2D Tensor\n which is used in calculation of corresponding attention in\n operation_order. Default: None.\n query_key_padding_mask (Tensor): ByteTensor for `query`, with\n shape [bs, num_queries]. Only used in self-attention\n Default: None.\n key_padding_mask (Tensor): ByteTensor for `query`, with\n shape [bs, num_keys]. Default: None.\n\n Returns:\n Tensor: results with shape [num_queries, bs, embed_dims].\n \"\"\"\n for layer in self.layers:\n query = layer(\n query,\n key,\n value,\n query_pos=query_pos,\n key_pos=key_pos,\n attn_masks=attn_masks,\n query_key_padding_mask=query_key_padding_mask,\n key_padding_mask=key_padding_mask,\n **kwargs)\n return query\n", "# Copyright (c) OpenMMLab. All rights reserved.\nimport inspect\n\nimport numpy as np\nimport popart\nimport poptorch\nimport torch\nimport torch.nn as nn\n\nfrom mmcv.utils import Registry\n\n\ndef _options_assigner(cfg, options_node):\n # set popart.options by config\n # cfg: dict, python data type\n # options_node: python module or function\n if isinstance(cfg, dict):\n for key in cfg:\n _options_assigner(cfg[key], getattr(options_node, key))\n elif isinstance(cfg, (int, float, str, list)):\n if callable(options_node):\n options_node(cfg)\n else:\n error_msg = f'options_node type {type(options_node)} not supported'\n raise NotImplementedError(error_msg)\n else:\n error_msg = f'cfg type {type(cfg)} not supported'\n raise NotImplementedError(error_msg)\n\n\ndef cfg2options(cfg):\n \"\"\"Parse dictionary to ipu options.\n\n Args:\n cfg (dict): A dictionary of ipu settings.\n\n Returns:\n dict[str, poptorch.Options]: Training options and inference options\n of IPU.\n \"\"\"\n # set ipu options for inference and training by config\n train_cfg = cfg.pop('train_cfg', {})\n eval_cfg = cfg.pop('eval_cfg', {})\n eval_cfg['replicationFactor'] = 1 # eval mode only use one replica\n eval_cfg['executionStrategy'] = 'ShardedExecution'\n # overwrite default ipu cfg with specified train cfgs\n training_ipu_cfg = {**cfg, **train_cfg}\n # overwrite default ipu cfg with specified eval cfgs\n inference_ipu_cfg = {**cfg, **eval_cfg}\n\n ipu_options = {\n 'training': _cast_to_options(training_ipu_cfg),\n 'inference': _cast_to_options(inference_ipu_cfg)\n }\n\n # TODO configure these codes\n ipu_options['training']._Popart.set('disableGradAccumulationTensorStreams',\n True)\n ipu_options['training']._Popart.set(\n 'accumulateOuterFragmentSettings.schedule',\n int(popart.AccumulateOuterFragmentSchedule.OverlapMemoryOptimized))\n ipu_options['training'].Precision.enableStochasticRounding(True)\n\n return ipu_options\n\n\ndef _cast_to_options(cfg):\n # If it cannot be directly assigned, use if statement to parse it,\n # and if it can be directly assigned, use _options_assigner to assign\n options = poptorch.Options()\n\n if 'availableMemoryProportion' in cfg:\n available_memory_proportion = cfg.pop('availableMemoryProportion')\n mem_props = {}\n for i, mem_prop in enumerate(available_memory_proportion):\n mem_props[f'IPU{i}'] = mem_prop\n options.setAvailableMemoryProportion(mem_props)\n\n if 'executionStrategy' in cfg:\n execution_strategy = cfg.pop('executionStrategy')\n if execution_strategy == 'SameAsIpu':\n options.setExecutionStrategy(\n poptorch.PipelinedExecution(\n getattr(poptorch.AutoStage, execution_strategy)))\n elif execution_strategy == 'ShardedExecution':\n options.setExecutionStrategy(poptorch.ShardedExecution())\n else:\n raise NotImplementedError(\n 'executionStrategy should be \"SameAsIpu\" or \"ShardedExecution\"'\n f', but got {execution_strategy}')\n\n if 'partialsType' in cfg:\n partials_type = cfg.pop('partialsType')\n options.Precision.setPartialsType(getattr(\n torch, partials_type)) # half or float\n\n _options_assigner(cfg, options)\n return options\n\n\ndef model_sharding(model, split_edges):\n \"\"\"split models in-place into multi-IPUs.\n\n Args:\n model (nn.Module): The target model to be split.\n split_edges (list of dict): Model layer names or layer numbers\n of split edge. Each item of ``split_edges`` is a dictionary,\n which may contain the following key-pairs:\n\n - layer_to_call: PyTorch module to assign to the block\n - user_id (optional): A user defined identifier for the block.\n - ipu_id: The id of the IPU to run on.\n\n Examples:\n >>> split_edges = [\n ... dict(layer_to_call='model.conv1', ipu_id=0),\n ... dict(layer_to_call='model.conv3', ipu_id=1)]\n >>> sharding_model = model_sharding(torch_model, split_edges)\n\n Returns:\n nn.Module: Split model.\n \"\"\"\n if len(split_edges) == 0:\n return model\n assert isinstance(split_edges, list)\n spilt_edges_dict = {edge['layer_to_call']: edge for edge in split_edges}\n\n for idx, (name, module) in enumerate(model.named_modules()):\n if idx in spilt_edges_dict and name in spilt_edges_dict:\n raise ValueError(\n 'The same layer is referenced twice while doing model'\n f' partition: idx is {idx} and name is {name}')\n\n edge = spilt_edges_dict.pop(name, None)\n edge = spilt_edges_dict.pop(idx, edge)\n if edge is not None:\n poptorch.BeginBlock(module, edge.get('user_id', name),\n edge['ipu_id'])\n\n # ensure all split_edges are used\n if len(spilt_edges_dict) > 0:\n split_edge_names = list(spilt_edges_dict.keys())\n raise RuntimeError(\n f'split_edges: {split_edge_names} are not contained in the model')\n return model\n\n\ndef recomputation_checkpoint(model: nn.Module, module_names: list):\n \"\"\"Annotates the output of a module to be checkpointed instead of\n recomputed.\n\n If recomputation mode is enabled, ipu will release the activations of\n the middle layers to save memory. During the backward of gradient,\n the activation of the middle layer will be recalculated again.\n This function is used to declare the activations of some intermediate\n layers that need to be saved in order to skip the recomputation of\n some layers.\n\n Args:\n model (nn.Module): The target model to apply recomputation\n checkpoint.\n module_names (list): Layer names of module.\n \"\"\"\n\n def recompute_outputs(module, inputs, outputs):\n if isinstance(outputs, tuple):\n return tuple(poptorch.recomputationCheckpoint(y) for y in outputs)\n else:\n return poptorch.recomputationCheckpoint(outputs)\n\n for name, module in model.named_modules():\n if name in module_names:\n module.register_forward_hook(recompute_outputs)\n module_names.remove(name)\n\n # check all module_names are used\n assert len(module_names) == 0,\\\n f'recomputed nodes: {module_names} are not contained in the model'\n\n\ndef compare_ndarray(featA, featB, rtol=1e-3, atol=1e-5):\n \"\"\"Align data between two activations or weights.\"\"\"\n try:\n np.testing.assert_allclose(featA, featB, rtol=rtol, atol=atol)\n except AssertionError as e:\n print(e)\n\n\ndef build_from_cfg_with_wrapper(cfg,\n registry,\n wrapper_func=None,\n default_args=None):\n \"\"\"Build a module from config dict and wrap module with \"wrapper_func\".\n\n Args:\n cfg (dict): Config dict. It should at least contain the key \"type\".\n registry (:obj:`Registry`): The registry to search the type from.\n default_args (dict, optional): Default initialization arguments.\n wrapper_func (function): Used to wrap class\n\n Returns:\n object: The constructed object.\n \"\"\"\n if not isinstance(cfg, dict):\n raise TypeError(f'cfg must be a dict, but got {type(cfg)}')\n if 'type' not in cfg:\n if default_args is None or 'type' not in default_args:\n raise KeyError(\n '`cfg` or `default_args` must contain the key \"type\", '\n f'but got {cfg}\\n{default_args}')\n if not isinstance(registry, Registry):\n raise TypeError('registry must be an mmcv.Registry object, '\n f'but got {type(registry)}')\n if not (isinstance(default_args, dict) or default_args is None):\n raise TypeError('default_args must be a dict or None, '\n f'but got {type(default_args)}')\n\n args = cfg.copy()\n\n if default_args is not None:\n for name, value in default_args.items():\n args.setdefault(name, value)\n\n obj_type = args.pop('type')\n if isinstance(obj_type, str):\n obj_cls = registry.get(obj_type)\n if obj_cls is None:\n raise KeyError(\n f'{obj_type} is not in the {registry.name} registry')\n elif inspect.isclass(obj_type):\n obj_cls = obj_type\n else:\n raise TypeError(\n f'type must be a str or valid type, but got {type(obj_type)}')\n\n if wrapper_func is None:\n wrapped_obj_cls = obj_cls\n else:\n wrapped_obj_cls = wrapper_func(obj_cls)\n try:\n return wrapped_obj_cls(**args)\n except Exception as e:\n # Normal TypeError does not print class name.\n raise type(e)(f'{wrapped_obj_cls.__name__}: {e}')\n", "# Copyright (c) OpenMMLab. All rights reserved.\nfrom typing import Optional, Union\n\nimport numpy as np\n\nfrom mmcv.image import rgb2bgr\nfrom mmcv.video import flowread\nfrom .image import imshow\n\n\ndef flowshow(flow: Union[np.ndarray, str],\n win_name: str = '',\n wait_time: int = 0) -> None:\n \"\"\"Show optical flow.\n\n Args:\n flow (ndarray or str): The optical flow to be displayed.\n win_name (str): The window name.\n wait_time (int): Value of waitKey param.\n \"\"\"\n flow = flowread(flow)\n flow_img = flow2rgb(flow)\n imshow(rgb2bgr(flow_img), win_name, wait_time)\n\n\ndef flow2rgb(flow: np.ndarray,\n color_wheel: Optional[np.ndarray] = None,\n unknown_thr: float = 1e6) -> np.ndarray:\n \"\"\"Convert flow map to RGB image.\n\n Args:\n flow (ndarray): Array of optical flow.\n color_wheel (ndarray or None): Color wheel used to map flow field to\n RGB colorspace. Default color wheel will be used if not specified.\n unknown_thr (float): Values above this threshold will be marked as\n unknown and thus ignored.\n\n Returns:\n ndarray: RGB image that can be visualized.\n \"\"\"\n assert flow.ndim == 3 and flow.shape[-1] == 2\n if color_wheel is None:\n color_wheel = make_color_wheel()\n assert color_wheel.ndim == 2 and color_wheel.shape[1] == 3\n num_bins = color_wheel.shape[0]\n\n dx = flow[:, :, 0].copy()\n dy = flow[:, :, 1].copy()\n\n ignore_inds = (\n np.isnan(dx) | np.isnan(dy) | (np.abs(dx) > unknown_thr) |\n (np.abs(dy) > unknown_thr))\n dx[ignore_inds] = 0\n dy[ignore_inds] = 0\n\n rad = np.sqrt(dx**2 + dy**2)\n if np.any(rad > np.finfo(float).eps):\n max_rad = np.max(rad)\n dx /= max_rad\n dy /= max_rad\n\n rad = np.sqrt(dx**2 + dy**2)\n angle = np.arctan2(-dy, -dx) / np.pi\n\n bin_real = (angle + 1) / 2 * (num_bins - 1)\n bin_left = np.floor(bin_real).astype(int)\n bin_right = (bin_left + 1) % num_bins\n w = (bin_real - bin_left.astype(np.float32))[..., None]\n flow_img = (1 -\n w) * color_wheel[bin_left, :] + w * color_wheel[bin_right, :]\n small_ind = rad <= 1\n flow_img[small_ind] = 1 - rad[small_ind, None] * (1 - flow_img[small_ind])\n flow_img[np.logical_not(small_ind)] *= 0.75\n\n flow_img[ignore_inds, :] = 0\n\n return flow_img\n\n\ndef make_color_wheel(bins: Optional[Union[list, tuple]] = None) -> np.ndarray:\n \"\"\"Build a color wheel.\n\n Args:\n bins(list or tuple, optional): Specify the number of bins for each\n color range, corresponding to six ranges: red -> yellow,\n yellow -> green, green -> cyan, cyan -> blue, blue -> magenta,\n magenta -> red. [15, 6, 4, 11, 13, 6] is used for default\n (see Middlebury).\n\n Returns:\n ndarray: Color wheel of shape (total_bins, 3).\n \"\"\"\n if bins is None:\n bins = [15, 6, 4, 11, 13, 6]\n assert len(bins) == 6\n\n RY, YG, GC, CB, BM, MR = tuple(bins)\n\n ry = [1, np.arange(RY) / RY, 0]\n yg = [1 - np.arange(YG) / YG, 1, 0]\n gc = [0, 1, np.arange(GC) / GC]\n cb = [0, 1 - np.arange(CB) / CB, 1]\n bm = [np.arange(BM) / BM, 0, 1]\n mr = [1, 0, 1 - np.arange(MR) / MR]\n\n num_bins = RY + YG + GC + CB + BM + MR\n\n color_wheel = np.zeros((3, num_bins), dtype=np.float32)\n\n col = 0\n for i, color in enumerate([ry, yg, gc, cb, bm, mr]):\n for j in range(3):\n color_wheel[j, col:col + bins[i]] = color[j]\n col += bins[i]\n\n return color_wheel.T\n", "# Copyright (c) OpenMMLab. All rights reserved.\nfrom typing import Callable, Union\n\nimport cv2\nimport numpy as np\n\n\ndef imconvert(img: np.ndarray, src: str, dst: str) -> np.ndarray:\n \"\"\"Convert an image from the src colorspace to dst colorspace.\n\n Args:\n img (ndarray): The input image.\n src (str): The source colorspace, e.g., 'rgb', 'hsv'.\n dst (str): The destination colorspace, e.g., 'rgb', 'hsv'.\n\n Returns:\n ndarray: The converted image.\n \"\"\"\n code = getattr(cv2, f'COLOR_{src.upper()}2{dst.upper()}')\n out_img = cv2.cvtColor(img, code)\n return out_img\n\n\ndef bgr2gray(img: np.ndarray, keepdim: bool = False) -> np.ndarray:\n \"\"\"Convert a BGR image to grayscale image.\n\n Args:\n img (ndarray): The input image.\n keepdim (bool): If False (by default), then return the grayscale image\n with 2 dims, otherwise 3 dims.\n\n Returns:\n ndarray: The converted grayscale image.\n \"\"\"\n out_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n if keepdim:\n out_img = out_img[..., None]\n return out_img\n\n\ndef rgb2gray(img: np.ndarray, keepdim: bool = False) -> np.ndarray:\n \"\"\"Convert a RGB image to grayscale image.\n\n Args:\n img (ndarray): The input image.\n keepdim (bool): If False (by default), then return the grayscale image\n with 2 dims, otherwise 3 dims.\n\n Returns:\n ndarray: The converted grayscale image.\n \"\"\"\n out_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n if keepdim:\n out_img = out_img[..., None]\n return out_img\n\n\ndef gray2bgr(img: np.ndarray) -> np.ndarray:\n \"\"\"Convert a grayscale image to BGR image.\n\n Args:\n img (ndarray): The input image.\n\n Returns:\n ndarray: The converted BGR image.\n \"\"\"\n img = img[..., None] if img.ndim == 2 else img\n out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n return out_img\n\n\ndef gray2rgb(img: np.ndarray) -> np.ndarray:\n \"\"\"Convert a grayscale image to RGB image.\n\n Args:\n img (ndarray): The input image.\n\n Returns:\n ndarray: The converted RGB image.\n \"\"\"\n img = img[..., None] if img.ndim == 2 else img\n out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n return out_img\n\n\ndef _convert_input_type_range(img: np.ndarray) -> np.ndarray:\n \"\"\"Convert the type and range of the input image.\n\n It converts the input image to np.float32 type and range of [0, 1].\n It is mainly used for pre-processing the input image in colorspace\n conversion functions such as rgb2ycbcr and ycbcr2rgb.\n\n Args:\n img (ndarray): The input image. It accepts:\n 1. np.uint8 type with range [0, 255];\n 2. np.float32 type with range [0, 1].\n\n Returns:\n (ndarray): The converted image with type of np.float32 and range of\n [0, 1].\n \"\"\"\n img_type = img.dtype\n img = img.astype(np.float32)\n if img_type == np.float32:\n pass\n elif img_type == np.uint8:\n img /= 255.\n else:\n raise TypeError('The img type should be np.float32 or np.uint8, '\n f'but got {img_type}')\n return img\n\n\ndef _convert_output_type_range(\n img: np.ndarray, dst_type: Union[np.uint8, np.float32]) -> np.ndarray:\n \"\"\"Convert the type and range of the image according to dst_type.\n\n It converts the image to desired type and range. If `dst_type` is np.uint8,\n images will be converted to np.uint8 type with range [0, 255]. If\n `dst_type` is np.float32, it converts the image to np.float32 type with\n range [0, 1].\n It is mainly used for post-processing images in colorspace conversion\n functions such as rgb2ycbcr and ycbcr2rgb.\n\n Args:\n img (ndarray): The image to be converted with np.float32 type and\n range [0, 255].\n dst_type (np.uint8 | np.float32): If dst_type is np.uint8, it\n converts the image to np.uint8 type with range [0, 255]. If\n dst_type is np.float32, it converts the image to np.float32 type\n with range [0, 1].\n\n Returns:\n (ndarray): The converted image with desired type and range.\n \"\"\"\n if dst_type not in (np.uint8, np.float32):\n raise TypeError('The dst_type should be np.float32 or np.uint8, '\n f'but got {dst_type}')\n if dst_type == np.uint8:\n img = img.round()\n else:\n img /= 255.\n return img.astype(dst_type)\n\n\ndef rgb2ycbcr(img: np.ndarray, y_only: bool = False) -> np.ndarray:\n \"\"\"Convert a RGB image to YCbCr image.\n\n This function produces the same results as Matlab's `rgb2ycbcr` function.\n It implements the ITU-R BT.601 conversion for standard-definition\n television. See more details in\n https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.\n\n It differs from a similar function in cv2.cvtColor: `RGB <-> YCrCb`.\n In OpenCV, it implements a JPEG conversion. See more details in\n https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.\n\n Args:\n img (ndarray): The input image. It accepts:\n 1. np.uint8 type with range [0, 255];\n 2. np.float32 type with range [0, 1].\n y_only (bool): Whether to only return Y channel. Default: False.\n\n Returns:\n ndarray: The converted YCbCr image. The output image has the same type\n and range as input image.\n \"\"\"\n img_type = img.dtype\n img = _convert_input_type_range(img)\n if y_only:\n out_img = np.dot(img, [65.481, 128.553, 24.966]) + 16.0\n else:\n out_img = np.matmul(\n img, [[65.481, -37.797, 112.0], [128.553, -74.203, -93.786],\n [24.966, 112.0, -18.214]]) + [16, 128, 128]\n out_img = _convert_output_type_range(out_img, img_type)\n return out_img\n\n\ndef bgr2ycbcr(img: np.ndarray, y_only: bool = False) -> np.ndarray:\n \"\"\"Convert a BGR image to YCbCr image.\n\n The bgr version of rgb2ycbcr.\n It implements the ITU-R BT.601 conversion for standard-definition\n television. See more details in\n https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.\n\n It differs from a similar function in cv2.cvtColor: `BGR <-> YCrCb`.\n In OpenCV, it implements a JPEG conversion. See more details in\n https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.\n\n Args:\n img (ndarray): The input image. It accepts:\n 1. np.uint8 type with range [0, 255];\n 2. np.float32 type with range [0, 1].\n y_only (bool): Whether to only return Y channel. Default: False.\n\n Returns:\n ndarray: The converted YCbCr image. The output image has the same type\n and range as input image.\n \"\"\"\n img_type = img.dtype\n img = _convert_input_type_range(img)\n if y_only:\n out_img = np.dot(img, [24.966, 128.553, 65.481]) + 16.0\n else:\n out_img = np.matmul(\n img, [[24.966, 112.0, -18.214], [128.553, -74.203, -93.786],\n [65.481, -37.797, 112.0]]) + [16, 128, 128]\n out_img = _convert_output_type_range(out_img, img_type)\n return out_img\n\n\ndef ycbcr2rgb(img: np.ndarray) -> np.ndarray:\n \"\"\"Convert a YCbCr image to RGB image.\n\n This function produces the same results as Matlab's ycbcr2rgb function.\n It implements the ITU-R BT.601 conversion for standard-definition\n television. See more details in\n https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.\n\n It differs from a similar function in cv2.cvtColor: `YCrCb <-> RGB`.\n In OpenCV, it implements a JPEG conversion. See more details in\n https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.\n\n Args:\n img (ndarray): The input image. It accepts:\n 1. np.uint8 type with range [0, 255];\n 2. np.float32 type with range [0, 1].\n\n Returns:\n ndarray: The converted RGB image. The output image has the same type\n and range as input image.\n \"\"\"\n img_type = img.dtype\n img = _convert_input_type_range(img) * 255\n out_img = np.matmul(img, [[0.00456621, 0.00456621, 0.00456621],\n [0, -0.00153632, 0.00791071],\n [0.00625893, -0.00318811, 0]]) * 255.0 + [\n -222.921, 135.576, -276.836\n ]\n out_img = _convert_output_type_range(out_img, img_type)\n return out_img\n\n\ndef ycbcr2bgr(img: np.ndarray) -> np.ndarray:\n \"\"\"Convert a YCbCr image to BGR image.\n\n The bgr version of ycbcr2rgb.\n It implements the ITU-R BT.601 conversion for standard-definition\n television. See more details in\n https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.\n\n It differs from a similar function in cv2.cvtColor: `YCrCb <-> BGR`.\n In OpenCV, it implements a JPEG conversion. See more details in\n https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.\n\n Args:\n img (ndarray): The input image. It accepts:\n 1. np.uint8 type with range [0, 255];\n 2. np.float32 type with range [0, 1].\n\n Returns:\n ndarray: The converted BGR image. The output image has the same type\n and range as input image.\n \"\"\"\n img_type = img.dtype\n img = _convert_input_type_range(img) * 255\n out_img = np.matmul(img, [[0.00456621, 0.00456621, 0.00456621],\n [0.00791071, -0.00153632, 0],\n [0, -0.00318811, 0.00625893]]) * 255.0 + [\n -276.836, 135.576, -222.921\n ]\n out_img = _convert_output_type_range(out_img, img_type)\n return out_img\n\n\ndef convert_color_factory(src: str, dst: str) -> Callable:\n\n code = getattr(cv2, f'COLOR_{src.upper()}2{dst.upper()}')\n\n def convert_color(img: np.ndarray) -> np.ndarray:\n out_img = cv2.cvtColor(img, code)\n return out_img\n\n convert_color.__doc__ = f\"\"\"Convert a {src.upper()} image to {dst.upper()}\n image.\n\n Args:\n img (ndarray or str): The input image.\n\n Returns:\n ndarray: The converted {dst.upper()} image.\n \"\"\"\n\n return convert_color\n\n\nbgr2rgb = convert_color_factory('bgr', 'rgb')\n\nrgb2bgr = convert_color_factory('rgb', 'bgr')\n\nbgr2hsv = convert_color_factory('bgr', 'hsv')\n\nhsv2bgr = convert_color_factory('hsv', 'bgr')\n\nbgr2hls = convert_color_factory('bgr', 'hls')\n\nhls2bgr = convert_color_factory('hls', 'bgr')\n" ]
[ [ "torch.nn.Sequential", "torch.cat", "torch.matmul", "torch.nn.MaxPool1d", "torch.nn.MaxPool2d", "torch.nn.MaxPool3d" ], [ "torch.onnx.export", "torch.testing.assert_allclose", "torch.Tensor", "torch.zeros", "torch.randn", "torch.from_numpy", "torch.equal", "torch.nn.InstanceNorm2d", "torch.no_grad", "torch.cuda.is_available", "torch.nn.functional.grid_sample", "torch.rand", "torch.allclose", "numpy.array", "torch.nn.functional.affine_grid" ], [ "torch.nn.Dropout", "torch.nn.MultiheadAttention", "torch.nn.Linear", "torch.nn.Unfold", "torch.nn.Identity", "torch.nn.functional.pad" ], [ "numpy.testing.assert_allclose" ], [ "numpy.logical_not", "numpy.sqrt", "numpy.abs", "numpy.isnan", "numpy.arange", "numpy.finfo", "numpy.arctan2", "numpy.max", "numpy.floor", "numpy.zeros" ], [ "numpy.dot", "numpy.matmul" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ullmannsven/pymor
[ "407103ec50efa45d933f0c973314a4d511cae792", "407103ec50efa45d933f0c973314a4d511cae792", "407103ec50efa45d933f0c973314a4d511cae792" ]
[ "src/pymordemos/minimal_cpp_demo/wrapper.py", "src/pymor/algorithms/rand_la.py", "src/pymor/reductors/neural_network.py" ]
[ "# This file is part of the pyMOR project (https://www.pymor.org).\n# Copyright pyMOR developers and contributors. All rights reserved.\n# License: BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause)\n\nfrom pymor.operators.interface import Operator\nfrom pymor.vectorarrays.list import CopyOnWriteVector, ListVectorSpace\n\nimport numpy as np\nimport math\nfrom model import Vector, DiffusionOperator\n\n\nclass WrappedVector(CopyOnWriteVector):\n\n def __init__(self, vector):\n assert isinstance(vector, Vector)\n self._impl = vector\n\n @classmethod\n def from_instance(cls, instance):\n return cls(instance._impl)\n\n def to_numpy(self, ensure_copy=False):\n result = np.frombuffer(self._impl, dtype=np.float64)\n if ensure_copy:\n result = result.copy()\n return result\n\n def _copy_data(self):\n self._impl = Vector(self._impl)\n\n def _scal(self, alpha):\n self._impl.scal(alpha)\n\n def _axpy(self, alpha, x):\n self._impl.axpy(alpha, x._impl)\n\n def inner(self, other):\n return self._impl.inner(other._impl)\n\n def norm(self):\n return math.sqrt(self.inner(self))\n\n def norm2(self):\n return self.inner(self)\n\n def sup_norm(self):\n raise NotImplementedError\n\n def dofs(self, dof_indices):\n raise NotImplementedError\n\n def amax(self):\n raise NotImplementedError\n\n\nclass WrappedVectorSpace(ListVectorSpace):\n\n def __init__(self, dim):\n self.dim = dim\n\n def zero_vector(self):\n return WrappedVector(Vector(self.dim, 0))\n\n def make_vector(self, obj):\n return WrappedVector(obj)\n\n def __eq__(self, other):\n return type(other) is WrappedVectorSpace and self.dim == other.dim\n\n\nclass WrappedDiffusionOperator(Operator):\n def __init__(self, op):\n assert isinstance(op, DiffusionOperator)\n self.op = op\n self.source = WrappedVectorSpace(op.dim_source)\n self.range = WrappedVectorSpace(op.dim_range)\n self.linear = True\n\n @classmethod\n def create(cls, n, left, right):\n return cls(DiffusionOperator(n, left, right))\n\n def apply(self, U, mu=None):\n assert U in self.source\n\n def apply_one_vector(u):\n v = Vector(self.range.dim, 0)\n self.op.apply(u._impl, v)\n return v\n\n return self.range.make_array([apply_one_vector(u) for u in U.vectors])\n", "# This file is part of the pyMOR project (https://www.pymor.org).\n# Copyright pyMOR developers and contributors. All rights reserved.\n# License: BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause)\n\nimport numpy as np\nimport scipy as sp\nfrom scipy.sparse.linalg import eigsh, LinearOperator\nfrom scipy.linalg import lu_factor, lu_solve\nfrom scipy.special import erfinv\n\nfrom pymor.algorithms.gram_schmidt import gram_schmidt\nfrom pymor.core.defaults import defaults\nfrom pymor.operators.interface import Operator\nfrom pymor.core.logger import getLogger\nfrom pymor.operators.constructions import InverseOperator, IdentityOperator\n\n\n@defaults('tol', 'failure_tolerance', 'num_testvecs')\ndef adaptive_rrf(A, source_product=None, range_product=None, tol=1e-4,\n failure_tolerance=1e-15, num_testvecs=20, lambda_min=None, iscomplex=False):\n r\"\"\"Adaptive randomized range approximation of `A`.\n\n This is an implementation of Algorithm 1 in :cite:`BS18`.\n\n Given the |Operator| `A`, the return value of this method is the |VectorArray|\n `B` with the property\n\n .. math::\n \\Vert A - P_{span(B)} A \\Vert \\leq tol\n\n with a failure probability smaller than `failure_tolerance`, where the norm denotes the\n operator norm. The inner product of the range of `A` is given by `range_product` and\n the inner product of the source of `A` is given by `source_product`.\n\n Parameters\n ----------\n A\n The |Operator| A.\n source_product\n Inner product |Operator| of the source of A.\n range_product\n Inner product |Operator| of the range of A.\n tol\n Error tolerance for the algorithm.\n failure_tolerance\n Maximum failure probability.\n num_testvecs\n Number of test vectors.\n lambda_min\n The smallest eigenvalue of source_product.\n If `None`, the smallest eigenvalue is computed using scipy.\n iscomplex\n If `True`, the random vectors are chosen complex.\n\n Returns\n -------\n B\n |VectorArray| which contains the basis, whose span approximates the range of A.\n \"\"\"\n assert source_product is None or isinstance(source_product, Operator)\n assert range_product is None or isinstance(range_product, Operator)\n assert isinstance(A, Operator)\n\n B = A.range.empty()\n\n R = A.source.random(num_testvecs, distribution='normal')\n if iscomplex:\n R += 1j*A.source.random(num_testvecs, distribution='normal')\n\n if source_product is None:\n lambda_min = 1\n elif lambda_min is None:\n def mv(v):\n return source_product.apply(source_product.source.from_numpy(v)).to_numpy()\n\n def mvinv(v):\n return source_product.apply_inverse(source_product.range.from_numpy(v)).to_numpy()\n L = LinearOperator((source_product.source.dim, source_product.range.dim), matvec=mv)\n Linv = LinearOperator((source_product.range.dim, source_product.source.dim), matvec=mvinv)\n lambda_min = eigsh(L, sigma=0, which=\"LM\", return_eigenvectors=False, k=1, OPinv=Linv)[0]\n\n testfail = failure_tolerance / min(A.source.dim, A.range.dim)\n testlimit = np.sqrt(2. * lambda_min) * erfinv(testfail**(1. / num_testvecs)) * tol\n maxnorm = np.inf\n M = A.apply(R)\n\n while(maxnorm > testlimit):\n basis_length = len(B)\n v = A.source.random(distribution='normal')\n if iscomplex:\n v += 1j*A.source.random(distribution='normal')\n B.append(A.apply(v))\n gram_schmidt(B, range_product, atol=0, rtol=0, offset=basis_length, copy=False)\n M -= B.lincomb(B.inner(M, range_product).T)\n maxnorm = np.max(M.norm(range_product))\n\n return B\n\n\n@defaults('q', 'l')\ndef rrf(A, source_product=None, range_product=None, q=2, l=8, return_rand=False, iscomplex=False):\n r\"\"\"Randomized range approximation of `A`.\n\n Given the |Operator| `A`, the return value of this method is the |VectorArray|\n `Q` whose vectors form an approximate orthonormal basis for the range of `A`.\n\n This method is based on algorithm 2 in :cite:`SHB21`.\n\n Parameters\n ----------\n A\n The |Operator| A.\n source_product\n Inner product |Operator| of the source of A.\n range_product\n Inner product |Operator| of the range of A.\n q\n The number of power iterations.\n l\n The block size of the normalized power iterations.\n return_rand\n If `True`, the randomly sampled |VectorArray| R is returned.\n iscomplex\n If `True`, the random vectors are chosen complex.\n\n Returns\n -------\n Q\n |VectorArray| which contains the basis, whose span approximates the range of A.\n R\n The randomly sampled |VectorArray| (if `return_rand` is `True`).\n \"\"\"\n assert isinstance(A, Operator)\n\n if range_product is None:\n range_product = IdentityOperator(A.range)\n else:\n assert isinstance(range_product, Operator)\n\n if source_product is None:\n source_product = IdentityOperator(A.source)\n else:\n assert isinstance(source_product, Operator)\n\n assert 0 <= l <= min(A.source.dim, A.range.dim) and isinstance(l, int)\n assert q >= 0 and isinstance(q, int)\n\n R = A.source.random(l, distribution='normal')\n\n if iscomplex:\n R += 1j*A.source.random(l, distribution='normal')\n\n Q = A.apply(R)\n gram_schmidt(Q, range_product, copy=False)\n\n for i in range(q):\n Q = A.apply_adjoint(range_product.apply(Q))\n Q = source_product.apply_inverse(Q)\n gram_schmidt(Q, source_product, copy=False)\n Q = A.apply(Q)\n gram_schmidt(Q, range_product, copy=False)\n\n if return_rand:\n return Q, R\n else:\n return Q\n\n\n@defaults('p', 'q', 'modes')\ndef random_generalized_svd(A, range_product=None, source_product=None, modes=6, p=20, q=2):\n r\"\"\"Randomized SVD of an |Operator|.\n\n Viewing the `A` as a `A.dim x len(A)` matrix, the return value\n of this method is the randomized singular value decomposition of `A`, where the\n inner product on :math:`\\mathbb{R}^{\\mathtt{A.dim}}` is given by 'range_product' and\n the inner product on :math:`\\mathbb{R}^{\\mathtt{len(A)}}` is given by `source_product`.\n\n .. math::\n\n A = U \\Sigma V^H \\mathtt{source_product}\n\n This method is based on :cite:`SHB21`.\n\n Parameters\n ----------\n A\n The |Operator| for which the randomized SVD is to be computed.\n range_product\n Range product |Operator| w.r.t which the randomized SVD is computed.\n source_product\n Source product |Operator| w.r.t which the randomized SVD is computed.\n modes\n The first `modes` approximated singular values and vectors are returned.\n p\n If not `0`, adds `p` columns to the randomly sampled matrix (oversampling parameter).\n q\n If not `0`, performs `q` so-called power iterations to increase the relative weight\n of the first singular values.\n\n Returns\n -------\n U\n |VectorArray| of approximated left singular vectors.\n s\n One-dimensional |NumPy array| of the approximated singular values.\n Vh\n |VectorArray| of the approximated right singular vectors.\n \"\"\"\n logger = getLogger('pymor.algorithms.rand_la')\n\n assert isinstance(A, Operator)\n\n assert 0 <= modes <= max(A.source.dim, A.range.dim) and isinstance(modes, int)\n assert 0 <= p <= max(A.source.dim, A.range.dim) - modes and isinstance(p, int)\n assert q >= 0 and isinstance(q, int)\n\n if range_product is None:\n range_product = IdentityOperator(A.range)\n else:\n assert isinstance(range_product, Operator)\n assert range_product.source == range_product.range == A.range\n\n if source_product is None:\n source_product = IdentityOperator(A.source)\n else:\n assert isinstance(source_product, Operator)\n assert source_product.source == source_product.range == A.source\n\n if A.source.dim == 0 or A.range.dim == 0:\n return A.source.empty(), np.array([]), A.range.empty()\n\n Q = rrf(A, source_product=source_product, range_product=range_product, q=q, l=modes+p)\n B = A.apply_adjoint(range_product.apply(Q))\n Q_B, R_B = gram_schmidt(source_product.apply_inverse(B), product=source_product, return_R=True)\n U_b, s, Vh_b = sp.linalg.svd(R_B.T, full_matrices=False)\n\n with logger.block(f'Computing generalized left-singular vectors ({modes} vectors) ...'):\n U = Q.lincomb(U_b.T)\n\n with logger.block(f'Computung generalized right-singular vector ({modes} vectors) ...'):\n Vh = Q_B.lincomb(Vh_b)\n\n return U[:modes], s[:modes], Vh[:modes]\n\n\n@defaults('modes', 'p', 'q')\ndef random_ghep(A, E=None, modes=6, p=20, q=2, single_pass=False):\n r\"\"\"Approximates a few eigenvalues of a symmetric linear |Operator| with randomized methods.\n\n Approximates `modes` eigenvalues `w` with corresponding eigenvectors `v` which solve\n the eigenvalue problem\n\n .. math::\n A v_i = w_i v_i\n\n or the generalized eigenvalue problem\n\n .. math::\n A v_i = w_i E v_i\n\n if `E` is not `None`.\n\n This method is an implementation of algorithm 6 and 7 in :cite:`SJK16`.\n\n Parameters\n ----------\n A\n The Hermitian linear |Operator| for which the eigenvalues are to be computed.\n E\n The Hermitian |Operator| which defines the generalized eigenvalue problem.\n modes\n The number of eigenvalues and eigenvectors which are to be computed.\n p\n If not `0`, adds `p` columns to the randomly sampled matrix in the :func:`rrf` method\n (oversampling parameter).\n q\n If not `0`, performs `q` power iterations to increase the relative weight\n of the larger singular values. Ignored when `single_pass` is `True`.\n single_pass\n If `True`, computes the GHEP where only one set of matvecs Ax is required, but at the\n expense of lower numerical accuracy.\n If `False`, the methods require two sets of matvecs Ax.\n\n Returns\n -------\n w\n A 1D |NumPy array| which contains the computed eigenvalues.\n V\n A |VectorArray| which contains the computed eigenvectors.\n \"\"\"\n logger = getLogger('pymor.algorithms.rand_la')\n\n assert isinstance(A, Operator) and A.linear\n assert not A.parametric\n assert A.source == A.range\n assert 0 <= modes <= max(A.source.dim, A.range.dim) and isinstance(modes, int)\n assert 0 <= p <= max(A.source.dim, A.range.dim) - modes and isinstance(p, int)\n assert q >= 0 and isinstance(q, int)\n\n if E is None:\n E = IdentityOperator(A.source)\n else:\n assert isinstance(E, Operator) and E.linear\n assert not E.parametric\n assert E.source == E.range\n assert E.source == A.source\n\n if A.source.dim == 0 or A.range.dim == 0:\n return A.source.empty(), np.array([]), A.range.empty()\n\n if single_pass:\n Omega = A.source.random(modes+p, distribution='normal')\n Y_bar = A.apply(Omega)\n Y = E.apply_inverse(Y_bar)\n Q, R = gram_schmidt(Y, product=E, return_R=True)\n X = E.apply2(Omega, Q)\n X_lu = lu_factor(X)\n T = lu_solve(X_lu, lu_solve(X_lu, Omega.inner(Y_bar)).T).T\n else:\n C = InverseOperator(E) @ A\n Y, Omega = rrf(C, q=q, l=modes+p, return_rand=True)\n Q = gram_schmidt(Y, product=E)\n T = A.apply2(Q, Q)\n\n w, S = sp.linalg.eigh(T)\n w = w[::-1]\n S = S[:, ::-1]\n\n with logger.block(f'Computing eigenvectors ({modes} vectors) ...'):\n V = Q.lincomb(S)\n\n return w[:modes], V[:modes]\n", "# This file is part of the pyMOR project (https://www.pymor.org).\n# Copyright pyMOR developers and contributors. All rights reserved.\n# License: BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause)\n\nfrom pymor.core.config import config\nconfig.require('TORCH')\n\n\nfrom numbers import Number\nimport inspect\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils as utils\n\nfrom pymor.algorithms.pod import pod\nfrom pymor.algorithms.projection import project\nfrom pymor.core.base import BasicObject\nfrom pymor.core.exceptions import NeuralNetworkTrainingFailed\nfrom pymor.core.logger import getLogger\nfrom pymor.models.neural_network import (FullyConnectedNN, NeuralNetworkModel,\n NeuralNetworkStatefreeOutputModel,\n NeuralNetworkInstationaryModel,\n NeuralNetworkInstationaryStatefreeOutputModel)\n\n\nclass NeuralNetworkReductor(BasicObject):\n \"\"\"Reduced Basis reductor relying on artificial neural networks.\n\n This is a reductor that constructs a reduced basis using proper\n orthogonal decomposition and trains a neural network that approximates\n the mapping from parameter space to coefficients of the full-order\n solution in the reduced basis.\n The approach is described in :cite:`HU18`.\n\n Parameters\n ----------\n fom\n The full-order |Model| to reduce.\n training_set\n Set of |parameter values| to use for POD and training of the\n neural network.\n validation_set\n Set of |parameter values| to use for validation in the training\n of the neural network.\n validation_ratio\n Fraction of the training set to use for validation in the training\n of the neural network (only used if no validation set is provided).\n basis_size\n Desired size of the reduced basis. If `None`, rtol, atol or l2_err must\n be provided.\n rtol\n Relative tolerance the basis should guarantee on the training set.\n atol\n Absolute tolerance the basis should guarantee on the training set.\n l2_err\n L2-approximation error the basis should not exceed on the training\n set.\n pod_params\n Dict of additional parameters for the POD-method.\n ann_mse\n If `'like_basis'`, the mean squared error of the neural network on\n the training set should not exceed the error of projecting onto the basis.\n If `None`, the neural network with smallest validation error is\n used to build the ROM.\n If a tolerance is prescribed, the mean squared error of the neural\n network on the training set should not exceed this threshold.\n Training is interrupted if a neural network that undercuts the\n error tolerance is found.\n scale_inputs\n Determines whether or not to scale the inputs of the neural networks.\n scale_outputs\n Determines whether or not to scale the outputs/targets of the neural\n networks.\n \"\"\"\n\n def __init__(self, fom, training_set, validation_set=None, validation_ratio=0.1,\n basis_size=None, rtol=0., atol=0., l2_err=0., pod_params={},\n ann_mse='like_basis', scale_inputs=True, scale_outputs=False):\n assert 0 < validation_ratio < 1 or validation_set\n\n self.scaling_parameters = {'min_inputs': None, 'max_inputs': None,\n 'min_targets': None, 'max_targets': None}\n\n self.__auto_init(locals())\n\n def reduce(self, hidden_layers='[(N+P)*3, (N+P)*3]', activation_function=torch.tanh,\n optimizer=optim.LBFGS, epochs=1000, batch_size=20, learning_rate=1.,\n loss_function=None, restarts=10, lr_scheduler=optim.lr_scheduler.StepLR,\n lr_scheduler_params={'step_size': 10, 'gamma': 0.7},\n es_scheduler_params={'patience': 10, 'delta': 0.}, weight_decay=0.,\n log_loss_frequency=0, seed=0):\n \"\"\"Reduce by training artificial neural networks.\n\n Parameters\n ----------\n hidden_layers\n Number of neurons in the hidden layers. Can either be fixed or\n a Python expression string depending on the reduced basis size\n respectively output dimension `N` and the total dimension of\n the |Parameters| `P`.\n activation_function\n Activation function to use between the hidden layers.\n optimizer\n Algorithm to use as optimizer during training.\n epochs\n Maximum number of epochs for training.\n batch_size\n Batch size to use if optimizer allows mini-batching.\n learning_rate\n Step size to use in each optimization step.\n loss_function\n Loss function to use for training. If `'weighted MSE'`, a weighted\n mean squared error is used as loss function, where the weights are\n given as the singular values of the corresponding reduced basis\n functions. If `None`, the usual mean squared error is used.\n restarts\n Number of restarts of the training algorithm. Since the training\n results highly depend on the initial starting point, i.e. the\n initial weights and biases, it is advisable to train multiple\n neural networks by starting with different initial values and\n choose that one performing best on the validation set.\n lr_scheduler\n Algorithm to use as learning rate scheduler during training.\n If `None`, no learning rate scheduler is used.\n lr_scheduler_params\n A dictionary of additional parameters passed to the init method of\n the learning rate scheduler. The possible parameters depend on the\n chosen learning rate scheduler.\n es_scheduler_params\n A dictionary of additional parameters passed to the init method of\n the early stopping scheduler. For the possible parameters,\n see :class:`EarlyStoppingScheduler`.\n weight_decay\n Weighting parameter for the l2-regularization of the weights and\n biases in the neural network. This regularization is not available\n for all optimizers; see the PyTorch documentation for more details.\n log_loss_frequency\n Frequency of epochs in which to log the current validation and\n training loss during training of the neural networks.\n If `0`, no intermediate logging of losses is done.\n seed\n Seed to use for various functions in PyTorch. Using a fixed seed,\n it is possible to reproduce former results.\n\n Returns\n -------\n rom\n Reduced-order |NeuralNetworkModel|.\n \"\"\"\n assert restarts > 0\n assert epochs > 0\n assert batch_size > 0\n assert learning_rate > 0.\n assert weight_decay >= 0.\n\n # set a seed for the PyTorch initialization of weights and biases\n # and further PyTorch methods\n torch.manual_seed(seed)\n\n # build a reduced basis using POD and compute training data\n if not hasattr(self, 'training_data'):\n self.compute_training_data()\n\n layer_sizes = self._compute_layer_sizes(hidden_layers)\n\n # compute validation data\n if not hasattr(self, 'validation_data'):\n with self.logger.block('Computing validation snapshots ...'):\n\n if self.validation_set:\n self.validation_data = []\n for mu in self.validation_set:\n sample = self._compute_sample(mu)\n self.validation_data.extend(sample)\n else:\n number_validation_snapshots = int(len(self.training_data)*self.validation_ratio)\n # randomly shuffle training data before splitting into two sets\n np.random.shuffle(self.training_data)\n # split training data into validation and training set\n self.validation_data = self.training_data[0:number_validation_snapshots]\n self.training_data = self.training_data[number_validation_snapshots+1:]\n\n # run the actual training of the neural network\n with self.logger.block('Training of neural network ...'):\n target_loss = self._compute_target_loss()\n # set parameters for neural network and training\n neural_network_parameters = {'layer_sizes': layer_sizes,\n 'activation_function': activation_function}\n if loss_function == 'weighted MSE':\n if hasattr(self, 'weights'):\n weights = self.weights\n\n def weighted_mse_loss_function(inputs, targets):\n return (weights * (inputs - targets) ** 2).mean()\n\n loss_function = weighted_mse_loss_function\n self.logger.info('Using weighted MSE loss function ...')\n else:\n raise RuntimeError('No weights for weighted MSE loss available!')\n training_parameters = {'optimizer': optimizer, 'epochs': epochs,\n 'batch_size': batch_size, 'learning_rate': learning_rate,\n 'lr_scheduler': lr_scheduler, 'lr_scheduler_params': lr_scheduler_params,\n 'es_scheduler_params': es_scheduler_params, 'weight_decay': weight_decay,\n 'loss_function': loss_function}\n\n self.logger.info('Initializing neural network ...')\n # initialize the neural network\n neural_network = FullyConnectedNN(**neural_network_parameters).double()\n # run training algorithm with multiple restarts\n self.neural_network, self.losses = multiple_restarts_training(self.training_data, self.validation_data,\n neural_network, target_loss, restarts,\n log_loss_frequency, training_parameters,\n self.scaling_parameters, seed)\n\n self._check_tolerances()\n\n return self._build_rom()\n\n def compute_training_data(self):\n \"\"\"Compute a reduced basis using proper orthogonal decomposition.\"\"\"\n # compute snapshots for POD and training of neural networks\n with self.logger.block('Computing training snapshots ...'):\n U = self.fom.solution_space.empty()\n for mu in self.training_set:\n U.append(self.fom.solve(mu))\n\n # compute reduced basis via POD\n with self.logger.block('Building reduced basis ...'):\n self.reduced_basis, svals = pod(U, modes=self.basis_size, rtol=self.rtol / 2.,\n atol=self.atol / 2., l2_err=self.l2_err / 2.,\n **(self.pod_params or {}))\n\n # compute training samples\n with self.logger.block('Computing training samples ...'):\n self.training_data = []\n for mu, u in zip(self.training_set, U):\n sample = self._compute_sample(mu, u)\n # compute minimum and maximum of outputs/targets for scaling\n self._update_scaling_parameters(sample)\n self.training_data.extend(sample)\n\n # set singular values as weights for the weighted MSE loss\n self.weights = torch.Tensor(svals)\n\n # compute mean square loss\n self.mse_basis = (sum(U.norm2()) - sum(svals**2)) / len(U)\n\n def _update_scaling_parameters(self, sample):\n assert len(sample) == 2 or (len(sample) == 1 and len(sample[0]) == 2)\n if len(sample) == 1:\n sample = sample[0]\n\n def prepare_datum(datum):\n if not (isinstance(datum, torch.DoubleTensor) or isinstance(datum, np.ndarray)):\n return datum.to_numpy()\n return datum\n sample = (torch.DoubleTensor(prepare_datum(sample[0])), torch.DoubleTensor(prepare_datum(sample[1])))\n\n if self.scale_inputs:\n if self.scaling_parameters['min_inputs'] is not None:\n self.scaling_parameters['min_inputs'] = torch.min(self.scaling_parameters['min_inputs'], sample[0])\n else:\n self.scaling_parameters['min_inputs'] = sample[0]\n if self.scaling_parameters['max_inputs'] is not None:\n self.scaling_parameters['max_inputs'] = torch.max(self.scaling_parameters['max_inputs'], sample[0])\n else:\n self.scaling_parameters['max_inputs'] = sample[0]\n\n if self.scale_outputs:\n if self.scaling_parameters['min_targets'] is not None:\n self.scaling_parameters['min_targets'] = torch.min(self.scaling_parameters['min_targets'],\n sample[1])\n else:\n self.scaling_parameters['min_targets'] = sample[1]\n if self.scaling_parameters['max_targets'] is not None:\n self.scaling_parameters['max_targets'] = torch.max(self.scaling_parameters['max_targets'],\n sample[1])\n else:\n self.scaling_parameters['max_targets'] = sample[1]\n\n def _compute_sample(self, mu, u=None):\n \"\"\"Transform parameter and corresponding solution to |NumPy arrays|.\"\"\"\n # determine the coefficients of the full-order solutions in the reduced basis to obtain\n # the training data\n if u is None:\n u = self.fom.solve(mu)\n\n product = self.pod_params.get('product')\n\n return [(mu, self.reduced_basis.inner(u, product=product)[:, 0])]\n\n def _compute_layer_sizes(self, hidden_layers):\n \"\"\"Compute the number of neurons in the layers of the neural network.\"\"\"\n # determine the numbers of neurons in the hidden layers\n if isinstance(hidden_layers, str):\n hidden_layers = eval(hidden_layers, {'N': len(self.reduced_basis), 'P': self.fom.parameters.dim})\n # input and output size of the neural network are prescribed by the\n # dimension of the parameter space and the reduced basis size\n assert isinstance(hidden_layers, list)\n return [self.fom.parameters.dim, ] + hidden_layers + [len(self.reduced_basis), ]\n\n def _compute_target_loss(self):\n \"\"\"Compute target loss depending on value of `ann_mse`.\"\"\"\n target_loss = None\n if isinstance(self.ann_mse, Number):\n target_loss = self.ann_mse\n elif self.ann_mse == 'like_basis':\n target_loss = self.mse_basis\n return target_loss\n\n def _check_tolerances(self):\n \"\"\"Check if trained neural network is sufficient to guarantee certain error bounds.\"\"\"\n with self.logger.block('Checking tolerances for error of neural network ...'):\n\n if isinstance(self.ann_mse, Number):\n if self.losses['full'] > self.ann_mse:\n raise NeuralNetworkTrainingFailed('Could not train a neural network that '\n 'guarantees prescribed tolerance!')\n elif self.ann_mse == 'like_basis':\n if self.losses['full'] > self.mse_basis:\n raise NeuralNetworkTrainingFailed('Could not train a neural network with an error as small as '\n 'the reduced basis error! Maybe you can try a different '\n 'neural network architecture or change the value of '\n '`ann_mse`.')\n elif self.ann_mse is None:\n self.logger.info('Using neural network with smallest validation error ...')\n self.logger.info(f'Finished training with a validation loss of {self.losses[\"val\"]} ...')\n else:\n raise ValueError('Unknown value for mean squared error of neural network')\n\n def _build_rom(self):\n \"\"\"Construct the reduced order model.\"\"\"\n with self.logger.block('Building ROM ...'):\n projected_output_functional = project(self.fom.output_functional, None, self.reduced_basis)\n rom = NeuralNetworkModel(self.neural_network, parameters=self.fom.parameters,\n scaling_parameters=self.scaling_parameters,\n output_functional=projected_output_functional,\n name=f'{self.fom.name}_reduced')\n\n return rom\n\n def reconstruct(self, u):\n \"\"\"Reconstruct high-dimensional vector from reduced vector `u`.\"\"\"\n assert hasattr(self, 'reduced_basis')\n return self.reduced_basis.lincomb(u.to_numpy())\n\n\nclass NeuralNetworkStatefreeOutputReductor(NeuralNetworkReductor):\n \"\"\"Output reductor relying on artificial neural networks.\n\n This is a reductor that trains a neural network that approximates\n the mapping from parameter space to output space.\n\n Parameters\n ----------\n fom\n The full-order |Model| to reduce.\n training_set\n Set of |parameter values| to use for POD and training of the\n neural network.\n validation_set\n Set of |parameter values| to use for validation in the training\n of the neural network.\n validation_ratio\n Fraction of the training set to use for validation in the training\n of the neural network (only used if no validation set is provided).\n validation_loss\n The validation loss to reach during training. If `None`, the neural\n network with the smallest validation loss is returned.\n scale_inputs\n Determines whether or not to scale the inputs of the neural networks.\n scale_outputs\n Determines whether or not to scale the outputs/targets of the neural\n networks.\n \"\"\"\n\n def __init__(self, fom, training_set, validation_set=None, validation_ratio=0.1,\n validation_loss=None, scale_inputs=True, scale_outputs=False):\n assert 0 < validation_ratio < 1 or validation_set\n\n self.scaling_parameters = {'min_inputs': None, 'max_inputs': None,\n 'min_targets': None, 'max_targets': None}\n\n self.__auto_init(locals())\n\n def compute_training_data(self):\n \"\"\"Compute the training samples (the outputs to the parameters of the training set).\"\"\"\n with self.logger.block('Computing training samples ...'):\n self.training_data = []\n for mu in self.training_set:\n sample = self._compute_sample(mu)\n self._update_scaling_parameters(sample)\n self.training_data.extend(sample)\n\n def _compute_sample(self, mu):\n \"\"\"Transform parameter and corresponding output to tensors.\"\"\"\n return [(mu, self.fom.output(mu).flatten())]\n\n def _compute_layer_sizes(self, hidden_layers):\n \"\"\"Compute the number of neurons in the layers of the neural network.\"\"\"\n # determine the numbers of neurons in the hidden layers\n if isinstance(hidden_layers, str):\n hidden_layers = eval(hidden_layers, {'N': self.fom.dim_output, 'P': self.fom.parameters.dim})\n # input and output size of the neural network are prescribed by the\n # dimension of the parameter space and the output dimension\n assert isinstance(hidden_layers, list)\n return [self.fom.parameters.dim, ] + hidden_layers + [self.fom.dim_output, ]\n\n def _compute_target_loss(self):\n \"\"\"Compute target loss depending on value of `ann_mse`.\"\"\"\n return self.validation_loss\n\n def _check_tolerances(self):\n \"\"\"Check if trained neural network is sufficient to guarantee certain error bounds.\"\"\"\n self.logger.info('Using neural network with smallest validation error ...')\n self.logger.info(f'Finished training with a validation loss of {self.losses[\"val\"]} ...')\n\n def _build_rom(self):\n \"\"\"Construct the reduced order model.\"\"\"\n with self.logger.block('Building ROM ...'):\n rom = NeuralNetworkStatefreeOutputModel(self.neural_network, parameters=self.fom.parameters,\n scaling_parameters=self.scaling_parameters,\n name=f'{self.fom.name}_output_reduced')\n\n return rom\n\n\nclass NeuralNetworkInstationaryReductor(NeuralNetworkReductor):\n \"\"\"Reduced Basis reductor for instationary problems relying on artificial neural networks.\n\n This is a reductor that constructs a reduced basis using proper\n orthogonal decomposition and trains a neural network that approximates\n the mapping from parameter and time space to coefficients of the\n full-order solution in the reduced basis.\n The approach is described in :cite:`WHR19`.\n\n Parameters\n ----------\n fom\n The full-order |Model| to reduce.\n training_set\n Set of |parameter values| to use for POD and training of the\n neural network.\n validation_set\n Set of |parameter values| to use for validation in the training\n of the neural network.\n validation_ratio\n Fraction of the training set to use for validation in the training\n of the neural network (only used if no validation set is provided).\n basis_size\n Desired size of the reduced basis. If `None`, rtol, atol or l2_err must\n be provided.\n rtol\n Relative tolerance the basis should guarantee on the training set.\n atol\n Absolute tolerance the basis should guarantee on the training set.\n l2_err\n L2-approximation error the basis should not exceed on the training\n set.\n pod_params\n Dict of additional parameters for the POD-method.\n ann_mse\n If `'like_basis'`, the mean squared error of the neural network on\n the training set should not exceed the error of projecting onto the basis.\n If `None`, the neural network with smallest validation error is\n used to build the ROM.\n If a tolerance is prescribed, the mean squared error of the neural\n network on the training set should not exceed this threshold.\n Training is interrupted if a neural network that undercuts the\n error tolerance is found.\n scale_inputs\n Determines whether or not to scale the inputs of the neural networks.\n scale_outputs\n Determines whether or not to scale the outputs/targets of the neural\n networks.\n \"\"\"\n\n def __init__(self, fom, training_set, validation_set=None, validation_ratio=0.1,\n basis_size=None, rtol=0., atol=0., l2_err=0., pod_params={},\n ann_mse='like_basis', scale_inputs=True, scale_outputs=False):\n assert 0 < validation_ratio < 1 or validation_set\n\n self.scaling_parameters = {'min_inputs': None, 'max_inputs': None,\n 'min_targets': None, 'max_targets': None}\n\n self.__auto_init(locals())\n\n def compute_training_data(self):\n \"\"\"Compute a reduced basis using proper orthogonal decomposition.\"\"\"\n # compute snapshots for POD and training of neural networks\n with self.logger.block('Computing training snapshots ...'):\n U = self.fom.solution_space.empty()\n for mu in self.training_set:\n u = self.fom.solve(mu)\n if hasattr(self, 'nt'):\n assert self.nt == len(u)\n else:\n self.nt = len(u)\n U.append(u)\n\n # compute reduced basis via POD\n with self.logger.block('Building reduced basis ...'):\n self.reduced_basis, svals = pod(U, modes=self.basis_size, rtol=self.rtol / 2.,\n atol=self.atol / 2., l2_err=self.l2_err / 2.,\n **(self.pod_params or {}))\n\n # compute training samples\n with self.logger.block('Computing training samples ...'):\n self.training_data = []\n for i, mu in enumerate(self.training_set):\n samples = self._compute_sample(mu, U[i*self.nt:(i+1)*self.nt])\n for sample in samples:\n self._update_scaling_parameters(sample)\n self.training_data.extend(samples)\n\n # set singular values as weights for the weighted MSE loss\n self.weights = torch.Tensor(svals)\n\n # compute mean square loss\n self.mse_basis = (sum(U.norm2()) - sum(svals**2)) / len(U)\n\n def _compute_sample(self, mu, u=None):\n \"\"\"Transform parameter and corresponding solution to |NumPy arrays|.\n\n This function takes care of including the time instances in the inputs.\n \"\"\"\n if u is None:\n u = self.fom.solve(mu)\n\n parameters_with_time = [mu.with_(t=t) for t in np.linspace(0, self.fom.T, self.nt)]\n\n product = self.pod_params.get('product')\n\n samples = [(mu, self.reduced_basis.inner(u_t, product=product)[:, 0])\n for mu, u_t in zip(parameters_with_time, u)]\n\n return samples\n\n def _compute_layer_sizes(self, hidden_layers):\n \"\"\"Compute the number of neurons in the layers of the neural network\n\n (make sure to increase the input dimension to account for the time).\n \"\"\"\n # determine the numbers of neurons in the hidden layers\n if isinstance(hidden_layers, str):\n hidden_layers = eval(hidden_layers, {'N': len(self.reduced_basis), 'P': self.fom.parameters.dim})\n # input and output size of the neural network are prescribed by the\n # dimension of the parameter space and the reduced basis size\n assert isinstance(hidden_layers, list)\n return [self.fom.parameters.dim + 1, ] + hidden_layers + [len(self.reduced_basis), ]\n\n def _build_rom(self):\n \"\"\"Construct the reduced order model.\"\"\"\n with self.logger.block('Building ROM ...'):\n projected_output_functional = project(self.fom.output_functional, None, self.reduced_basis)\n rom = NeuralNetworkInstationaryModel(self.fom.T, self.nt, self.neural_network,\n parameters=self.fom.parameters,\n scaling_parameters=self.scaling_parameters,\n output_functional=projected_output_functional,\n name=f'{self.fom.name}_reduced')\n\n return rom\n\n\nclass NeuralNetworkInstationaryStatefreeOutputReductor(NeuralNetworkStatefreeOutputReductor):\n \"\"\"Output reductor relying on artificial neural networks.\n\n This is a reductor that trains a neural network that approximates\n the mapping from parameter space to output space.\n\n Parameters\n ----------\n fom\n The full-order |Model| to reduce.\n nt\n Number of time steps in the reduced order model (does not have to\n coincide with the number of time steps in the full order model).\n training_set\n Set of |parameter values| to use for POD and training of the\n neural network.\n validation_set\n Set of |parameter values| to use for validation in the training\n of the neural network.\n validation_ratio\n Fraction of the training set to use for validation in the training\n of the neural network (only used if no validation set is provided).\n validation_loss\n The validation loss to reach during training. If `None`, the neural\n network with the smallest validation loss is returned.\n scale_inputs\n Determines whether or not to scale the inputs of the neural networks.\n scale_outputs\n Determines whether or not to scale the outputs/targets of the neural\n networks.\n \"\"\"\n\n def __init__(self, fom, nt, training_set, validation_set=None, validation_ratio=0.1,\n validation_loss=None, scale_inputs=True, scale_outputs=False):\n assert 0 < validation_ratio < 1 or validation_set\n\n self.scaling_parameters = {'min_inputs': None, 'max_inputs': None,\n 'min_targets': None, 'max_targets': None}\n\n self.__auto_init(locals())\n\n def compute_training_data(self):\n \"\"\"Compute the training samples (the outputs to the parameters of the training set).\"\"\"\n with self.logger.block('Computing training samples ...'):\n self.training_data = []\n for mu in self.training_set:\n samples = self._compute_sample(mu)\n for sample in samples:\n self._update_scaling_parameters(sample)\n self.training_data.extend(samples)\n\n def _compute_sample(self, mu):\n \"\"\"Transform parameter and corresponding output to |NumPy arrays|.\n\n This function takes care of including the time instances in the inputs.\n \"\"\"\n output_trajectory = self.fom.output(mu)\n output_size = output_trajectory.shape[0]\n samples = [(mu.with_(t=t), output.flatten())\n for t, output in zip(np.linspace(0, self.fom.T, output_size), output_trajectory)]\n\n return samples\n\n def _compute_layer_sizes(self, hidden_layers):\n \"\"\"Compute the number of neurons in the layers of the neural network.\"\"\"\n # determine the numbers of neurons in the hidden layers\n if isinstance(hidden_layers, str):\n hidden_layers = eval(hidden_layers, {'N': self.fom.dim_output, 'P': self.fom.parameters.dim})\n # input and output size of the neural network are prescribed by the\n # dimension of the parameter space and the output dimension\n assert isinstance(hidden_layers, list)\n return [self.fom.parameters.dim + 1, ] + hidden_layers + [self.fom.dim_output, ]\n\n def _build_rom(self):\n \"\"\"Construct the reduced order model.\"\"\"\n with self.logger.block('Building ROM ...'):\n rom = NeuralNetworkInstationaryStatefreeOutputModel(self.fom.T, self.nt, self.neural_network,\n parameters=self.fom.parameters,\n scaling_parameters=self.scaling_parameters,\n name=f'{self.fom.name}_output_reduced')\n\n return rom\n\n\nclass EarlyStoppingScheduler(BasicObject):\n \"\"\"Class for performing early stopping in training of neural networks.\n\n If the validation loss does not decrease over a certain amount of epochs, the\n training should be aborted to avoid overfitting the training data.\n This class implements an early stopping scheduler that recommends to stop the\n training process if the validation loss did not decrease by at least `delta`\n over `patience` epochs.\n\n Parameters\n ----------\n size_training_validation_set\n Size of both, training and validation set together.\n patience\n Number of epochs of non-decreasing validation loss allowed, before early\n stopping the training process.\n delta\n Minimal amount of decrease in the validation loss that is required to reset\n the counter of non-decreasing epochs.\n \"\"\"\n\n def __init__(self, size_training_validation_set, patience=10, delta=0.):\n self.__auto_init(locals())\n\n self.best_losses = None\n self.best_neural_network = None\n self.counter = 0\n\n def __call__(self, losses, neural_network=None):\n \"\"\"Returns `True` if early stopping of training is suggested.\n\n Parameters\n ----------\n losses\n Dictionary of losses on the validation and the training set in\n the current epoch.\n neural_network\n Neural network that produces the current validation loss.\n\n Returns\n -------\n `True` if early stopping is suggested, `False` otherwise.\n \"\"\"\n if self.best_losses is None:\n self.best_losses = losses\n self.best_losses['full'] /= self.size_training_validation_set\n self.best_neural_network = neural_network\n elif self.best_losses['val'] - self.delta <= losses['val']:\n self.counter += 1\n if self.counter >= self.patience:\n return True\n else:\n self.best_losses = losses\n self.best_losses['full'] /= self.size_training_validation_set\n self.best_neural_network = neural_network\n self.counter = 0\n\n return False\n\n\nclass CustomDataset(utils.data.Dataset):\n \"\"\"Class that represents the dataset to use in PyTorch.\n\n Parameters\n ----------\n training_data\n Set of training parameters and the respective coefficients of the\n solution in the reduced basis.\n \"\"\"\n\n def __init__(self, training_data):\n self.training_data = training_data\n\n def __len__(self):\n return len(self.training_data)\n\n def __getitem__(self, idx):\n t = self.training_data[idx]\n return t\n\n\ndef train_neural_network(training_data, validation_data, neural_network,\n training_parameters={}, scaling_parameters={}, log_loss_frequency=0):\n \"\"\"Training algorithm for artificial neural networks.\n\n Trains a single neural network using the given training and validation data.\n\n Parameters\n ----------\n training_data\n Data to use during the training phase. Has to be a list of tuples,\n where each tuple consists of two elements that are either\n PyTorch-tensors (`torch.DoubleTensor`) or |NumPy arrays| or pyMOR data\n structures that have `to_numpy()` implemented.\n The first element contains the input data, the second element contains\n the target values.\n validation_data\n Data to use during the validation phase. Has to be a list of tuples,\n where each tuple consists of two elements that are either\n PyTorch-tensors (`torch.DoubleTensor`) or |NumPy arrays| or pyMOR data\n structures that have `to_numpy()` implemented.\n The first element contains the input data, the second element contains\n the target values.\n neural_network\n The neural network to train (can also be a pre-trained model).\n Has to be a PyTorch-Module.\n training_parameters\n Dictionary with additional parameters for the training routine like\n the type of the optimizer, the (maximum) number of epochs, the batch\n size, the learning rate or the loss function to use.\n Possible keys are `'optimizer'` (an optimizer from the PyTorch `optim`\n package; if not provided, the LBFGS-optimizer is taken as default),\n `'epochs'` (an integer that determines the number of epochs to use\n for training the neural network (if training is not interrupted\n prematurely due to early stopping); if not provided, 1000 is taken as\n default value), `'batch_size'` (an integer that determines the number\n of samples to pass to the optimizer at once; if not provided, 20 is\n taken as default value; not used in the case of the LBFGS-optimizer\n since LBFGS does not support mini-batching), `'learning_rate'` (a\n positive real number used as the (initial) step size of the optimizer;\n if not provided, 1 is taken as default value), `'loss_function'`\n (a loss function from PyTorch; if not provided, the MSE loss is taken\n as default), `'lr_scheduler'` (a learning rate scheduler from the\n PyTorch `optim.lr_scheduler` package; if not provided or `None`,\n no learning rate scheduler is used), `'lr_scheduler_params'`\n (a dictionary of additional parameters for the learning rate\n scheduler), `'es_scheduler_params'` (a dictionary of additional\n parameters for the early stopping scheduler), and `'weight_decay'`\n (non-negative real number that determines the strenght of the\n l2-regularization; if not provided or 0., no regularization is applied).\n scaling_parameters\n Dict of tensors that determine how to scale inputs before passing them\n through the neural network and outputs after obtaining them from the\n neural network. If not provided or each entry is `None`, no scaling is\n applied. Required keys are `'min_inputs'`, `'max_inputs'`, `'min_targets'`,\n and `'max_targets'`.\n log_loss_frequency\n Frequency of epochs in which to log the current validation and\n training loss. If `0`, no intermediate logging of losses is done.\n\n Returns\n -------\n best_neural_network\n The best trained neural network with respect to validation loss.\n losses\n The corresponding losses as a dictionary with keys `'full'` (for the\n full loss containing the training and the validation average loss),\n `'train'` (for the average loss on the training set), and `'val'`\n (for the average loss on the validation set).\n \"\"\"\n assert isinstance(neural_network, nn.Module)\n assert isinstance(log_loss_frequency, int)\n\n for data in training_data, validation_data:\n assert isinstance(data, list)\n assert all(isinstance(datum, tuple) and len(datum) == 2 for datum in data)\n\n def prepare_datum(datum):\n if not (isinstance(datum, torch.DoubleTensor) or isinstance(datum, np.ndarray)):\n return datum.to_numpy()\n return datum\n\n training_data = [(prepare_datum(datum[0]), prepare_datum(datum[1])) for datum in training_data]\n validation_data = [(prepare_datum(datum[0]), prepare_datum(datum[1])) for datum in validation_data]\n\n optimizer = optim.LBFGS if 'optimizer' not in training_parameters else training_parameters['optimizer']\n epochs = 1000 if 'epochs' not in training_parameters else training_parameters['epochs']\n assert isinstance(epochs, int) and epochs > 0\n batch_size = 20 if 'batch_size' not in training_parameters else training_parameters['batch_size']\n assert isinstance(batch_size, int) and batch_size > 0\n learning_rate = 1. if 'learning_rate' not in training_parameters else training_parameters['learning_rate']\n assert learning_rate > 0.\n loss_function = (nn.MSELoss() if (training_parameters.get('loss_function') is None)\n else training_parameters['loss_function'])\n\n logger = getLogger('pymor.algorithms.neural_network.train_neural_network')\n\n # LBFGS-optimizer does not support mini-batching, so the batch size needs to be adjusted\n if optimizer == optim.LBFGS:\n batch_size = max(len(training_data), len(validation_data))\n\n # initialize optimizer, early stopping scheduler and learning rate scheduler\n weight_decay = training_parameters.get('weight_decay', 0.)\n assert weight_decay >= 0.\n if weight_decay > 0. and 'weight_decay' not in inspect.getfullargspec(optimizer).args:\n optimizer = optimizer(neural_network.parameters(), lr=learning_rate)\n logger.warning(f\"Optimizer {optimizer.__class__.__name__} does not support weight decay! \"\n \"Continuing without regularization!\")\n elif 'weight_decay' in inspect.getfullargspec(optimizer).args:\n optimizer = optimizer(neural_network.parameters(), lr=learning_rate,\n weight_decay=weight_decay)\n else:\n optimizer = optimizer(neural_network.parameters(), lr=learning_rate)\n\n if 'es_scheduler_params' in training_parameters:\n es_scheduler = EarlyStoppingScheduler(len(training_data) + len(validation_data),\n **training_parameters['es_scheduler_params'])\n else:\n es_scheduler = EarlyStoppingScheduler(len(training_data) + len(validation_data))\n if training_parameters.get('lr_scheduler'):\n lr_scheduler = training_parameters['lr_scheduler'](optimizer, **training_parameters['lr_scheduler_params'])\n\n # create the training and validation sets as well as the respective data loaders\n training_dataset = CustomDataset(training_data)\n validation_dataset = CustomDataset(validation_data)\n training_loader = utils.data.DataLoader(training_dataset, batch_size=batch_size)\n validation_loader = utils.data.DataLoader(validation_dataset, batch_size=batch_size)\n dataloaders = {'train': training_loader, 'val': validation_loader}\n\n phases = ['train', 'val']\n\n logger.info('Starting optimization procedure ...')\n\n if 'min_inputs' in scaling_parameters and 'max_inputs' in scaling_parameters:\n min_inputs = scaling_parameters['min_inputs']\n max_inputs = scaling_parameters['max_inputs']\n else:\n min_inputs = None\n max_inputs = None\n if 'min_targets' in scaling_parameters and 'max_targets' in scaling_parameters:\n min_targets = scaling_parameters['min_targets']\n max_targets = scaling_parameters['max_targets']\n else:\n min_targets = None\n max_targets = None\n\n # perform optimization procedure\n for epoch in range(epochs):\n losses = {'full': 0.}\n\n # alternate between training and validation phase\n for phase in phases:\n if phase == 'train':\n neural_network.train()\n else:\n neural_network.eval()\n\n running_loss = 0.0\n\n # iterate over batches\n for batch in dataloaders[phase]:\n # scale inputs and outputs if desired\n if min_inputs is not None and max_inputs is not None:\n inputs = (batch[0] - min_inputs) / (max_inputs - min_inputs)\n else:\n inputs = batch[0]\n if min_targets is not None and max_targets is not None:\n targets = (batch[1] - min_targets) / (max_targets - min_targets)\n else:\n targets = batch[1]\n\n with torch.set_grad_enabled(phase == 'train'):\n def closure():\n if torch.is_grad_enabled():\n optimizer.zero_grad()\n outputs = neural_network(inputs)\n loss = loss_function(outputs, targets)\n if loss.requires_grad:\n loss.backward()\n return loss\n\n # perform optimization step\n if phase == 'train':\n optimizer.step(closure)\n\n # compute loss of current batch\n loss = closure()\n\n # update overall absolute loss\n running_loss += loss.item() * len(batch[0])\n\n # compute average loss\n epoch_loss = running_loss / len(dataloaders[phase].dataset)\n\n losses[phase] = epoch_loss\n\n losses['full'] += running_loss\n\n if log_loss_frequency > 0 and epoch % log_loss_frequency == 0:\n logger.info(f'Epoch {epoch}: Current {phase} loss of {losses[phase]:.3e}')\n\n if 'lr_scheduler' in training_parameters and training_parameters['lr_scheduler']:\n lr_scheduler.step()\n\n # check for early stopping\n if phase == 'val' and es_scheduler(losses, neural_network):\n logger.info(f'Stopping training process early after {epoch + 1} epochs with validation loss '\n f'of {es_scheduler.best_losses[\"val\"]:.3e} ...')\n return es_scheduler.best_neural_network, es_scheduler.best_losses\n\n return es_scheduler.best_neural_network, es_scheduler.best_losses\n\n\ndef multiple_restarts_training(training_data, validation_data, neural_network,\n target_loss=None, max_restarts=10, log_loss_frequency=0,\n training_parameters={}, scaling_parameters={}, seed=None):\n \"\"\"Algorithm that performs multiple restarts of neural network training.\n\n This method either performs a predefined number of restarts and returns\n the best trained network or tries to reach a given target loss and\n stops training when the target loss is reached.\n\n See :func:`train_neural_network` for more information on the parameters.\n\n Parameters\n ----------\n training_data\n Data to use during the training phase.\n validation_data\n Data to use during the validation phase.\n neural_network\n The neural network to train (parameters will be reset after each\n restart).\n target_loss\n Loss to reach during training (if `None`, the network with the\n smallest loss is returned).\n max_restarts\n Maximum number of restarts to perform.\n log_loss_frequency\n Frequency of epochs in which to log the current validation and\n training loss. If `0`, no intermediate logging of losses is done.\n training_parameters\n Additional parameters for the training algorithm,\n see :func:`train_neural_network` for more information.\n scaling_parameters\n Additional parameters for scaling inputs respectively outputs,\n see :func:`train_neural_network` for more information.\n seed\n Seed to use for various functions in PyTorch. Using a fixed seed,\n it is possible to reproduce former results.\n\n Returns\n -------\n best_neural_network\n The best trained neural network.\n losses\n The corresponding losses.\n\n Raises\n ------\n NeuralNetworkTrainingFailed\n Raised if prescribed loss can not be reached within the given number\n of restarts.\n \"\"\"\n assert isinstance(training_parameters, dict)\n assert isinstance(max_restarts, int) and max_restarts > 0\n\n logger = getLogger('pymor.algorithms.neural_network.multiple_restarts_training')\n\n # if applicable, set a common seed for the PyTorch initialization\n # of weights and biases and further PyTorch methods for all training runs\n if seed:\n torch.manual_seed(seed)\n\n # in case no training data is provided, return a neural network\n # that always returns zeros independent of the input\n if len(training_data) == 0 or len(training_data[0]) == 0:\n for layers in neural_network.children():\n for layer in layers:\n torch.nn.init.zeros_(layer.weight)\n layer.bias.data.fill_(0.)\n return neural_network, {'full': None, 'train': None, 'val': None}\n\n if target_loss:\n logger.info(f'Performing up to {max_restarts} restart{\"s\" if max_restarts > 1 else \"\"} '\n f'to train a neural network with a loss below {target_loss:.3e} ...')\n else:\n logger.info(f'Performing up to {max_restarts} restart{\"s\" if max_restarts > 1 else \"\"} '\n 'to find the neural network with the lowest loss ...')\n\n with logger.block('Training neural network #0 ...'):\n best_neural_network, losses = train_neural_network(training_data, validation_data,\n neural_network, training_parameters,\n scaling_parameters, log_loss_frequency)\n\n # perform multiple restarts\n for run in range(1, max_restarts + 1):\n\n if target_loss and losses['full'] <= target_loss:\n logger.info(f'Finished training after {run - 1} restart{\"s\" if run - 1 != 1 else \"\"}, '\n f'found neural network with loss of {losses[\"full\"]:.3e} ...')\n return neural_network, losses\n\n with logger.block(f'Training neural network #{run} ...'):\n # reset parameters of layers to start training with a new and untrained network\n for layers in neural_network.children():\n for layer in layers:\n if hasattr(layer, 'reset_parameters'):\n layer.reset_parameters()\n # perform training\n current_nn, current_losses = train_neural_network(training_data, validation_data,\n neural_network, training_parameters,\n scaling_parameters, log_loss_frequency)\n\n if current_losses['full'] < losses['full']:\n logger.info(f'Found better neural network (loss of {current_losses[\"full\"]:.3e} '\n f'instead of {losses[\"full\"]:.3e}) ...')\n best_neural_network = current_nn\n losses = current_losses\n else:\n logger.info(f'Rejecting neural network with loss of {current_losses[\"full\"]:.3e} '\n f'(instead of {losses[\"full\"]:.3e}) ...')\n\n if target_loss:\n raise NeuralNetworkTrainingFailed(f'Could not find neural network with prescribed loss of '\n f'{target_loss:.3e} (best one found was {losses[\"full\"]:.3e})!')\n logger.info(f'Found neural network with error of {losses[\"full\"]:.3e} ...')\n return best_neural_network, losses\n" ]
[ [ "numpy.frombuffer" ], [ "scipy.linalg.svd", "numpy.sqrt", "scipy.special.erfinv", "scipy.linalg.eigh", "scipy.sparse.linalg.LinearOperator", "scipy.linalg.lu_factor", "numpy.array", "scipy.sparse.linalg.eigsh" ], [ "torch.max", "torch.Tensor", "numpy.linspace", "torch.manual_seed", "torch.min", "torch.utils.data.DataLoader", "numpy.random.shuffle", "torch.set_grad_enabled", "torch.nn.init.zeros_", "torch.is_grad_enabled", "torch.nn.MSELoss" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.12", "0.14", "0.15" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
seanandrews/DSHARP_CPDs
[ "40d8f02945e0d412c5c912b050d4a3d8c6dbbfa2", "40d8f02945e0d412c5c912b050d4a3d8c6dbbfa2", "40d8f02945e0d412c5c912b050d4a3d8c6dbbfa2", "40d8f02945e0d412c5c912b050d4a3d8c6dbbfa2", "40d8f02945e0d412c5c912b050d4a3d8c6dbbfa2", "40d8f02945e0d412c5c912b050d4a3d8c6dbbfa2" ]
[ "CPD_search/GWLup_gap0_imageloop.py", "CSD_modeling/dmrs1.py", "CSD_modeling/extract_arc.py", "CSD_modeling/data_symm_imaging.py", "CSD_modeling/resid_peaks.py", "CSD_modeling/recover_loop.py" ]
[ "import os, sys, time\nimport numpy as np\nexecfile('reduction_utils.py')\nexecfile('JvM_correction_brief.py')\nexecfile('ImportMS.py')\nsys.path.append('.')\nimport diskdictionary as disk\n\n# specify target disk and gap\ntarget = 'GWLup'\ngap_ix = 0\nsubsuf = '0'\n\n# load mock injection parameters file data (as strings)\ninj_file = target+'_gap'+str(gap_ix)+'_mpars.'+subsuf+'.txt'\nFstr, mstr, rstr, azstr = np.loadtxt(inj_file, dtype=str).T\n\n\n# loop through each set of residuals and make an image\nfor i in range(len(Fstr)):\n\n t0 = time.time()\n\n # create a MS from the residual visibilities\n rfile = 'resid_vis/' + target + '_gap' + str(gap_ix) + \\\n '_F' + Fstr[i] + 'uJy_' + mstr[i] + '_frank_uv_resid'\n resid_suffix = 'gap'+str(gap_ix)+'.F'+Fstr[i]+'uJy_'+mstr[i]+'.resid'\n os.system('rm -rf '+target+'_data.'+resid_suffix+'.ms*')\n ImportMS('data/'+target+'_data.ms', rfile, suffix=resid_suffix, \n make_resid=False)\n\n # clean image for the residual visibilities (note this is 1024x1024, not\n # the default 3000x3000 used for other imaging; done for speed/space)\n im_outfile = target+'_'+resid_suffix\n tclean_wrapper(vis='data/'+target+'_data.'+resid_suffix+'.ms',\n imagename=im_outfile,\n mask=disk.disk[target]['cmask'],\n scales=disk.disk[target]['cscales'],\n imsize=1024, cellsize='.003arcsec',\n threshold=disk.disk[target]['cthresh'],\n gain=disk.disk[target]['cgain'],\n cycleniter=disk.disk[target]['ccycleniter'],\n robust=disk.disk[target]['crobust'],\n uvtaper=disk.disk[target]['ctaper'])\n\n # perform the JvM correction\n eps = do_JvM_correction_and_get_epsilon(im_outfile)\n\n # export the resulting image to a FITS file\n exportfits(im_outfile+'.JvMcorr.image', \n 'resid_images/'+im_outfile+'.JvMcorr.fits', overwrite=True)\n \n # clean up\n for ext in ['.image', '.mask', '.model', '.pb', '.psf', '.residual', \n '.sumwt', '.JvMcorr.image']:\n os.system('rm -rf '+im_outfile+ext)\n os.system('rm -rf data/'+target+'_data.'+resid_suffix+'.ms*')\n\n print(time.time()-t0)\n", "import os, sys, time \nimport numpy as np \nfrom astropy.io import fits \nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom matplotlib.colorbar import Colorbar\nfrom matplotlib.patches import Ellipse\nfrom astropy.visualization import (AsinhStretch, ImageNormalize)\nfrom deproject_vis import deproject_vis\nsys.path.append('../')\nimport diskdictionary as disk\n\n# set color map\ncmap = 'inferno'\n\n# constants\nc_ = 2.99792e10\nk_ = 1.38057e-16\n\n# target-specific inputs\ntargets = ['SR4', 'RULup', 'Elias20', 'Sz129', 'HD143006']\nTbticks = [[0, 5, 10, 20, 30, 40, 50],\n [0, 5, 10, 20, 30, 50, 70],\n [0, 5, 10, 20, 30, 40, 50],\n [0, 5, 10, 20, 30],\n [0, 2, 4, 8, 12]]\n\n# plotting conventions\nrout = 0.40\nrs = 1.5 # plot image extent of +/- (rs * rout) for each target\ndmr = ['data', 'model', 'resid']\nplt.style.use('default')\nplt.rc('font', size=6)\nleft, right, bottom, top = 0.09, 0.92, 0.05, 0.99\nwspace, hspace = 0.03, 0.15\nfig = plt.figure(figsize=(3.5, 5.4))\ngs = gridspec.GridSpec(5, 4, width_ratios=(1, 1, 1, 0.08),\n height_ratios=(1, 1, 1, 1, 1))\n\n# target loop (index i)\nfor i in range(len(targets)):\n\n ### Prepare image plotting\n # parse header information into physical numbers\n if (targets[i] == 'HD143006'):\n dfile = 'data/deep_'+targets[i]+'_data_symm.JvMcorr.fits'\n else:\n dfile = 'data/deep_'+targets[i]+'_data.JvMcorr.fits'\n hd = fits.open(dfile)[0].header\n nx, ny = hd['NAXIS1'], hd['NAXIS2']\n RAo = 3600 * hd['CDELT1'] * (np.arange(nx) - (hd['CRPIX1'] - 1))\n DECo = 3600 * hd['CDELT2'] * (np.arange(ny) - (hd['CRPIX2'] - 1))\n dRA, dDEC = np.meshgrid(RAo - disk.disk[targets[i]]['dx'], \n DECo - disk.disk[targets[i]]['dy'])\n freq = hd['CRVAL3']\n\n # beam parameters \n bmaj, bmin, bPA = 3600 * hd['BMAJ'], 3600 * hd['BMIN'], hd['BPA']\n barea = (np.pi * bmaj * bmin / (4 * np.log(2))) / (3600 * 180 / np.pi)**2\n\n # image setups\n im_bounds = (dRA.max(), dRA.min(), dDEC.min(), dDEC.max())\n dRA_lims, dDEC_lims = [rs*rout, -rs*rout], [-rs*rout, rs*rout]\n\n # intensity limits, and stretch\n norm = ImageNormalize(vmin=0, vmax=disk.disk[targets[i]]['maxTb'], \n stretch=AsinhStretch())\n\n\n ### Loop through data, model, residual images\n for j in range(len(dmr)):\n # load image\n if (targets[i] == 'HD143006'):\n dfile = 'data/deep_'+targets[i]+'_'+dmr[j]+'_symm.JvMcorr.fits'\n else:\n dfile = 'data/deep_'+targets[i]+'_'+dmr[j]+'.JvMcorr.fits'\n hdu = fits.open(dfile)\n img = np.squeeze(hdu[0].data) \n\n # set location in figure\n ax = fig.add_subplot(gs[i,j])\n\n # plot the image (in brightness temperature units)\n Tb = (1e-23 * img / barea) * c_**2 / (2 * k_ * freq**2)\n im = ax.imshow(Tb, origin='lower', cmap=cmap, extent=im_bounds,\n norm=norm, aspect='equal')\n\n # clean beams\n beam = Ellipse((dRA_lims[0] + 0.1*np.diff(dRA_lims),\n dDEC_lims[0] + 0.1*np.diff(dDEC_lims)), \n bmaj, bmin, 90-bPA)\n beam.set_facecolor('w')\n ax.add_artist(beam)\n\n # limits and labeling\n if (j == 0):\n ax.text(dRA_lims[0] + 0.03*np.diff(dRA_lims), \n dDEC_lims[1] - 0.10*np.diff(dDEC_lims), \n disk.disk[targets[i]]['label'], color='w', fontsize=6)\n ax.set_xlim(dRA_lims)\n ax.set_ylim(dDEC_lims)\n ax.set_yticks([-0.5, 0.0, 0.5])\n if (i == 4) and (j == 0):\n ax.set_xlabel('RA offset ($^{\\prime\\prime}$)', labelpad=2)\n ax.set_ylabel('DEC offset ($^{\\prime\\prime}$)', labelpad=-3)\n ax.tick_params(axis='y', length=1.5)\n ax.tick_params(axis='x', length=2)\n else:\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n ax.axis('off')\n\n\n ### Colormap scalebar\n cbax = fig.add_subplot(gs[i,3])\n cbax.tick_params(axis='y', length=2)\n cb = Colorbar(ax=cbax, mappable=im, orientation='vertical',\n ticklocation='right', ticks=Tbticks[i])\n if (i == 4):\n cb.set_label('$T_b$ (K)', rotation=270, labelpad=6)\n\n\n# adjust full figure layout\nfig.subplots_adjust(wspace=wspace, hspace=hspace)\nfig.subplots_adjust(left=left, right=right, bottom=bottom, top=top)\nfig.savefig('../figs/dmrs1.pdf')\n", "import os\nimport numpy as np\nexecfile('ExportMS.py')\n\n# read which disk this is about\ntarget = str(np.loadtxt('whichdisk.txt', dtype='str'))\n\n# load FITS model of the arc (the modified CLEAN model)\nimportfits(fitsimage='data/'+target+'_data_arc.cleanmodel.fits',\n imagename='data/'+target+'_data_arc.cleanmodel', overwrite=True)\n\n# Fourier transform the arc model onto the same (u,v) tracks as in the data\n# MS (make a copy first!), and store them in the 'MODEL_DATA' column\nos.system('rm -rf data/'+target+'_data.ms*')\nos.system('cp -r data/'+target+'_continuum_spavg_tbin30s.ms data/temp_' + \\\n target+'.ms')\nft(vis='data/temp_'+target+'.ms', \n model='data/'+target+'_data_arc.model', usescratch=True)\n\n# Now subtract the FT of the arc model from the observed visibilities; the \n# result is stored in the 'CORRECTED_DATA' column\nuvsub(vis='data/temp_'+target+'.ms')\n\n# Split out the 'CORRECTED_DATA' visibilities into their own \"arc-less\" MS\nos.system('rm -rf data/'+target+'_data_symm.ms*')\nsplit(vis='data/temp_'+target+'.ms', outputvis='data/'+target+'_data_symm.ms', \n datacolumn='corrected')\n\n# Export the \"arc-less\" MS into npz format for frankenstein modeling\nExportMS('data/'+target+'_data_symm.ms')\n\n# Clean up\nos.system('rm -rf data/temp_'+target+'.ms*')\nos.system('rm -rf data/'+target+'_data_symm_spavg.ms*')\nos.system('mv data/'+target+'_data_symm_spavg.vis.npz ' + \\\n 'data/'+target+'_data_symm.vis.npz')\n", "import os, sys\nimport numpy as np\nexecfile('reduction_utils.py')\nexecfile('JvM_correction.py')\nexecfile('ImportMS.py')\nsys.path.append('../')\nimport diskdictionary as disk\n\n# read which disk this is about\ntarget = str(np.loadtxt('whichdisk.txt', dtype='str'))\n\n# Perform the imaging\nimagename = 'data/deep_'+target+'_data_symm'\nfor ext in ['.image', '.mask', '.model', '.pb', '.psf', '.residual', '.sumwt']:\n os.system('rm -rf '+imagename+ext)\ntclean(vis='data/'+target+'_data_symm.ms',\n imagename=imagename, specmode='mfs', deconvolver='multiscale',\n scales=disk.disk[target]['cscales'], mask=disk.disk[target]['cmask'], \n imsize=1024, cell='.006arcsec', gain=disk.disk[target]['cgain'],\n cycleniter=disk.disk[target]['ccycleniter'], cyclefactor=1, nterms=1,\n weighting='briggs', robust=disk.disk[target]['crobust'],\n uvtaper=disk.disk[target]['ctaper'],\n niter=50000, threshold=disk.disk[target]['gthresh'], savemodel='none')\n\n# Perform the JvM correction\neps = do_JvM_correction_and_get_epsilon(imagename)\n\n# Estimate map RMS as in DSHARP\ncoords = str.split(str.split(disk.disk[target]['cmask'], ']')[0], '[[')[1]\nnoise_ann = \"annulus[[%s], ['%.2farcsec', '4.25arcsec']]\" % \\\n (coords, 1.2 * disk.disk[target]['rout'])\nestimate_SNR(imagename+'.JvMcorr.image', \n disk_mask = disk.disk[target]['cmask'], noise_mask=noise_ann)\nprint('epsilon = ', eps)\n\n# Export FITS files of the original + JvM-corrected images\nexportfits(imagename+'.image', imagename+'.fits', overwrite=True)\nexportfits(imagename+'.JvMcorr.image', imagename+'.JvMcorr.fits', \n overwrite=True)\n", "import os, sys, time\nimport numpy as np\nfrom astropy.io import fits\nsys.path.append('../')\nimport diskdictionary as disk\n\n\ntargets = ['SR4', 'RULup', 'Elias20', 'Sz129', 'HD143006', 'GWLup',\n 'Elias24', 'HD163296', 'AS209']\n\ntargets = ['HD143006']\n\n\nfor i in range(len(targets)):\n\n # load residual images and headers\n if np.logical_or((targets[i] == 'HD143006'), (targets[i] == 'HD163296')):\n hdu = fits.open('data/'+targets[i]+'_resid_symm.JvMcorr.fits')\n else:\n hdu = fits.open('data/'+targets[i]+'_resid.JvMcorr.fits')\n img = 1e6 * np.squeeze(hdu[0].data) # in uJy/beam\n hd = hdu[0].header\n\n # Cartesian sky-plane coordinate system\n nx, ny = hd['NAXIS1'], hd['NAXIS2']\n RAo = 3600 * hd['CDELT1'] * (np.arange(nx) - (hd['CRPIX1'] - 1))\n DECo = 3600 * hd['CDELT2'] * (np.arange(ny) - (hd['CRPIX2'] - 1))\n x_s, y_s = np.meshgrid(RAo - disk.disk[targets[i]]['dx'],\n DECo - disk.disk[targets[i]]['dy'])\n\n # Cartesian disk-plane coordinate system\n inclr = np.radians(disk.disk[targets[i]]['incl'])\n PAr = np.radians(disk.disk[targets[i]]['PA'])\n x_d = (x_s * np.cos(PAr) - y_s * np.sin(PAr)) / np.cos(inclr)\n y_d = (x_s * np.sin(PAr) + y_s * np.cos(PAr))\n\n # Polar disk-plane coordinate system\n r_d = np.sqrt(x_d**2 + y_d**2)\n az_d = np.arctan2(y_d, x_d)\n\n\n # Loop through gaps\n rgap = disk.disk[targets[i]]['rgap']\n wgap = disk.disk[targets[i]]['wgap']\n for j in range(len(rgap)):\n\n # gap boundaries in Polar sky-plane coordinates\n bndi = (r_d <= (rgap[j] - wgap[j]))\n bndo = (r_d >= (rgap[j] + wgap[j]))\n\n # apply a boolean mask of gap annulus\n mask = np.ones_like(img, dtype='bool')\n mask[np.logical_or(bndi, bndo)] = 0\n gimg, gx_s, gy_s = img[mask], x_s[mask], y_s[mask]\n gr_d, gaz_d = r_d[mask], az_d[mask]\n\n # isolate peak\n peak = (gimg == gimg.max())\n pk_xs, pk_ys = gx_s[peak], gy_s[peak]\n pk_r, pk_az = gr_d[peak], gaz_d[peak]\n pk_SB = gimg.max()\n\n # print outputs for Table 4\n name_str = targets[i].ljust(8)\n r_str = str(np.int(np.round(1e3 * pk_r)))\n az_str = str(np.int(np.round(np.degrees(pk_az))))\n SB_str = str(np.int(np.round(pk_SB)))\n rms_str = str(np.int(np.round(np.ma.std(gimg))))\n noise_str = str(np.int(disk.disk[targets[i]]['RMS']))\n disk_mask = np.zeros_like(img, dtype='bool')\n disk_mask[(r_d <= (1.2*disk.disk[targets[i]]['rout']))] = 1\n dimg = img[disk_mask]\n noise_str = str(np.int(np.round(np.ma.std(dimg))))\n print(name_str + ' ' + 'gap'+str(j) + ' ' + r_str + ' ' + \\\n az_str + ' ' + SB_str + ' ' + rms_str + ' ' + noise_str)\n", "import os, sys, time\nimport numpy as np\nfrom astropy.io import fits\nsys.path.append('.')\nimport diskdictionary as disk\n\n# target disk/gap; iteration\ntarget = 'Elias24'\ngap = 0\nix = '0'\n\n# load the injection file data\ninj_file = target + '_gap' + str(gap) + '_mpars.' + ix + '.txt'\nFstr, mstr, rstr, azstr = np.loadtxt(inj_file, dtype=str).T\nFcpd, mdl, rcpd, azcpd = np.loadtxt(inj_file).T\n\n# bookkeeping\nrecov_file = target + '_gap' + str(gap) + '_recoveries.' + ix + '.txt'\nos.system('rm -rf ' + recov_file)\n\n\n# loop through injections\nfor i in range(len(Fstr)):\n\n # load the residual image, header\n im_file = target + '_gap' + str(gap) + '.' + Fstr[i] + 'uJy_' + mstr[i]\n hdu = fits.open('resid_images/' + im_file + '.resid.JvMcorr.fits')\n img = 1e6 * np.squeeze(hdu[0].data) # in microJy/beam\n hd = hdu[0].header\n hdu.close()\n\n # Cartesian sky-plane coordinate system\n nx, ny = hd['NAXIS1'], hd['NAXIS2']\n RAo = 3600 * hd['CDELT1'] * (np.arange(nx) - (hd['CRPIX1'] - 1))\n DECo = 3600 * hd['CDELT2'] * (np.arange(ny) - (hd['CRPIX2'] - 1))\n xs, ys = np.meshgrid(RAo - disk.disk[target]['dx'],\n DECo - disk.disk[target]['dy'])\n\n # Cartesian disk-plane coordinate system\n inclr = np.radians(disk.disk[target]['incl'])\n PAr = np.radians(disk.disk[target]['PA'])\n xd = (xs * np.cos(PAr) - ys * np.sin(PAr)) / np.cos(inclr)\n yd = (xs * np.sin(PAr) + ys * np.cos(PAr))\n\n # Polar disk-plane coordinate system\n rd = np.sqrt(xd**2 + yd**2)\n azd = np.arctan2(yd, xd)\n\n # Load gap properties\n rgap = disk.disk[target]['rgap'][gap]\n wgap = disk.disk[target]['wgap'][gap]\n \n # Apply a boolean mask to isolate the search annulus\n mask = np.ones_like(img, dtype='bool')\n bndi, bndo = (rd <= (rgap - wgap)), (rd >= (rgap + wgap))\n mask[np.logical_or(bndi, bndo)] = 0\n g_img, g_xs, g_ys = img[mask], xs[mask], ys[mask]\n g_rd, g_azd = rd[mask], azd[mask]\n\n # Locate and measure the peak\n peak = (g_img == g_img.max())\n pk_xs, pk_ys, pk_r, pk_az = g_xs[peak], g_ys[peak], g_rd[peak], g_azd[peak]\n pk_SB = g_img.max()\n\n # Record the injection / recovery outcomes\n with open(recov_file, 'a') as f:\n f.write('%.0f %.0f %s %.3f %.3f %4i %4i %.5f %.5f\\n' % \\\n (Fcpd[i], pk_SB, mstr[i], rcpd[i], pk_r, azcpd[i], pk_az,\n pk_xs, pk_ys))\n" ]
[ [ "numpy.loadtxt" ], [ "numpy.log", "numpy.arange", "numpy.squeeze", "matplotlib.pyplot.rc", "numpy.diff", "matplotlib.gridspec.GridSpec", "matplotlib.colorbar.Colorbar", "numpy.meshgrid", "matplotlib.pyplot.style.use", "matplotlib.pyplot.figure" ], [ "numpy.loadtxt" ], [ "numpy.loadtxt" ], [ "numpy.radians", "numpy.ones_like", "numpy.sqrt", "numpy.arange", "numpy.squeeze", "numpy.degrees", "numpy.ma.std", "numpy.cos", "numpy.sin", "numpy.logical_or", "numpy.arctan2", "numpy.int", "numpy.round", "numpy.zeros_like", "numpy.meshgrid" ], [ "numpy.radians", "numpy.ones_like", "numpy.sqrt", "numpy.arange", "numpy.squeeze", "numpy.cos", "numpy.sin", "numpy.arctan2", "numpy.logical_or", "numpy.meshgrid", "numpy.loadtxt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
SH-Tan/voxel-rangenet
[ "f2050cd30a8684fd09e561aba004adea978d3d35" ]
[ "pcdet/datasets/kitti/kitti_dataset.py" ]
[ "import copy\nimport pickle\n\nimport numpy as np\nfrom skimage import io\n\nfrom . import kitti_utils\nfrom ...ops.roiaware_pool3d import roiaware_pool3d_utils\nfrom ...utils import box_utils, calibration_kitti, common_utils, object3d_kitti\nfrom ..dataset import DatasetTemplate\nimport struct\n\n\nclass KittiDataset(DatasetTemplate):\n def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None):\n \"\"\"\n Args:\n root_path:\n dataset_cfg:\n class_names:\n training:\n logger:\n \"\"\"\n super().__init__(\n dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=root_path, logger=logger\n )\n self.split = self.dataset_cfg.DATA_SPLIT[self.mode]\n self.root_split_path = self.root_path / ('training' if self.split != 'test' else 'testing')\n\n split_dir = self.root_path / 'ImageSets' / (self.split + '.txt')\n self.sample_id_list = [x.strip() for x in open(split_dir).readlines()] if split_dir.exists() else None\n\n self.kitti_infos = []\n self.include_kitti_data(self.mode)\n\n def include_kitti_data(self, mode):\n if self.logger is not None:\n self.logger.info('Loading KITTI dataset')\n kitti_infos = []\n\n for info_path in self.dataset_cfg.INFO_PATH[mode]:\n info_path = self.root_path / info_path\n if not info_path.exists():\n continue\n with open(info_path, 'rb') as f:\n infos = pickle.load(f)\n kitti_infos.extend(infos)\n\n self.kitti_infos.extend(kitti_infos)\n\n if self.logger is not None:\n self.logger.info('Total samples for KITTI dataset: %d' % (len(kitti_infos)))\n\n def set_split(self, split):\n super().__init__(\n dataset_cfg=self.dataset_cfg, class_names=self.class_names, training=self.training, root_path=self.root_path, logger=self.logger\n )\n self.split = split\n self.root_split_path = self.root_path / ('training' if self.split != 'test' else 'testing')\n\n split_dir = self.root_path / 'ImageSets' / (self.split + '.txt')\n self.sample_id_list = [x.strip() for x in open(split_dir).readlines()] if split_dir.exists() else None\n\n def get_lidar(self, idx):\n lidar_file = self.root_split_path / 'velodyne' / ('%s.bin' % idx)\n assert lidar_file.exists()\n return np.fromfile(str(lidar_file), dtype=np.float32).reshape(-1, 4)\n\n def get_image(self, idx):\n \"\"\"\n Loads image for a sample\n Args:\n idx: int, Sample index\n Returns:\n image: (H, W, 3), RGB Image\n \"\"\"\n img_file = self.root_split_path / 'image_2' / ('%s.png' % idx)\n \n assert img_file.exists()\n image = io.imread(img_file)\n image = image.astype(np.float32)\n image /= 255.0\n return image\n\n def get_image_shape(self, idx):\n print(self.root_split_path / 'image_2' / ('%s.png' % idx))\n # input()\n img_file = self.root_split_path / 'image_2' / ('%s.png' % idx)\n # print(img_file.exists())\n assert img_file.exists()\n return np.array(io.imread(img_file).shape[:2], dtype=np.int32)\n\n def get_label(self, idx):\n label_file = self.root_split_path / 'label_2' / ('%s.txt' % idx)\n assert label_file.exists()\n return object3d_kitti.get_objects_from_label(label_file)\n\n def get_depth_map(self, idx):\n \"\"\"\n Loads depth map for a sample\n Args:\n idx: str, Sample index\n Returns:\n depth: (H, W), Depth map\n \"\"\"\n depth_file = self.root_split_path / 'depth_2' / ('%s.png' % idx)\n assert depth_file.exists()\n depth = io.imread(depth_file)\n depth = depth.astype(np.float32)\n depth /= 256.0\n return depth\n\n def get_calib(self, idx):\n calib_file = self.root_split_path / 'calib' / ('%s.txt' % idx)\n assert calib_file.exists()\n return calibration_kitti.Calibration(calib_file)\n\n def get_road_plane(self, idx):\n plane_file = self.root_split_path / 'planes' / ('%s.txt' % idx)\n if not plane_file.exists():\n return None\n\n with open(plane_file, 'r') as f:\n lines = f.readlines()\n lines = [float(i) for i in lines[3].split()]\n plane = np.asarray(lines)\n\n # Ensure normal is always facing up, this is in the rectified camera coordinate\n if plane[1] > 0:\n plane = -plane\n\n norm = np.linalg.norm(plane[0:3])\n plane = plane / norm\n return plane\n\n @staticmethod\n def get_fov_flag(pts_rect, img_shape, calib):\n \"\"\"\n Args:\n pts_rect:\n img_shape:\n calib:\n\n Returns:\n\n \"\"\"\n pts_img, pts_rect_depth = calib.rect_to_img(pts_rect)\n val_flag_1 = np.logical_and(pts_img[:, 0] >= 0, pts_img[:, 0] < img_shape[1])\n val_flag_2 = np.logical_and(pts_img[:, 1] >= 0, pts_img[:, 1] < img_shape[0])\n val_flag_merge = np.logical_and(val_flag_1, val_flag_2)\n pts_valid_flag = np.logical_and(val_flag_merge, pts_rect_depth >= 0)\n\n return pts_valid_flag\n\n def get_infos(self, num_workers=4, has_label=True, count_inside_pts=True, sample_id_list=None):\n import concurrent.futures as futures\n\n def process_single_scene(sample_idx):\n print('%s sample_idx: %s' % (self.split, sample_idx))\n info = {}\n pc_info = {'num_features': 4, 'lidar_idx': sample_idx}\n info['point_cloud'] = pc_info\n\n image_info = {'image_idx': sample_idx, 'image_shape': self.get_image_shape(sample_idx)}\n info['image'] = image_info\n calib = self.get_calib(sample_idx)\n\n P2 = np.concatenate([calib.P2, np.array([[0., 0., 0., 1.]])], axis=0)\n R0_4x4 = np.zeros([4, 4], dtype=calib.R0.dtype)\n R0_4x4[3, 3] = 1.\n R0_4x4[:3, :3] = calib.R0\n V2C_4x4 = np.concatenate([calib.V2C, np.array([[0., 0., 0., 1.]])], axis=0)\n calib_info = {'P2': P2, 'R0_rect': R0_4x4, 'Tr_velo_to_cam': V2C_4x4}\n\n info['calib'] = calib_info\n\n if has_label:\n obj_list = self.get_label(sample_idx)\n annotations = {}\n annotations['name'] = np.array([obj.cls_type for obj in obj_list])\n annotations['truncated'] = np.array([obj.truncation for obj in obj_list])\n annotations['occluded'] = np.array([obj.occlusion for obj in obj_list])\n annotations['alpha'] = np.array([obj.alpha for obj in obj_list])\n annotations['bbox'] = np.concatenate([obj.box2d.reshape(1, 4) for obj in obj_list], axis=0)\n annotations['dimensions'] = np.array([[obj.l, obj.h, obj.w] for obj in obj_list]) # lhw(camera) format\n annotations['location'] = np.concatenate([obj.loc.reshape(1, 3) for obj in obj_list], axis=0)\n annotations['rotation_y'] = np.array([obj.ry for obj in obj_list])\n annotations['score'] = np.array([obj.score for obj in obj_list])\n annotations['difficulty'] = np.array([obj.level for obj in obj_list], np.int32)\n\n num_objects = len([obj.cls_type for obj in obj_list if obj.cls_type != 'DontCare'])\n num_gt = len(annotations['name'])\n index = list(range(num_objects)) + [-1] * (num_gt - num_objects)\n annotations['index'] = np.array(index, dtype=np.int32)\n\n loc = annotations['location'][:num_objects]\n dims = annotations['dimensions'][:num_objects]\n rots = annotations['rotation_y'][:num_objects]\n loc_lidar = calib.rect_to_lidar(loc)\n l, h, w = dims[:, 0:1], dims[:, 1:2], dims[:, 2:3]\n loc_lidar[:, 2] += h[:, 0] / 2\n gt_boxes_lidar = np.concatenate([loc_lidar, l, w, h, -(np.pi / 2 + rots[..., np.newaxis])], axis=1)\n annotations['gt_boxes_lidar'] = gt_boxes_lidar\n\n info['annos'] = annotations\n\n if count_inside_pts:\n points = self.get_lidar(sample_idx)\n calib = self.get_calib(sample_idx)\n pts_rect = calib.lidar_to_rect(points[:, 0:3])\n\n fov_flag = self.get_fov_flag(pts_rect, info['image']['image_shape'], calib)\n pts_fov = points[fov_flag]\n corners_lidar = box_utils.boxes_to_corners_3d(gt_boxes_lidar)\n num_points_in_gt = -np.ones(num_gt, dtype=np.int32)\n\n for k in range(num_objects):\n flag = box_utils.in_hull(pts_fov[:, 0:3], corners_lidar[k])\n num_points_in_gt[k] = flag.sum()\n annotations['num_points_in_gt'] = num_points_in_gt\n\n return info\n\n sample_id_list = sample_id_list if sample_id_list is not None else self.sample_id_list\n with futures.ThreadPoolExecutor(num_workers) as executor:\n infos = executor.map(process_single_scene, sample_id_list)\n return list(infos)\n\n def create_groundtruth_database(self, info_path=None, used_classes=None, split='train'):\n import torch\n\n database_save_path = Path(self.root_path) / ('gt_database' if split == 'train' else ('gt_database_%s' % split))\n db_info_save_path = Path(self.root_path) / ('kitti_dbinfos_%s.pkl' % split)\n\n database_save_path.mkdir(parents=True, exist_ok=True)\n all_db_infos = {}\n\n with open(info_path, 'rb') as f:\n infos = pickle.load(f)\n\n for k in range(len(infos)):\n print('gt_database sample: %d/%d' % (k + 1, len(infos)))\n info = infos[k]\n sample_idx = info['point_cloud']['lidar_idx']\n points = self.get_lidar(sample_idx)\n annos = info['annos']\n names = annos['name']\n difficulty = annos['difficulty']\n bbox = annos['bbox']\n gt_boxes = annos['gt_boxes_lidar']\n\n num_obj = gt_boxes.shape[0]\n point_indices = roiaware_pool3d_utils.points_in_boxes_cpu(\n torch.from_numpy(points[:, 0:3]), torch.from_numpy(gt_boxes)\n ).numpy() # (nboxes, npoints)\n\n for i in range(num_obj):\n filename = '%s_%s_%d.bin' % (sample_idx, names[i], i)\n filepath = database_save_path / filename\n gt_points = points[point_indices[i] > 0]\n\n gt_points[:, :3] -= gt_boxes[i, :3]\n with open(filepath, 'w') as f:\n gt_points.tofile(f)\n\n if (used_classes is None) or names[i] in used_classes:\n db_path = str(filepath.relative_to(self.root_path)) # gt_database/xxxxx.bin\n db_info = {'name': names[i], 'path': db_path, 'image_idx': sample_idx, 'gt_idx': i,\n 'box3d_lidar': gt_boxes[i], 'num_points_in_gt': gt_points.shape[0],\n 'difficulty': difficulty[i], 'bbox': bbox[i], 'score': annos['score'][i]}\n if names[i] in all_db_infos:\n all_db_infos[names[i]].append(db_info)\n else:\n all_db_infos[names[i]] = [db_info]\n for k, v in all_db_infos.items():\n print('Database %s: %d' % (k, len(v)))\n\n with open(db_info_save_path, 'wb') as f:\n pickle.dump(all_db_infos, f)\n\n @staticmethod\n def generate_prediction_dicts(batch_dict, pred_dicts, class_names, output_path=None):\n \"\"\"\n Args:\n batch_dict:\n frame_id:\n pred_dicts: list of pred_dicts\n pred_boxes: (N, 7), Tensor\n pred_scores: (N), Tensor\n pred_labels: (N), Tensor\n class_names:\n output_path:\n\n Returns:\n\n \"\"\"\n def get_template_prediction(num_samples):\n ret_dict = {\n 'name': np.zeros(num_samples), 'truncated': np.zeros(num_samples),\n 'occluded': np.zeros(num_samples), 'alpha': np.zeros(num_samples),\n 'bbox': np.zeros([num_samples, 4]), 'dimensions': np.zeros([num_samples, 3]),\n 'location': np.zeros([num_samples, 3]), 'rotation_y': np.zeros(num_samples),\n 'score': np.zeros(num_samples), 'boxes_lidar': np.zeros([num_samples, 7])\n }\n return ret_dict\n\n def generate_single_sample_dict(batch_index, box_dict):\n pred_scores = box_dict['pred_scores'].cpu().numpy()\n pred_boxes = box_dict['pred_boxes'].cpu().numpy()\n pred_labels = box_dict['pred_labels'].cpu().numpy()\n pred_dict = get_template_prediction(pred_scores.shape[0])\n if pred_scores.shape[0] == 0:\n return pred_dict\n\n calib = batch_dict['calib'][batch_index]\n image_shape = batch_dict['image_shape'][batch_index].cpu().numpy()\n pred_boxes_camera = box_utils.boxes3d_lidar_to_kitti_camera(pred_boxes, calib)\n pred_boxes_img = box_utils.boxes3d_kitti_camera_to_imageboxes(\n pred_boxes_camera, calib, image_shape=image_shape\n )\n\n pred_dict['name'] = np.array(class_names)[pred_labels - 1]\n pred_dict['alpha'] = -np.arctan2(-pred_boxes[:, 1], pred_boxes[:, 0]) + pred_boxes_camera[:, 6]\n pred_dict['bbox'] = pred_boxes_img\n pred_dict['dimensions'] = pred_boxes_camera[:, 3:6]\n pred_dict['location'] = pred_boxes_camera[:, 0:3]\n pred_dict['rotation_y'] = pred_boxes_camera[:, 6]\n pred_dict['score'] = pred_scores\n pred_dict['boxes_lidar'] = pred_boxes\n\n return pred_dict\n\n annos = []\n for index, box_dict in enumerate(pred_dicts):\n frame_id = batch_dict['frame_id'][index]\n\n single_pred_dict = generate_single_sample_dict(index, box_dict)\n single_pred_dict['frame_id'] = frame_id\n annos.append(single_pred_dict)\n\n if output_path is not None:\n cur_det_file = output_path / ('%s.txt' % frame_id)\n with open(cur_det_file, 'w') as f:\n bbox = single_pred_dict['bbox']\n loc = single_pred_dict['location']\n dims = single_pred_dict['dimensions'] # lhw -> hwl\n\n for idx in range(len(bbox)):\n print('%s -1 -1 %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f'\n % (single_pred_dict['name'][idx], single_pred_dict['alpha'][idx],\n bbox[idx][0], bbox[idx][1], bbox[idx][2], bbox[idx][3],\n dims[idx][1], dims[idx][2], dims[idx][0], loc[idx][0],\n loc[idx][1], loc[idx][2], single_pred_dict['rotation_y'][idx],\n single_pred_dict['score'][idx]), file=f)\n\n return annos\n\n def evaluation(self, det_annos, class_names, **kwargs):\n if 'annos' not in self.kitti_infos[0].keys():\n return None, {}\n\n from .kitti_object_eval_python import eval as kitti_eval\n\n eval_det_annos = copy.deepcopy(det_annos)\n eval_gt_annos = [copy.deepcopy(info['annos']) for info in self.kitti_infos]\n ap_result_str, ap_dict = kitti_eval.get_official_eval_result(eval_gt_annos, eval_det_annos, class_names)\n\n return ap_result_str, ap_dict\n\n def __len__(self):\n if self._merge_all_iters_to_one_epoch:\n return len(self.kitti_infos) * self.total_epochs\n\n return len(self.kitti_infos)\n\n def __getitem__(self, index):\n # index = 4\n if self._merge_all_iters_to_one_epoch:\n index = index % len(self.kitti_infos)\n\n info = copy.deepcopy(self.kitti_infos[index])\n\n sample_idx = info['point_cloud']['lidar_idx']\n img_shape = info['image']['image_shape']\n calib = self.get_calib(sample_idx)\n get_item_list = self.dataset_cfg.get('GET_ITEM_LIST', ['points'])\n\n input_dict = {\n \n 'frame_id': sample_idx,\n 'calib': calib,\n }\n\n if 'annos' in info:\n annos = info['annos']\n annos = common_utils.drop_info_with_name(annos, name='DontCare')\n loc, dims, rots = annos['location'], annos['dimensions'], annos['rotation_y']\n gt_names = annos['name']\n gt_boxes_camera = np.concatenate([loc, dims, rots[..., np.newaxis]], axis=1).astype(np.float32)\n gt_boxes_lidar = box_utils.boxes3d_kitti_camera_to_lidar(gt_boxes_camera, calib)\n\n input_dict.update({\n 'gt_names': gt_names,\n 'gt_boxes': gt_boxes_lidar\n })\n if \"gt_boxes2d\" in get_item_list:\n input_dict['gt_boxes2d'] = annos[\"bbox\"]\n\n road_plane = self.get_road_plane(sample_idx)\n if road_plane is not None:\n input_dict['road_plane'] = road_plane\n\n if \"points\" in get_item_list:\n points = self.get_lidar(sample_idx)\n\n if self.dataset_cfg.FOV_POINTS_ONLY:\n pts_rect = calib.lidar_to_rect(points[:, 0:3])\n fov_flag = self.get_fov_flag(pts_rect, img_shape, calib)\n points = points[fov_flag]\n '''\n filename = str(sample_idx)+'.bin'\n binfile = open(filename, 'wb')\n binfile.write(points)\n binfile.close()\n input()\n '''\n # print(points.shape)\n input_dict['points'] = points\n\n if \"images\" in get_item_list:\n input_dict['images'] = self.get_image(sample_idx)\n\n if \"depth_maps\" in get_item_list:\n input_dict['depth_maps'] = self.get_depth_map(sample_idx)\n\n if \"calib_matricies\" in get_item_list:\n input_dict[\"trans_lidar_to_cam\"], input_dict[\"trans_cam_to_img\"] = kitti_utils.calib_to_matricies(calib)\n\n data_dict = self.prepare_data(data_dict=input_dict)\n\n data_dict['image_shape'] = img_shape\n return data_dict\n\n\ndef create_kitti_infos(dataset_cfg, class_names, data_path, save_path, workers=4):\n dataset = KittiDataset(dataset_cfg=dataset_cfg, class_names=class_names, root_path=data_path, training=False)\n train_split, val_split = 'train', 'val'\n\n train_filename = save_path / ('kitti_infos_%s.pkl' % train_split)\n val_filename = save_path / ('kitti_infos_%s.pkl' % val_split)\n trainval_filename = save_path / 'kitti_infos_trainval.pkl'\n test_filename = save_path / 'kitti_infos_test.pkl'\n\n print('---------------Start to generate data infos---------------')\n\n dataset.set_split(train_split)\n kitti_infos_train = dataset.get_infos(num_workers=workers, has_label=True, count_inside_pts=True)\n with open(train_filename, 'wb') as f:\n pickle.dump(kitti_infos_train, f)\n print('Kitti info train file is saved to %s' % train_filename)\n\n dataset.set_split(val_split)\n kitti_infos_val = dataset.get_infos(num_workers=workers, has_label=True, count_inside_pts=True)\n with open(val_filename, 'wb') as f:\n pickle.dump(kitti_infos_val, f)\n print('Kitti info val file is saved to %s' % val_filename)\n\n with open(trainval_filename, 'wb') as f:\n pickle.dump(kitti_infos_train + kitti_infos_val, f)\n print('Kitti info trainval file is saved to %s' % trainval_filename)\n\n dataset.set_split('test')\n kitti_infos_test = dataset.get_infos(num_workers=workers, has_label=False, count_inside_pts=False)\n with open(test_filename, 'wb') as f:\n pickle.dump(kitti_infos_test, f)\n print('Kitti info test file is saved to %s' % test_filename)\n\n print('---------------Start create groundtruth database for data augmentation---------------')\n dataset.set_split(train_split)\n dataset.create_groundtruth_database(train_filename, split=train_split)\n\n print('---------------Data preparation Done---------------')\n\n\nif __name__ == '__main__':\n import sys\n if sys.argv.__len__() > 1 and sys.argv[1] == 'create_kitti_infos':\n import yaml\n from pathlib import Path\n from easydict import EasyDict\n dataset_cfg = EasyDict(yaml.load(open(sys.argv[2]),Loader=yaml.FullLoader))\n ROOT_DIR = (Path(__file__).resolve().parent / '../../../').resolve()\n create_kitti_infos(\n dataset_cfg=dataset_cfg,\n class_names=['Car', 'Pedestrian', 'Cyclist'],\n data_path=ROOT_DIR / 'data' / 'kitti',\n save_path=ROOT_DIR / 'data' / 'kitti' \n )\n" ]
[ [ "numpy.logical_and", "numpy.asarray", "numpy.linalg.norm", "torch.from_numpy", "numpy.ones", "numpy.concatenate", "numpy.arctan2", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rickyHong/magenta-repl
[ "93ec9bca9796056af4e0bb6580cb64540d85a96c", "93ec9bca9796056af4e0bb6580cb64540d85a96c", "93ec9bca9796056af4e0bb6580cb64540d85a96c" ]
[ "magenta/music/melodies_lib.py", "magenta/scripts/convert_dir_to_note_sequences_test.py", "magenta/models/sketch_rnn/utils.py" ]
[ "# Copyright 2016 Google Inc. 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\"\"\"Utility functions for working with melodies.\n\nUse extract_melodies to extract monophonic melodies from a quantized\nNoteSequence proto.\n\nUse Melody.to_sequence to write a melody to a NoteSequence proto. Then use\nmidi_io.sequence_proto_to_midi_file to write that NoteSequence to a midi file.\n\"\"\"\n\n# internal imports\nimport numpy as np\nfrom six.moves import range # pylint: disable=redefined-builtin\n\nfrom magenta.music import constants\nfrom magenta.music import events_lib\nfrom magenta.music import midi_io\nfrom magenta.music import sequences_lib\nfrom magenta.pipelines import statistics\nfrom magenta.protobuf import music_pb2\n\n\nMELODY_NOTE_OFF = constants.MELODY_NOTE_OFF\nMELODY_NO_EVENT = constants.MELODY_NO_EVENT\nMIN_MELODY_EVENT = constants.MIN_MELODY_EVENT\nMAX_MELODY_EVENT = constants.MAX_MELODY_EVENT\nMIN_MIDI_PITCH = constants.MIN_MIDI_PITCH\nMAX_MIDI_PITCH = constants.MAX_MIDI_PITCH\nNOTES_PER_OCTAVE = constants.NOTES_PER_OCTAVE\nDEFAULT_STEPS_PER_BAR = constants.DEFAULT_STEPS_PER_BAR\nDEFAULT_STEPS_PER_QUARTER = constants.DEFAULT_STEPS_PER_QUARTER\nSTANDARD_PPQ = constants.STANDARD_PPQ\nNOTE_KEYS = constants.NOTE_KEYS\n\n\nclass PolyphonicMelodyException(Exception):\n pass\n\n\nclass BadNoteException(Exception):\n pass\n\n\nclass Melody(events_lib.SimpleEventSequence):\n \"\"\"Stores a quantized stream of monophonic melody events.\n\n Melody is an intermediate representation that all melody models can use.\n Quantized sequence to Melody code will do work to align notes and extract\n extract monophonic melodies. Model-specific code then needs to convert Melody\n to SequenceExample protos for TensorFlow.\n\n Melody implements an iterable object. Simply iterate to retrieve the melody\n events.\n\n Melody events are integers in range [-2, 127] (inclusive), where negative\n values are the special event events: MELODY_NOTE_OFF, and MELODY_NO_EVENT.\n Non-negative values [0, 127] are note-on events for that midi pitch. A note\n starts at a non-negative value (that is the pitch), and is held through\n subsequent MELODY_NO_EVENT events until either another non-negative value is\n reached (even if the pitch is the same as the previous note), or a\n MELODY_NOTE_OFF event is reached. A MELODY_NOTE_OFF starts at least one step\n of silence, which continues through MELODY_NO_EVENT events until the next\n non-negative value.\n\n MELODY_NO_EVENT values are treated as default filler. Notes must be inserted\n in ascending order by start time. Note end times will be truncated if the next\n note overlaps.\n\n Any sustained notes are implicitly turned off at the end of a melody.\n\n Melodies can start at any non-negative time, and are shifted left so that\n the bar containing the first note-on event is the first bar.\n\n Attributes:\n start_step: The offset of the first step of the melody relative to the\n beginning of the source sequence. Will always be the first step of a\n bar.\n end_step: The offset to the beginning of the bar following the last step\n of the melody relative the beginning of the source sequence. Will always\n be the first step of a bar.\n steps_per_quarter: Number of steps in in a quarter note.\n steps_per_bar: Number of steps in a bar (measure) of music.\n \"\"\"\n\n def __init__(self, events=None, **kwargs):\n \"\"\"Construct a Melody.\"\"\"\n if 'pad_event' in kwargs:\n del kwargs['pad_event']\n super(Melody, self).__init__(pad_event=MELODY_NO_EVENT,\n events=events, **kwargs)\n\n def _from_event_list(self, events, start_step=0,\n steps_per_bar=DEFAULT_STEPS_PER_BAR,\n steps_per_quarter=DEFAULT_STEPS_PER_QUARTER):\n \"\"\"Initializes with a list of event values and sets attributes.\n\n Args:\n events: List of Melody events to set melody to.\n start_step: The integer starting step offset.\n steps_per_bar: The number of steps in a bar.\n steps_per_quarter: The number of steps in a quarter note.\n\n Raises:\n ValueError: If `events` contains an event that is not in the proper range.\n \"\"\"\n for event in events:\n if not MIN_MELODY_EVENT <= event <= MAX_MELODY_EVENT:\n raise ValueError('Melody event out of range: %d' % event)\n super(Melody, self)._from_event_list(\n events, start_step=start_step, steps_per_bar=steps_per_bar,\n steps_per_quarter=steps_per_quarter)\n\n def _add_note(self, pitch, start_step, end_step):\n \"\"\"Adds the given note to the `events` list.\n\n `start_step` is set to the given pitch. `end_step` is set to NOTE_OFF.\n Everything after `start_step` in `events` is deleted before the note is\n added. `events`'s length will be changed so that the last event has index\n `end_step`.\n\n Args:\n pitch: Midi pitch. An integer between 0 and 127 inclusive.\n start_step: A non-negative integer step that the note begins on.\n end_step: An integer step that the note ends on. The note is considered to\n end at the onset of the end step. `end_step` must be greater than\n `start_step`.\n\n Raises:\n BadNoteException: If `start_step` does not precede `end_step`.\n \"\"\"\n if start_step >= end_step:\n raise BadNoteException(\n 'Start step does not precede end step: start=%d, end=%d' %\n (start_step, end_step))\n\n self.set_length(end_step + 1)\n\n self._events[start_step] = pitch\n self._events[end_step] = MELODY_NOTE_OFF\n for i in range(start_step + 1, end_step):\n self._events[i] = MELODY_NO_EVENT\n\n def _get_last_on_off_events(self):\n \"\"\"Returns indexes of the most recent pitch and NOTE_OFF events.\n\n Returns:\n A tuple (start_step, end_step) of the last note's on and off event\n indices.\n\n Raises:\n ValueError: If `events` contains no NOTE_OFF or pitch events.\n \"\"\"\n last_off = len(self)\n for i in range(len(self) - 1, -1, -1):\n if self._events[i] == MELODY_NOTE_OFF:\n last_off = i\n if self._events[i] >= MIN_MIDI_PITCH:\n return (i, last_off)\n raise ValueError('No events in the stream')\n\n def get_note_histogram(self):\n \"\"\"Gets a histogram of the note occurrences in a melody.\n\n Returns:\n A list of 12 ints, one for each note value (C at index 0 through B at\n index 11). Each int is the total number of times that note occurred in\n the melody.\n \"\"\"\n np_melody = np.array(self._events, dtype=int)\n return np.bincount(np_melody[np_melody >= MIN_MIDI_PITCH] %\n NOTES_PER_OCTAVE,\n minlength=NOTES_PER_OCTAVE)\n\n def get_major_key_histogram(self):\n \"\"\"Gets a histogram of the how many notes fit into each key.\n\n Returns:\n A list of 12 ints, one for each Major key (C Major at index 0 through\n B Major at index 11). Each int is the total number of notes that could\n fit into that key.\n \"\"\"\n note_histogram = self.get_note_histogram()\n key_histogram = np.zeros(NOTES_PER_OCTAVE)\n for note, count in enumerate(note_histogram):\n key_histogram[NOTE_KEYS[note]] += count\n return key_histogram\n\n def get_major_key(self):\n \"\"\"Finds the major key that this melody most likely belongs to.\n\n If multiple keys match equally, the key with the lowest index is returned,\n where the indexes of the keys are C Major = 0 through B Major = 11.\n\n Returns:\n An int for the most likely key (C Major = 0 through B Major = 11)\n \"\"\"\n key_histogram = self.get_major_key_histogram()\n return key_histogram.argmax()\n\n def append(self, event):\n \"\"\"Appends the event to the end of the melody and increments the end step.\n\n An implicit NOTE_OFF at the end of the melody will not be respected by this\n modification.\n\n Args:\n event: The integer Melody event to append to the end.\n Raises:\n ValueError: If `event` is not in the proper range.\n \"\"\"\n if not MIN_MELODY_EVENT <= event <= MAX_MELODY_EVENT:\n raise ValueError('Event out of range: %d' % event)\n super(Melody, self).append(event)\n\n def from_quantized_sequence(self,\n quantized_sequence,\n search_start_step=0,\n instrument=0,\n gap_bars=1,\n ignore_polyphonic_notes=False,\n pad_end=False,\n filter_drums=True):\n \"\"\"Populate self with a melody from the given quantized NoteSequence.\n\n A monophonic melody is extracted from the given `instrument` starting at\n `search_start_step`. `instrument` and `search_start_step` can be used to\n drive extraction of multiple melodies from the same quantized sequence. The\n end step of the extracted melody will be stored in `self._end_step`.\n\n 0 velocity notes are ignored. The melody extraction is ended when there are\n no held notes for a time stretch of `gap_bars` in bars (measures) of music.\n The number of time steps per bar is computed from the time signature in\n `quantized_sequence`.\n\n `ignore_polyphonic_notes` determines what happens when polyphonic (multiple\n notes start at the same time) data is encountered. If\n `ignore_polyphonic_notes` is true, the highest pitch is used in the melody\n when multiple notes start at the same time. If false, an exception is\n raised.\n\n Args:\n quantized_sequence: A NoteSequence quantized with\n sequences_lib.quantize_note_sequence.\n search_start_step: Start searching for a melody at this time step. Assumed\n to be the first step of a bar.\n instrument: Search for a melody in this instrument number.\n gap_bars: If this many bars or more follow a NOTE_OFF event, the melody\n is ended.\n ignore_polyphonic_notes: If True, the highest pitch is used in the melody\n when multiple notes start at the same time. If False,\n PolyphonicMelodyException will be raised if multiple notes start at\n the same time.\n pad_end: If True, the end of the melody will be padded with NO_EVENTs so\n that it will end at a bar boundary.\n filter_drums: If True, notes for which `is_drum` is True will be ignored.\n\n Raises:\n NonIntegerStepsPerBarException: If `quantized_sequence`'s bar length\n (derived from its time signature) is not an integer number of time\n steps.\n PolyphonicMelodyException: If any of the notes start on the same step\n and `ignore_polyphonic_notes` is False.\n \"\"\"\n sequences_lib.assert_is_relative_quantized_sequence(quantized_sequence)\n self._reset()\n\n steps_per_bar_float = sequences_lib.steps_per_bar_in_quantized_sequence(\n quantized_sequence)\n if steps_per_bar_float % 1 != 0:\n raise events_lib.NonIntegerStepsPerBarException(\n 'There are %f timesteps per bar. Time signature: %d/%d' %\n (steps_per_bar_float, quantized_sequence.time_signatures[0].numerator,\n quantized_sequence.time_signatures[0].denominator))\n self._steps_per_bar = steps_per_bar = int(steps_per_bar_float)\n self._steps_per_quarter = (\n quantized_sequence.quantization_info.steps_per_quarter)\n\n # Sort track by note start times, and secondarily by pitch descending.\n notes = sorted([n for n in quantized_sequence.notes\n if n.instrument == instrument and\n n.quantized_start_step >= search_start_step],\n key=lambda note: (note.quantized_start_step, -note.pitch))\n\n if not notes:\n return\n\n # The first step in the melody, beginning at the first step of a bar.\n melody_start_step = (\n notes[0].quantized_start_step -\n (notes[0].quantized_start_step - search_start_step) % steps_per_bar)\n for note in notes:\n if filter_drums and note.is_drum:\n continue\n\n # Ignore 0 velocity notes.\n if not note.velocity:\n continue\n\n start_index = note.quantized_start_step - melody_start_step\n end_index = note.quantized_end_step - melody_start_step\n\n if not self._events:\n # If there are no events, we don't need to check for polyphony.\n self._add_note(note.pitch, start_index, end_index)\n continue\n\n # If `start_index` comes before or lands on an already added note's start\n # step, we cannot add it. In that case either discard the melody or keep\n # the highest pitch.\n last_on, last_off = self._get_last_on_off_events()\n on_distance = start_index - last_on\n off_distance = start_index - last_off\n if on_distance == 0:\n if ignore_polyphonic_notes:\n # Keep highest note.\n # Notes are sorted by pitch descending, so if a note is already at\n # this position its the highest pitch.\n continue\n else:\n self._reset()\n raise PolyphonicMelodyException()\n elif on_distance < 0:\n raise PolyphonicMelodyException(\n 'Unexpected note. Not in ascending order.')\n\n # If a gap of `gap` or more steps is found, end the melody.\n if len(self) and off_distance >= gap_bars * steps_per_bar:\n break\n\n # Add the note-on and off events to the melody.\n self._add_note(note.pitch, start_index, end_index)\n\n if not self._events:\n # If no notes were added, don't set `_start_step` and `_end_step`.\n return\n\n self._start_step = melody_start_step\n\n # Strip final MELODY_NOTE_OFF event.\n if self._events[-1] == MELODY_NOTE_OFF:\n del self._events[-1]\n\n length = len(self)\n # Optionally round up `_end_step` to a multiple of `steps_per_bar`.\n if pad_end:\n length += -len(self) % steps_per_bar\n self.set_length(length)\n\n def to_sequence(self,\n velocity=100,\n instrument=0,\n program=0,\n sequence_start_time=0.0,\n qpm=120.0):\n \"\"\"Converts the Melody to NoteSequence proto.\n\n The end of the melody is treated as a NOTE_OFF event for any sustained\n notes.\n\n Args:\n velocity: Midi velocity to give each note. Between 1 and 127 (inclusive).\n instrument: Midi instrument to give each note.\n program: Midi program to give each note.\n sequence_start_time: A time in seconds (float) that the first note in the\n sequence will land on.\n qpm: Quarter notes per minute (float).\n\n Returns:\n A NoteSequence proto encoding the given melody.\n \"\"\"\n seconds_per_step = 60.0 / qpm / self.steps_per_quarter\n\n sequence = music_pb2.NoteSequence()\n sequence.tempos.add().qpm = qpm\n sequence.ticks_per_quarter = STANDARD_PPQ\n\n sequence_start_time += self.start_step * seconds_per_step\n current_sequence_note = None\n for step, note in enumerate(self):\n if MIN_MIDI_PITCH <= note <= MAX_MIDI_PITCH:\n # End any sustained notes.\n if current_sequence_note is not None:\n current_sequence_note.end_time = (\n step * seconds_per_step + sequence_start_time)\n\n # Add a note.\n current_sequence_note = sequence.notes.add()\n current_sequence_note.start_time = (\n step * seconds_per_step + sequence_start_time)\n current_sequence_note.pitch = note\n current_sequence_note.velocity = velocity\n current_sequence_note.instrument = instrument\n current_sequence_note.program = program\n\n elif note == MELODY_NOTE_OFF:\n # End any sustained notes.\n if current_sequence_note is not None:\n current_sequence_note.end_time = (\n step * seconds_per_step + sequence_start_time)\n current_sequence_note = None\n\n # End any sustained notes.\n if current_sequence_note is not None:\n current_sequence_note.end_time = (\n len(self) * seconds_per_step + sequence_start_time)\n\n if sequence.notes:\n sequence.total_time = sequence.notes[-1].end_time\n\n return sequence\n\n def transpose(self, transpose_amount, min_note=0, max_note=128):\n \"\"\"Transpose notes in this Melody.\n\n All notes are transposed the specified amount. Additionally, all notes\n are octave shifted to lie within the [min_note, max_note) range.\n\n Args:\n transpose_amount: The number of half steps to transpose this Melody.\n Positive values transpose up. Negative values transpose down.\n min_note: Minimum pitch (inclusive) that the resulting notes will take on.\n max_note: Maximum pitch (exclusive) that the resulting notes will take on.\n \"\"\"\n for i in range(len(self)):\n # Transpose MIDI pitches. Special events below MIN_MIDI_PITCH are not\n # changed.\n if self._events[i] >= MIN_MIDI_PITCH:\n self._events[i] += transpose_amount\n if self._events[i] < min_note:\n self._events[i] = (\n min_note + (self._events[i] - min_note) % NOTES_PER_OCTAVE)\n elif self._events[i] >= max_note:\n self._events[i] = (max_note - NOTES_PER_OCTAVE +\n (self._events[i] - max_note) % NOTES_PER_OCTAVE)\n\n def squash(self, min_note, max_note, transpose_to_key=None):\n \"\"\"Transpose and octave shift the notes in this Melody.\n\n The key center of this melody is computed with a heuristic, and the notes\n are transposed to be in the given key. The melody is also octave shifted\n to be centered in the given range. Additionally, all notes are octave\n shifted to lie within a given range.\n\n Args:\n min_note: Minimum pitch (inclusive) that the resulting notes will take on.\n max_note: Maximum pitch (exclusive) that the resulting notes will take on.\n transpose_to_key: The melody is transposed to be in this key or None if\n should not be transposed. 0 = C Major.\n\n Returns:\n How much notes are transposed by.\n \"\"\"\n if transpose_to_key is None:\n transpose_amount = 0\n else:\n melody_key = self.get_major_key()\n key_diff = transpose_to_key - melody_key\n midi_notes = [note for note in self._events\n if MIN_MIDI_PITCH <= note <= MAX_MIDI_PITCH]\n if not midi_notes:\n return 0\n melody_min_note = min(midi_notes)\n melody_max_note = max(midi_notes)\n melody_center = (melody_min_note + melody_max_note) / 2\n target_center = (min_note + max_note - 1) / 2\n center_diff = target_center - (melody_center + key_diff)\n transpose_amount = (\n key_diff +\n NOTES_PER_OCTAVE * int(round(center_diff / float(NOTES_PER_OCTAVE))))\n self.transpose(transpose_amount, min_note, max_note)\n\n return transpose_amount\n\n def set_length(self, steps, from_left=False):\n \"\"\"Sets the length of the melody to the specified number of steps.\n\n If the melody is not long enough, ends any sustained notes and adds NO_EVENT\n steps for padding. If it is too long, it will be truncated to the requested\n length.\n\n Args:\n steps: How many steps long the melody should be.\n from_left: Whether to add/remove from the left instead of right.\n \"\"\"\n old_len = len(self)\n super(Melody, self).set_length(steps, from_left=from_left)\n if steps > old_len and not from_left:\n # When extending the melody on the right, we end any sustained notes.\n for i in reversed(range(old_len)):\n if self._events[i] == MELODY_NOTE_OFF:\n break\n elif self._events[i] != MELODY_NO_EVENT:\n self._events[old_len] = MELODY_NOTE_OFF\n break\n\n def increase_resolution(self, k):\n \"\"\"Increase the resolution of a Melody.\n\n Increases the resolution of a Melody object by a factor of `k`. This uses\n MELODY_NO_EVENT to extend each event in the melody to be `k` steps long.\n\n Args:\n k: An integer, the factor by which to increase the resolution of the\n melody.\n \"\"\"\n super(Melody, self).increase_resolution(\n k, fill_event=MELODY_NO_EVENT)\n\n\ndef extract_melodies(quantized_sequence,\n search_start_step=0,\n min_bars=7,\n max_steps_truncate=None,\n max_steps_discard=None,\n gap_bars=1.0,\n min_unique_pitches=5,\n ignore_polyphonic_notes=True,\n pad_end=False,\n filter_drums=True):\n \"\"\"Extracts a list of melodies from the given quantized NoteSequence.\n\n This function will search through `quantized_sequence` for monophonic\n melodies in every track at every time step.\n\n Once a note-on event in a track is encountered, a melody begins.\n Gaps of silence in each track will be splitting points that divide the\n track into separate melodies. The minimum size of these gaps are given\n in `gap_bars`. The size of a bar (measure) of music in time steps is\n computed from the time signature stored in `quantized_sequence`.\n\n The melody is then checked for validity. The melody is only used if it is\n at least `min_bars` bars long, and has at least `min_unique_pitches` unique\n notes (preventing melodies that only repeat a few notes, such as those found\n in some accompaniment tracks, from being used).\n\n After scanning each instrument track in the quantized sequence, a list of all\n extracted Melody objects is returned.\n\n Args:\n quantized_sequence: A quantized NoteSequence.\n search_start_step: Start searching for a melody at this time step. Assumed\n to be the first step of a bar.\n min_bars: Minimum length of melodies in number of bars. Shorter melodies are\n discarded.\n max_steps_truncate: Maximum number of steps in extracted melodies. If\n defined, longer melodies are truncated to this threshold. If pad_end is\n also True, melodies will be truncated to the end of the last bar below\n this threshold.\n max_steps_discard: Maximum number of steps in extracted melodies. If\n defined, longer melodies are discarded.\n gap_bars: A melody comes to an end when this number of bars (measures) of\n silence is encountered.\n min_unique_pitches: Minimum number of unique notes with octave equivalence.\n Melodies with too few unique notes are discarded.\n ignore_polyphonic_notes: If True, melodies will be extracted from\n `quantized_sequence` tracks that contain polyphony (notes start at\n the same time). If False, tracks with polyphony will be ignored.\n pad_end: If True, the end of the melody will be padded with NO_EVENTs so\n that it will end at a bar boundary.\n filter_drums: If True, notes for which `is_drum` is True will be ignored.\n\n Returns:\n melodies: A python list of Melody instances.\n stats: A dictionary mapping string names to `statistics.Statistic` objects.\n\n Raises:\n NonIntegerStepsPerBarException: If `quantized_sequence`'s bar length\n (derived from its time signature) is not an integer number of time\n steps.\n \"\"\"\n sequences_lib.assert_is_relative_quantized_sequence(quantized_sequence)\n\n # TODO(danabo): Convert `ignore_polyphonic_notes` into a float which controls\n # the degree of polyphony that is acceptable.\n melodies = []\n stats = dict([(stat_name, statistics.Counter(stat_name)) for stat_name in\n ['polyphonic_tracks_discarded',\n 'melodies_discarded_too_short',\n 'melodies_discarded_too_few_pitches',\n 'melodies_discarded_too_long',\n 'melodies_truncated']])\n # Create a histogram measuring melody lengths (in bars not steps).\n # Capture melodies that are very small, in the range of the filter lower\n # bound `min_bars`, and large. The bucket intervals grow approximately\n # exponentially.\n stats['melody_lengths_in_bars'] = statistics.Histogram(\n 'melody_lengths_in_bars',\n [0, 1, 10, 20, 30, 40, 50, 100, 200, 500, min_bars // 2, min_bars,\n min_bars + 1, min_bars - 1])\n instruments = set([n.instrument for n in quantized_sequence.notes])\n steps_per_bar = int(\n sequences_lib.steps_per_bar_in_quantized_sequence(quantized_sequence))\n for instrument in instruments:\n instrument_search_start_step = search_start_step\n # Quantize the track into a Melody object.\n # If any notes start at the same time, only one is kept.\n while 1:\n melody = Melody()\n try:\n melody.from_quantized_sequence(\n quantized_sequence,\n instrument=instrument,\n search_start_step=instrument_search_start_step,\n gap_bars=gap_bars,\n ignore_polyphonic_notes=ignore_polyphonic_notes,\n pad_end=pad_end,\n filter_drums=filter_drums)\n except PolyphonicMelodyException:\n stats['polyphonic_tracks_discarded'].increment()\n break # Look for monophonic melodies in other tracks.\n except events_lib.NonIntegerStepsPerBarException:\n raise\n # Start search for next melody on next bar boundary (inclusive).\n instrument_search_start_step = (\n melody.end_step +\n (search_start_step - melody.end_step) % steps_per_bar)\n if not melody:\n break\n\n # Require a certain melody length.\n if len(melody) - 1 < melody.steps_per_bar * min_bars:\n stats['melodies_discarded_too_short'].increment()\n continue\n\n # Discard melodies that are too long.\n if max_steps_discard is not None and len(melody) > max_steps_discard:\n stats['melodies_discarded_too_long'].increment()\n continue\n\n # Truncate melodies that are too long.\n if max_steps_truncate is not None and len(melody) > max_steps_truncate:\n truncated_length = max_steps_truncate\n if pad_end:\n truncated_length -= max_steps_truncate % melody.steps_per_bar\n melody.set_length(truncated_length)\n stats['melodies_truncated'].increment()\n\n # Require a certain number of unique pitches.\n note_histogram = melody.get_note_histogram()\n unique_pitches = np.count_nonzero(note_histogram)\n if unique_pitches < min_unique_pitches:\n stats['melodies_discarded_too_few_pitches'].increment()\n continue\n\n # TODO(danabo)\n # Add filter for rhythmic diversity.\n\n stats['melody_lengths_in_bars'].increment(\n len(melody) // melody.steps_per_bar)\n\n melodies.append(melody)\n\n return melodies, stats.values()\n\n\ndef midi_file_to_melody(midi_file, steps_per_quarter=4, qpm=None,\n ignore_polyphonic_notes=True):\n \"\"\"Loads a melody from a MIDI file.\n\n Args:\n midi_file: Absolute path to MIDI file.\n steps_per_quarter: Quantization of Melody. For example, 4 = 16th notes.\n qpm: Tempo in quarters per a minute. If not set, tries to use the first\n tempo of the midi track and defaults to\n magenta.music.DEFAULT_QUARTERS_PER_MINUTE if fails.\n ignore_polyphonic_notes: Only use the highest simultaneous note if True.\n\n Returns:\n A Melody object extracted from the MIDI file.\n \"\"\"\n sequence = midi_io.midi_file_to_sequence_proto(midi_file)\n if qpm is None:\n if sequence.tempos:\n qpm = sequence.tempos[0].qpm\n else:\n qpm = constants.DEFAULT_QUARTERS_PER_MINUTE\n quantized_sequence = sequences_lib.quantize_note_sequence(\n sequence, steps_per_quarter=steps_per_quarter)\n melody = Melody()\n melody.from_quantized_sequence(\n quantized_sequence, ignore_polyphonic_notes=ignore_polyphonic_notes)\n return melody\n", "# Copyright 2016 Google Inc. 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\"\"\"Tests for converting a directory of MIDIs to a NoteSequence TFRecord file.\"\"\"\n\nimport os\nimport tempfile\n\n# internal imports\nimport tensorflow as tf\n\nfrom magenta.music import note_sequence_io\nfrom magenta.scripts import convert_dir_to_note_sequences\n\n\nclass ConvertMidiDirToSequencesTest(tf.test.TestCase):\n\n def setUp(self):\n midi_filename = os.path.join(tf.resource_loader.get_data_files_path(),\n '../testdata/example.mid')\n\n root_dir = tempfile.mkdtemp(dir=self.get_temp_dir())\n sub_1_dir = os.path.join(root_dir, 'sub_1')\n sub_2_dir = os.path.join(root_dir, 'sub_2')\n sub_1_sub_dir = os.path.join(sub_1_dir, 'sub')\n\n tf.gfile.MkDir(sub_1_dir)\n tf.gfile.MkDir(sub_2_dir)\n tf.gfile.MkDir(sub_1_sub_dir)\n\n tf.gfile.Copy(midi_filename, os.path.join(root_dir, 'midi_1.mid'))\n tf.gfile.Copy(midi_filename, os.path.join(root_dir, 'midi_2.mid'))\n tf.gfile.Copy(midi_filename, os.path.join(sub_1_dir, 'midi_3.mid'))\n tf.gfile.Copy(midi_filename, os.path.join(sub_2_dir, 'midi_3.mid'))\n tf.gfile.Copy(midi_filename, os.path.join(sub_2_dir, 'midi_4.mid'))\n tf.gfile.Copy(midi_filename, os.path.join(sub_1_sub_dir, 'midi_5.mid'))\n\n tf.gfile.FastGFile(\n os.path.join(root_dir, 'non_midi_file'),\n mode='w').write('non-midi data')\n\n self.expected_sub_dirs = {\n '': {'sub_1', 'sub_2', 'sub_1/sub'},\n 'sub_1': {'sub'},\n 'sub_1/sub': set(),\n 'sub_2': set()\n }\n self.expected_dir_midi_contents = {\n '': {'midi_1.mid', 'midi_2.mid'},\n 'sub_1': {'midi_3.mid'},\n 'sub_2': {'midi_3.mid', 'midi_4.mid'},\n 'sub_1/sub': {'midi_5.mid'}\n }\n self.root_dir = root_dir\n\n def runTest(self, relative_root, recursive):\n \"\"\"Tests the output for the given parameters.\"\"\"\n root_dir = os.path.join(self.root_dir, relative_root)\n expected_filenames = self.expected_dir_midi_contents[relative_root]\n if recursive:\n for sub_dir in self.expected_sub_dirs[relative_root]:\n for filename in self.expected_dir_midi_contents[\n os.path.join(relative_root, sub_dir)]:\n expected_filenames.add(os.path.join(sub_dir, filename))\n\n with tempfile.NamedTemporaryFile(\n prefix='ConvertMidiDirToSequencesTest') as output_file:\n convert_dir_to_note_sequences.convert_directory(\n root_dir, output_file.name, 1, recursive)\n actual_filenames = set()\n for sequence in note_sequence_io.note_sequence_record_iterator(\n output_file.name):\n self.assertEquals(\n note_sequence_io.generate_note_sequence_id(\n sequence.filename, os.path.basename(relative_root), 'midi'),\n sequence.id)\n self.assertEquals(os.path.basename(root_dir), sequence.collection_name)\n self.assertNotEquals(0, len(sequence.notes))\n actual_filenames.add(sequence.filename)\n\n self.assertEquals(expected_filenames, actual_filenames)\n\n def testConvertMidiDirToSequences_NoRecurse(self):\n self.runTest('', recursive=False)\n self.runTest('sub_1', recursive=False)\n self.runTest('sub_1/sub', recursive=False)\n self.runTest('sub_2', recursive=False)\n\n def testConvertMidiDirToSequences_Recurse(self):\n self.runTest('', recursive=True)\n self.runTest('sub_1', recursive=True)\n self.runTest('sub_1/sub', recursive=True)\n self.runTest('sub_2', recursive=True)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2017 Google Inc. 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\"\"\"SketchRNN data loading and image manipulation utilities.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport random\nimport numpy as np\n\n\ndef get_bounds(data, factor=10):\n \"\"\"Return bounds of data.\"\"\"\n min_x = 0\n max_x = 0\n min_y = 0\n max_y = 0\n\n abs_x = 0\n abs_y = 0\n for i in range(len(data)):\n x = float(data[i, 0]) / factor\n y = float(data[i, 1]) / factor\n abs_x += x\n abs_y += y\n min_x = min(min_x, abs_x)\n min_y = min(min_y, abs_y)\n max_x = max(max_x, abs_x)\n max_y = max(max_y, abs_y)\n\n return (min_x, max_x, min_y, max_y)\n\n\ndef slerp(p0, p1, t):\n \"\"\"Spherical interpolation.\"\"\"\n omega = np.arccos(np.dot(p0 / np.linalg.norm(p0), p1 / np.linalg.norm(p1)))\n so = np.sin(omega)\n return np.sin((1.0 - t) * omega) / so * p0 + np.sin(t * omega) / so * p1\n\n\ndef lerp(p0, p1, t):\n \"\"\"Linear interpolation.\"\"\"\n return (1.0 - t) * p0 + t * p1\n\n\n# A note on formats:\n# Sketches are encoded as a sequence of strokes. stroke-3 and stroke-5 are\n# different stroke encodings.\n# stroke-3 uses 3-tuples, consisting of x-offset, y-offset, and a binary\n# variable which is 1 if the pen is lifted between this position and\n# the next, and 0 otherwise.\n# stroke-5 consists of x-offset, y-offset, and p_1, p_2, p_3, a binary\n# one-hot vector of 3 possible pen states: pen down, pen up, end of sketch.\n# See section 3.1 of https://arxiv.org/abs/1704.03477 for more detail.\n# Sketch-RNN takes input in stroke-5 format, with sketches padded to a common\n# maximum length and prefixed by the special start token [0, 0, 1, 0, 0]\n# The QuickDraw dataset is stored using stroke-3.\ndef strokes_to_lines(strokes):\n \"\"\"Convert stroke-3 format to polyline format.\"\"\"\n x = 0\n y = 0\n lines = []\n line = []\n for i in range(len(strokes)):\n if strokes[i, 2] == 1:\n x += float(strokes[i, 0])\n y += float(strokes[i, 1])\n line.append([x, y])\n lines.append(line)\n line = []\n else:\n x += float(strokes[i, 0])\n y += float(strokes[i, 1])\n line.append([x, y])\n return lines\n\n\ndef lines_to_strokes(lines):\n \"\"\"Convert polyline format to stroke-3 format.\"\"\"\n eos = 0\n strokes = [[0, 0, 0]]\n for line in lines:\n linelen = len(line)\n for i in range(linelen):\n eos = 0 if i < linelen - 1 else 1\n strokes.append([line[i][0], line[i][1], eos])\n strokes = np.array(strokes)\n strokes[1:, 0:2] -= strokes[:-1, 0:2]\n return strokes[1:, :]\n\n\ndef augment_strokes(strokes, prob=0.0):\n \"\"\"Perform data augmentation by randomly dropping out strokes.\"\"\"\n # drop each point within a line segments with a probability of prob\n # note that the logic in the loop prevents points at the ends to be dropped.\n result = []\n prev_stroke = [0, 0, 1]\n count = 0\n stroke = [0, 0, 1] # Added to be safe.\n for i in range(len(strokes)):\n candidate = [strokes[i][0], strokes[i][1], strokes[i][2]]\n if candidate[2] == 1 or prev_stroke[2] == 1:\n count = 0\n else:\n count += 1\n urnd = np.random.rand() # uniform random variable\n if candidate[2] == 0 and prev_stroke[2] == 0 and count > 2 and urnd < prob:\n stroke[0] += candidate[0]\n stroke[1] += candidate[1]\n else:\n stroke = candidate\n prev_stroke = stroke\n result.append(stroke)\n return np.array(result)\n\n\ndef scale_bound(stroke, average_dimension=10.0):\n \"\"\"Scale an entire image to be less than a certain size.\"\"\"\n # stroke is a numpy array of [dx, dy, pstate], average_dimension is a float.\n # modifies stroke directly.\n bounds = get_bounds(stroke, 1)\n max_dimension = max(bounds[1] - bounds[0], bounds[3] - bounds[2])\n stroke[:, 0:2] /= (max_dimension / average_dimension)\n\n\ndef to_normal_strokes(big_stroke):\n \"\"\"Convert from stroke-5 format (from sketch-rnn paper) back to stroke-3.\"\"\"\n l = 0\n for i in range(len(big_stroke)):\n if big_stroke[i, 4] > 0:\n l = i\n break\n if l == 0:\n l = len(big_stroke)\n result = np.zeros((l, 3))\n result[:, 0:2] = big_stroke[0:l, 0:2]\n result[:, 2] = big_stroke[0:l, 3]\n return result\n\n\ndef clean_strokes(sample_strokes, factor=100):\n \"\"\"Cut irrelevant end points, scale to pixel space and store as integer.\"\"\"\n # Useful function for exporting data to .json format.\n copy_stroke = []\n added_final = False\n for j in range(len(sample_strokes)):\n finish_flag = int(sample_strokes[j][4])\n if finish_flag == 0:\n copy_stroke.append([\n int(round(sample_strokes[j][0] * factor)),\n int(round(sample_strokes[j][1] * factor)),\n int(sample_strokes[j][2]),\n int(sample_strokes[j][3]), finish_flag\n ])\n else:\n copy_stroke.append([0, 0, 0, 0, 1])\n added_final = True\n break\n if not added_final:\n copy_stroke.append([0, 0, 0, 0, 1])\n return copy_stroke\n\n\ndef to_big_strokes(stroke, max_len=250):\n \"\"\"Converts from stroke-3 to stroke-5 format and pads to given length. (But\n does not insert special start token.)\"\"\"\n result = np.zeros((max_len, 5), dtype=float)\n l = len(stroke)\n assert l <= max_len\n result[0:l, 0:2] = stroke[:, 0:2]\n result[0:l, 3] = stroke[:, 2]\n result[0:l, 2] = 1 - result[0:l, 3]\n result[l:, 4] = 1\n return result\n\n\ndef get_max_len(strokes):\n \"\"\"Return the maximum length of an array of strokes.\"\"\"\n max_len = 0\n for stroke in strokes:\n ml = len(stroke)\n if ml > max_len:\n max_len = ml\n return max_len\n\n\nclass DataLoader(object):\n \"\"\"Class for loading data.\"\"\"\n\n def __init__(self,\n strokes,\n batch_size=100,\n max_seq_length=250,\n scale_factor=1.0,\n random_scale_factor=0.0,\n augment_stroke_prob=0.0,\n limit=1000):\n self.batch_size = batch_size # minibatch size\n self.max_seq_length = max_seq_length # N_max in sketch-rnn paper\n self.scale_factor = scale_factor # divide offsets by this factor\n self.random_scale_factor = random_scale_factor # data augmentation method\n # Removes large gaps in the data. x and y offsets are clamped to have\n # absolute value no greater than this limit.\n self.limit = limit\n self.augment_stroke_prob = augment_stroke_prob # data augmentation method\n self.start_stroke_token = [0, 0, 1, 0, 0] # S_0 in sketch-rnn paper\n # sets self.strokes (list of ndarrays, one per sketch, in stroke-3 format,\n # sorted by size)\n self.preprocess(strokes)\n\n def preprocess(self, strokes):\n \"\"\"Remove entries from strokes having > max_seq_length points.\"\"\"\n raw_data = []\n seq_len = []\n count_data = 0\n\n for i in range(len(strokes)):\n data = strokes[i]\n if len(data) <= (self.max_seq_length):\n count_data += 1\n # removes large gaps from the data\n data = np.minimum(data, self.limit)\n data = np.maximum(data, -self.limit)\n data = np.array(data, dtype=np.float32)\n data[:, 0:2] /= self.scale_factor\n raw_data.append(data)\n seq_len.append(len(data))\n seq_len = np.array(seq_len) # nstrokes for each sketch\n idx = np.argsort(seq_len)\n self.strokes = []\n for i in range(len(seq_len)):\n self.strokes.append(raw_data[idx[i]])\n print(\"total images <= max_seq_len is %d\" % count_data)\n self.num_batches = int(count_data / self.batch_size)\n\n def random_sample(self):\n \"\"\"Return a random sample, in stroke-3 format as used by draw_strokes.\"\"\"\n sample = np.copy(random.choice(self.strokes))\n return sample\n\n def random_scale(self, data):\n \"\"\"Augment data by stretching x and y axis randomly [1-e, 1+e].\"\"\"\n x_scale_factor = (\n np.random.random() - 0.5) * 2 * self.random_scale_factor + 1.0\n y_scale_factor = (\n np.random.random() - 0.5) * 2 * self.random_scale_factor + 1.0\n result = np.copy(data)\n result[:, 0] *= x_scale_factor\n result[:, 1] *= y_scale_factor\n return result\n\n def calculate_normalizing_scale_factor(self):\n \"\"\"Calculate the normalizing factor explained in appendix of sketch-rnn.\"\"\"\n data = []\n for i in range(len(self.strokes)):\n if len(self.strokes[i]) > self.max_seq_length:\n continue\n for j in range(len(self.strokes[i])):\n data.append(self.strokes[i][j, 0])\n data.append(self.strokes[i][j, 1])\n data = np.array(data)\n return np.std(data)\n\n def normalize(self, scale_factor=None):\n \"\"\"Normalize entire dataset (delta_x, delta_y) by the scaling factor.\"\"\"\n if scale_factor is None:\n scale_factor = self.calculate_normalizing_scale_factor()\n self.scale_factor = scale_factor\n for i in range(len(self.strokes)):\n self.strokes[i][:, 0:2] /= self.scale_factor\n\n def _get_batch_from_indices(self, indices):\n \"\"\"Given a list of indices, return the potentially augmented batch.\"\"\"\n x_batch = []\n seq_len = []\n for idx in range(len(indices)):\n i = indices[idx]\n data = self.random_scale(self.strokes[i])\n data_copy = np.copy(data)\n if self.augment_stroke_prob > 0:\n data_copy = augment_strokes(data_copy, self.augment_stroke_prob)\n x_batch.append(data_copy)\n length = len(data_copy)\n seq_len.append(length)\n seq_len = np.array(seq_len, dtype=int)\n # We return three things: stroke-3 format, stroke-5 format, list of seq_len.\n return x_batch, self.pad_batch(x_batch, self.max_seq_length), seq_len\n\n def random_batch(self):\n \"\"\"Return a randomised portion of the training data.\"\"\"\n idx = np.random.permutation(range(0, len(self.strokes)))[0:self.batch_size]\n return self._get_batch_from_indices(idx)\n\n def get_batch(self, idx):\n \"\"\"Get the idx'th batch from the dataset.\"\"\"\n assert idx >= 0, \"idx must be non negative\"\n assert idx < self.num_batches, \"idx must be less than the number of batches\"\n start_idx = idx * self.batch_size\n indices = range(start_idx, start_idx + self.batch_size)\n return self._get_batch_from_indices(indices)\n\n def pad_batch(self, batch, max_len):\n \"\"\"Pad the batch to be stroke-5 bigger format as described in paper.\"\"\"\n result = np.zeros((self.batch_size, max_len + 1, 5), dtype=float)\n assert len(batch) == self.batch_size\n for i in range(self.batch_size):\n l = len(batch[i])\n assert l <= max_len\n result[i, 0:l, 0:2] = batch[i][:, 0:2]\n result[i, 0:l, 3] = batch[i][:, 2]\n result[i, 0:l, 2] = 1 - result[i, 0:l, 3]\n result[i, l:, 4] = 1\n # put in the first token, as described in sketch-rnn methodology\n result[i, 1:, :] = result[i, :-1, :]\n result[i, 0, :] = 0\n result[i, 0, 2] = self.start_stroke_token[2] # setting S_0 from paper.\n result[i, 0, 3] = self.start_stroke_token[3]\n result[i, 0, 4] = self.start_stroke_token[4]\n return result\n" ]
[ [ "numpy.array", "numpy.zeros", "numpy.bincount", "numpy.count_nonzero" ], [ "tensorflow.resource_loader.get_data_files_path", "tensorflow.gfile.MkDir", "tensorflow.test.main" ], [ "numpy.minimum", "numpy.maximum", "numpy.random.random", "numpy.linalg.norm", "numpy.sin", "numpy.copy", "numpy.std", "numpy.random.rand", "numpy.argsort", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Anfauglith/iop-sim
[ "3726385fd08ef25b51f98f0eae47038a07468977" ]
[ "sim.py" ]
[ "#!/usr/bin/python3\n\nimport os\nimport numpy as np\nfrom scipy import integrate\nimport matplotlib.pyplot as plt\n\n\n############\n# MAIN\n############\n\n# File System Setup\nmainpath= \"./newtesting/\"\nsubfolder = \"funny/\"\nfullpath = mainpath+subfolder\nos.makedirs(fullpath, exist_ok=True)\n\n\n# Basic Parameters\n\nwindowLength = 2016\nsimLength = windowLength*40\nnLic = 230\nfactor = 2\ncap = int(windowLength/nLic) * factor\n\n\n# Make Arrays for hashPower\nhashPower = np.empty(nLic)\n\n# Define Function for hash power distribution\ndef myFunny(x):\n #return np.exp(-x/48)*(1+0.5*np.cos(100/(x+1)))\n return np.exp(-x/48)\n\n# Generate HashPower distribution\nfor i in range(0, nLic):\n hashPower[i] = myFunny(i)\nhashPower = np.sort(hashPower) # from small to large\ncumulPower = np.cumsum(hashPower)\nhashPower = hashPower / cumulPower[-1] # normalize hashingPower\ncumulPower = cumulPower / cumulPower[-1] # to total HashPower = 1.0\n\n# This cumulPower array gives every Miner a certain interval inside of [0,1]\n# that 'belongs' to that miner in the sense that if we generate a random\n# number in [0,1), it will fall into that interval with a probability \n# equal to that miner's contribution to the total hashrate. \n\n# Plot Distribution for reference\nplt.bar(range(1, nLic+1),hashPower)\n#plt.axis([0, nLic+1, 0, 2])\nplt.savefig(mainpath + subfolder + \"figure_0.png\", dpi=600)\nplt.clf()\n\n# Helper function\ndef FirstLarger(l, n):\n i = 0\n while l[i]<=n:\n i+=1\n return i\n \n# Algorithms for Adding Coins.\n# First basic Cap\ndef AddCoin_BasicCap(i, coinsinwindow, totalcoins, blocktimes, whoMinedBlock, difficulty):\n # Reset the Cap at start of windowLength\n if i%windowLength==0:\n coinsinwindow.fill(0)\n if i == 0:\n difficulty[0] = 1.0\n else:\n difficulty[0] *= np.average(blocktimes[(i-windowLength):i])\n # add difficulty adjustment using average of blocktime in last window\n \n # Get remaining network hash power\n remainingPower = 0;\n for j in range(0,nLic):\n if coinsinwindow[j] < cap: # all Miner's that reached Cap drop out\n remainingPower+=hashPower[j]\n \n # Blocktime rises proportional to 1/rem. hash rate (half the network hashrate -> double the blocktime)\n blocktimes[i] = 1.0/remainingPower / difficulty[0]\n \n # pick Miner with probability equal to his contribution to network hash rate\n ran = np.random.random()\n pos = FirstLarger(cumulPower,ran)\n \n # if that Miner already has reached cap, just choose another one.\n # (blocktime rise is already accounted for)\n while coinsinwindow[pos]>=cap:\n ran = np.random.random()\n pos = FirstLarger(cumulPower,ran)\n \n # Give that miner the coin\n totalcoins[pos] += 1\n coinsinwindow[pos] +=1\n # note who got the coin\n whoMinedBlock[i] = pos;\n \n# now floating Cap \ndef AddCoin_FloatingCap(i, coinsinwindow, totalcoins, blocktimes, whoMinedBlock, difficulty):\n # Determine from where to start counting coins\n if i <= windowLength:\n start = 0\n else:\n start = i - windowLength\n \n if i%windowLength==0:\n if i == 0:\n difficulty[0] = 1.0\n else:\n difficulty[0] *= np.average(blocktimes[i-windowLength:i])\n \n # # Count coins for each miner\n # coinsinwindow.fill(0)\n # for k in range(start, i):\n # miner = int(whoMinedBlock[k])\n # coinsinwindow[miner] += 1\n \n # Get remaining network hash power\n remainingPower = 0;\n for j in range(0,nLic):\n if coinsinwindow[j] < cap: # all Miner's that reached Cap drop out\n remainingPower+=hashPower[j]\n \n # Blocktime rises proportional to 1/rem. hash rate (half the network hashrate -> double the blocktime)\n blocktimes[i] = 1.0/remainingPower / difficulty[0]\n \n # pick Miner with probability equal to his contribution to network hash rate\n ran = np.random.random()\n pos = FirstLarger(cumulPower,ran)\n \n # if that Miner already has reached cap, just choose another one.\n # (blocktime rise is already accounted for)\n while coinsinwindow[pos]>=cap:\n ran = np.random.random()\n pos = FirstLarger(cumulPower,ran)\n \n # Give that miner the coin\n totalcoins[pos] += 1\n \n coinsinwindow[pos] += 1\n \n # note who got the coin\n whoMinedBlock[i] = pos;\n \n # move window along\n if i>=windowLength:\n miner = int(whoMinedBlock[i-windowLength])\n coinsinwindow[miner] -= 1\n \n# now Bucket System \ndef AddCoin_Buckets(i, buckets, totalcoins, blocktimes, whoMinedBlock, difficulty):\n # Determine from where to start counting coins\n \n if i%windowLength==0:\n if i == 0:\n difficulty[0] = 1.0\n else:\n difficulty[0] *= np.average(blocktimes[i-windowLength:i])\n \n # Get remaining network hash power\n remainingPower = 0;\n for j in range(0,nLic):\n if buckets[j] > 0: # all Miner's that reached Cap drop out\n remainingPower+=hashPower[j]\n \n # Blocktime rises proportional to 1/rem. hash rate (half the network hashrate -> double the blocktime)\n blocktimes[i] = 1.0/remainingPower / difficulty[0]\n \n # pick Miner with probability equal to his contribution to network hash rate\n ran = np.random.random()\n pos = FirstLarger(cumulPower,ran)\n \n # if that Miner already has reached cap, just choose another one.\n # (blocktime rise is already accounted for)\n while buckets[pos]<=0:\n ran = np.random.random()\n pos = FirstLarger(cumulPower,ran)\n \n # Give that miner the coin\n totalcoins[pos] += 1\n \n buckets[pos] -= nLic\n \n # note who got the coin\n whoMinedBlock[i] = pos;\n \n # refill all buckets \n buckets += 1\n\n\n\n# Now start simulating\n\n# First Basic Cap\n# Make Arrays for Miners\ncoinsinwindow = np.zeros(nLic)\ntotalcoins = np.zeros(nLic)\n\n# Make Arrays for blockchain\nblocktimes = np.empty(simLength)\nwhoMinedBlock = np.empty(simLength)\n\ndifficulty=np.array([1.0],dtype=float)\nfor i in range(0,simLength):\n if i%10000==0:\n print(i)\n AddCoin_BasicCap(i, coinsinwindow, totalcoins, blocktimes, whoMinedBlock, difficulty)\n\n\n# Plot results\n# Coins in last window\nplt.bar(np.arange(1, nLic+1, 1), coinsinwindow)\n#plt.axis([0, nLicenses+1, 0, cap + 2])\nplt.savefig(fullpath+\"plot_coinsinwindow_basic.png\", dpi=600)\nplt.yscale('log')\nplt.savefig(fullpath+\"logplot_coinsinwindow_basic.png\", dpi=600)\nplt.clf()\nplt.yscale('linear')\n\n# Total coins \nplt.bar(np.arange(1, nLic+1, 1), totalcoins)\n#plt.axis([0, nLicenses+1, 0, capRange])\nplt.savefig(fullpath+\"plot_totalcoins_basic.png\", dpi=600)\nplt.yscale('log')\nplt.savefig(fullpath+\"logplot_totalcoins_basic.png\", dpi=600)\nplt.clf()\nplt.yscale('linear')\n\n# Blocktimes\nplt.plot(np.arange(1, simLength+1, 1),blocktimes)\n#plt.axis([0, simLength, 0, bTime1Range])\nplt.savefig(fullpath+\"plot_blocktimes_basic.png\", dpi=600)\nplt.yscale('log')\nplt.savefig(fullpath+\"logplot_blocktimes_basic.png\", dpi=600)\nplt.clf()\nplt.yscale('linear')\n\n\n\n\n# Now Floating Cap\n# Make Arrays for Miners\ncoinsinwindow = np.zeros(nLic)\ntotalcoins = np.zeros(nLic)\n\n# Make Arrays for blockchain\nblocktimes = np.empty(simLength, dtype=float)\nwhoMinedBlock = np.zeros(simLength)\n\ndifficulty=np.array([1.0],dtype=float)\nfor i in range(0,simLength):\n if i%10000==0:\n print(i)\n AddCoin_FloatingCap(i, coinsinwindow, totalcoins, blocktimes, whoMinedBlock, difficulty)\n\n# Plot results\n# Coins in last window\nplt.bar(np.arange(1, nLic+1, 1), coinsinwindow)\n#plt.axis([0, nLicenses+1, 0, cap + 2])\nplt.savefig(fullpath+\"plot_coinsinwindow_floating.png\", dpi=600)\nplt.yscale('log')\nplt.savefig(fullpath+\"logplot_coinsinwindow_floating.png\", dpi=600)\nplt.clf()\nplt.yscale('linear')\n\n# Total coins \nplt.bar(np.arange(1, nLic+1, 1), totalcoins)\n#plt.axis([0, nLicenses+1, 0, capRange])\nplt.savefig(fullpath+\"plot_totalcoins_floating.png\", dpi=600)\nplt.yscale('log')\nplt.savefig(fullpath+\"logplot_totalcoins_floating.png\", dpi=600)\nplt.clf()\nplt.yscale('linear')\n\n# Blocktimes\nplt.plot(np.arange(1, simLength+1, 1),blocktimes)\n#plt.axis([0, simLength, 0, bTime1Range])\nplt.savefig(fullpath+\"plot_blocktimes_floating.png\", dpi=600)\nplt.yscale('log')\nplt.savefig(fullpath+\"logplot_blocktimes_floating.png\", dpi=600)\nplt.clf()\nplt.yscale('linear')\n\n\n# Now Bucket System\n# Make Arrays for Miners\nbuckets = np.zeros(nLic)\nbuckets += 1\ntotalcoins = np.zeros(nLic)\n\n# Make Arrays for blockchain\nblocktimes = np.empty(simLength, dtype=float)\nwhoMinedBlock = np.zeros(simLength)\n\ndifficulty=np.array([1.0],dtype=float)\nfor i in range(0,simLength):\n if i%10000==0:\n print(i)\n AddCoin_FloatingCap(i, buckets, totalcoins, blocktimes, whoMinedBlock, difficulty)\n\n# Plot results\n# Coins in last window\nplt.bar(np.arange(1, nLic+1, 1), buckets)\n#plt.axis([0, nLicenses+1, 0, cap + 2])\nplt.savefig(fullpath+\"plot_coinsinwindow_buckets.png\", dpi=600)\nplt.yscale('log')\nplt.savefig(fullpath+\"logplot_coinsinwindow_buckets.png\", dpi=600)\nplt.clf()\nplt.yscale('linear')\n\n# Total coins \nplt.bar(np.arange(1, nLic+1, 1), totalcoins)\n#plt.axis([0, nLicenses+1, 0, capRange])\nplt.savefig(fullpath+\"plot_totalcoins_buckets.png\", dpi=600)\nplt.yscale('log')\nplt.savefig(fullpath+\"logplot_totalcoins_buckets.png\", dpi=600)\nplt.clf()\nplt.yscale('linear')\n\n# Blocktimes\nplt.plot(np.arange(1, simLength+1, 1),blocktimes)\n#plt.axis([0, simLength, 0, bTime1Range])\nplt.savefig(fullpath+\"plot_blocktimes_buckets.png\", dpi=600)\nplt.yscale('log')\nplt.savefig(fullpath+\"logplot_blocktimes_buckets.png\", dpi=600)\nplt.clf()\nplt.yscale('linear')\n" ]
[ [ "numpy.random.random", "numpy.arange", "matplotlib.pyplot.yscale", "numpy.cumsum", "numpy.sort", "matplotlib.pyplot.savefig", "matplotlib.pyplot.clf", "numpy.average", "numpy.exp", "numpy.array", "numpy.zeros", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sallen7/IO_GNEP
[ "e6f207113c857690a1d6d7b68673dba09a2dcf2a" ]
[ "csv_data_files_from_experiments/1_generating_more_graphs_experimental_group_1.py" ]
[ "######### 1_generating_more_graphs.py #################\n\n############ Script to Create the Box Plots #############\n\nimport pdb #for debugging\nimport numpy as np \nimport pyomo.environ as pyo\nfrom pyomo.opt import SolverFactory \nfrom pyomo.opt import SolverStatus, TerminationCondition\nimport pyomo.mpec as pyompec #for the complementarity\nimport math\nfrom scipy.io import savemat, loadmat\nimport pandas\nimport time\nimport matplotlib.pyplot as plt\nimport csv\n\n############ Creating the Box Plots ##################\nnum_trials = 10\ntype_of_grid = [i for i in range(2,5+1)]\ntype_of_alpha = [1,2]\nnumber_of_players = [2,5,10]\n\n#############################################\nflow_error = []\nmin_flow_error = []\nmedian_flow_error = []\nmax_flow_error = []\n\nflow_error_normalized = []\nmin_flow_error_normalized = []\nmedian_flow_error_normalized = []\nmax_flow_error_normalized = []\n\ntiming = []\nmin_timing = []\nmedian_timing = []\nmax_timing = []\n\nobjective_error = []\nmin_objective_error = []\nmedian_objective_error = []\nmax_objective_error = []\n\nnames = []\n######## Aggregating the Data ##############\nfor player in number_of_players:\n for alpha in type_of_alpha:\n if alpha == 1:\n alpha_var = int(round(player/2))\n alpha_graph = player/2\n elif alpha == 2:\n alpha_var = int(player)\n alpha_graph = player\n for grid in type_of_grid:\n name_of_data = \"data_saving_experiment_\"+str(grid)+\"x\"+str(grid)+\\\n \"_Grid_num_players_\"+str(player)+\"_alpha_\"+str(alpha_var)+\".csv\"\n names.append(str(grid)+\"/\"+str(player)+\"/\"+str(alpha_graph))\n data = pandas.read_csv(name_of_data)\n \n #pdb.set_trace()\n \n ph_flow_error = np.zeros((num_trials,))\n ph_flow_error_normalized = np.zeros((num_trials,))\n ph_timing = np.zeros((num_trials,))\n ph_obj_error = np.zeros((num_trials,))\n \n ######### Figuring out number of OD pairs ##########\n dummy_variable = 1\n for i in range(1,grid*grid+1):\n dummy_variable = dummy_variable*i\n \n dummy_variable2 = 1\n for i in range(1,grid*grid-2+1):\n dummy_variable2 = dummy_variable2*i\n \n num_od_pairs = int((dummy_variable/(2*dummy_variable2))*2)\n ##########################################################\n normalization_factor = num_od_pairs*player*(grid-1)*(grid)*2*2\n \n #pdb.set_trace()\n for j in range(0,num_trials):\n ph_flow_error[j] = float(data.loc[2,str(j+1)])\n ph_flow_error_normalized[j] = float(data.loc[2,str(j+1)])/(normalization_factor)\n ph_timing[j] = (float(data.loc[3,str(j+1)])/60)\n ph_obj_error[j] = float(data.loc[4,str(j+1)])\n if data.loc[5,str(j+1)]==\"optimal\":\n pass\n else:\n print(\"PROBLEM: Non-optimal flag\")\n pdb.set_trace()\n \n ########## Calculating the Min, Median, and Max ############\n min_flow_error.append(np.min(ph_flow_error))\n median_flow_error.append(np.median(ph_flow_error))\n max_flow_error.append(np.max(ph_flow_error))\n \n min_flow_error_normalized.append(np.min(ph_flow_error_normalized))\n median_flow_error_normalized.append(np.median(ph_flow_error_normalized))\n max_flow_error_normalized.append(np.max(ph_flow_error_normalized))\n \n min_timing.append(np.min(ph_timing))\n median_timing.append(np.median(ph_timing))\n max_timing.append(np.max(ph_timing))\n \n min_objective_error.append(np.min(ph_obj_error))\n median_objective_error.append(np.median(ph_obj_error))\n max_objective_error.append(np.max(ph_obj_error)) \n \n ######## Appending to the Lists ##############\n flow_error.append(ph_flow_error)\n flow_error_normalized.append(ph_flow_error_normalized)\n timing.append(ph_timing)\n objective_error.append(ph_obj_error)\n\n########### Creating the Box Plots #############\n#pdb.set_trace() \n##### Print out Min/Median/Max ######\nprint(\"min flow error\", min_flow_error)\nprint(\"median_flow_error\",median_flow_error)\nprint(\"max_flow_error\",max_flow_error)\nprint(\"*********************************\")\nprint(\"min flow error normalized\", min_flow_error_normalized)\nprint(\"median_flow_error normalized\",median_flow_error_normalized)\nprint(\"max_flow_error normalized\",max_flow_error_normalized)\nprint(\"******************************\")\nprint(\"min_timing\",min_timing)\nprint(\"median_timing\",median_timing)\nprint(\"max_timing\",max_timing)\nprint(\"*****************************\")\nprint(\"min_objective_error\",min_objective_error)\nprint(\"median_objective_error\",median_objective_error)\nprint(\"max_objective_error\",max_objective_error)\n\n##### Flow Error #########\nvisual,test = plt.subplots()\ntest.boxplot(flow_error)\ntest.set_title(\"Flow Error for Grids: Same Parameters and 10 Trials for Each Experiment\")\n#pdb.set_trace()\nplt.xticks(rotation=45)\ntest.set_xticklabels(names)\ntest.set_ylabel(\"Frobenius-norm\")\n \nplt.show()\n\n\n##### Flow Error Normalized #########\ntest1 = plt.subplot(111)\ntest1.boxplot(flow_error_normalized)\nplt.title(\"Normalized Flow Error for Grids: Same Parameters and 10 Trials for Each Experiment\")\nplt.xticks(rotation=45)\ntest1.set_xticklabels(names)\nplt.ylabel(\"Frobenius-norm/((OD Pair Number)*(Num Arcs)*(Num Players))\")\nplt.show()\n\n\n##### Timing ##########\ntest2 = plt.subplot(111)\ntest2.boxplot(timing)\nplt.title(\"Timing for Grids: Same Parameters and 10 Trials for Each Experiment\")\nplt.xticks(rotation=45)\ntest2.set_xticklabels(names)\nplt.ylabel(\"Minutes\")\nplt.show()\n\n#### Objective Error ######\ntest3 = plt.subplot(111)\ntest3.boxplot(objective_error)\nplt.title(\"Obj Function Values for Grids: Same Parameters and 10 Trials for Each Experiment\")\nplt.xticks(rotation=45)\ntest3.set_xticklabels(names)\nplt.ylabel(\"Objective Function Value\")\nplt.show()\n\n" ]
[ [ "pandas.read_csv", "matplotlib.pyplot.title", "numpy.min", "numpy.median", "matplotlib.pyplot.subplots", "numpy.max", "matplotlib.pyplot.subplot", "matplotlib.pyplot.xticks", "matplotlib.pyplot.show", "numpy.zeros", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
YoungForever222/NN_POD
[ "c2fc0123a899667dbd712571762110189ad98e88" ]
[ "encoder.py" ]
[ "'''\r\n\r\nData mining from\r\n\r\n'''\r\n# Common imports\r\nimport os\r\nimport sys\r\nfrom data import *\r\nfrom tqdm import *\r\nimport numpy as np\r\nimport numpy.random as rnd\r\nimport tensorflow as tf\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\n#from sklearn.preprocessing import StandardScaler\r\nfrom sklearn.model_selection import train_test_split\r\n\r\ndef reset_graph(seed=42):\r\n \"\"\"\r\n to make this notebook's output stable across runs\r\n \"\"\"\r\n tf.reset_default_graph()\r\n tf.set_random_seed(seed)\r\n rnd.seed(seed)\r\n\r\nplt.rcParams['axes.labelsize'] = 14\r\nplt.rcParams['xtick.labelsize'] = 12\r\nplt.rcParams['ytick.labelsize'] = 12\r\nPROJECT_ROOT_DIR = \".\"\r\nCODE_ID = \"autoencoders\"\r\n\r\ndef save_fig(fig_id, tight_layout=True):\r\n path = os.path.join(PROJECT_ROOT_DIR, \"images\", CODE_ID, fig_id + \".png\")\r\n print(\"Saving figure\", fig_id)\r\n if tight_layout:\r\n plt.tight_layout()\r\n plt.savefig(path, format='png', dpi=300)\r\n\r\ndef plot_image(image, shape=[28, 28]):\r\n plt.imshow(image.reshape(shape), cmap=\"Greys\", interpolation=\"nearest\")\r\n plt.axis(\"off\")\r\n\r\ndef plot_multiple_images(images, n_rows, n_cols, pad=2):\r\n images = images - images.min() # make the minimum == 0, so the padding looks white\r\n w, h = images.shape[1:]\r\n image = np.zeros(((w + pad) * n_rows + pad, (h + pad) * n_cols + pad))\r\n for y in range(n_rows):\r\n for x in range(n_cols):\r\n image[(y * (h + pad) + pad):(y * (h + pad) + pad + h), (x *\r\n (w + pad) + pad):(x * (w + pad) + pad + w)] = images[y * n_cols + x]\r\n plt.imshow(image, cmap=\"Greys\", interpolation=\"nearest\")\r\n plt.axis(\"off\")\r\n\r\ndef run():\r\n '''\r\n Main function of the Auto-Encoder\r\n input:\r\n X_train: The input and the target Tensor.\r\n '''\r\n reset_graph()\r\n linear = False\r\n n_inputs = 400\r\n n_hidden = 128 # codings\r\n n_mid = 100\r\n n_outputs = n_inputs\r\n learning_rate = 0.001\r\n datasets = DataVel().Vel\r\n X_train = datasets\r\n X = tf.placeholder(tf.float32, shape=[64*64*3, n_inputs])\r\n # Net\r\n if linear:\r\n mid = tf.layers.dense(X,n_mid)\r\n outputs = tf.layers.dense(mid, n_outputs)\r\n else:\r\n hidden1 = tf.layers.dense(X, n_hidden,activation=tf.tanh)\r\n mid = tf.layers.dense(hidden1,n_mid)\r\n hidden2 = tf.layers.dense(mid,n_hidden,activation=tf.tanh)\r\n outputs = tf.layers.dense(hidden2, n_outputs)\r\n reconstruction_loss = tf.reduce_mean(tf.square(outputs - X))\r\n accuracy_loss = tf.sqrt(tf.reduce_mean(tf.square(outputs - X)))/tf.sqrt(tf.reduce_mean(tf.square(X)))\r\n optimizer = tf.train.AdamOptimizer(learning_rate)\r\n training_op = optimizer.minimize(reconstruction_loss)\r\n init = tf.global_variables_initializer()\r\n n_iterations = 10000\r\n codings = mid\r\n with tf.Session() as sess:\r\n init.run()\r\n for step in tqdm(range(n_iterations)):\r\n training_op.run(feed_dict={X: X_train})\r\n loss_train = accuracy_loss.eval(feed_dict={X: X_train})\r\n if step % (n_iterations/10) == 0:\r\n print(\"\\r{}\".format(step), \"Train MSE:\", loss_train) \r\n codings_val = codings.eval(feed_dict={X: X_train})\r\n loss_train = accuracy_loss.eval(feed_dict={X: X_train})\r\n print(\"Test MSE:\",loss_train)\r\n print(codings_val.shape)\r\n result_vel = codings_val.reshape((64,64,3,n_mid))\r\n for i in range(n_mid):\r\n energy = .5*(np.sqrt(result_vel[:,:,0,i]**2 + result_vel[:,:,1,i]**2 + result_vel[:,:,2,i]**2))\r\n fig = plt.figure(figsize=(6.,6.))\r\n ax = fig.add_axes([.0, .0, 1., 1.])\r\n contour = ax.contour(z, y, energy, 30)\r\n ax.set_xlabel('z')\r\n ax.set_ylabel('y')\r\n plt.clabel(contour, inline=1, fontsize=10)\r\n plt.title('Energy contours, layer = {0}'.format(i))\r\n fig.savefig('./middle_layer/'+figname + str(i)+'.eps', format = 'eps', bbox_inches = 'tight')\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n run()\r\n" ]
[ [ "matplotlib.pyplot.imshow", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.clabel", "numpy.sqrt", "numpy.random.seed", "tensorflow.placeholder", "matplotlib.pyplot.savefig", "tensorflow.layers.dense", "tensorflow.global_variables_initializer", "tensorflow.reset_default_graph", "tensorflow.train.AdamOptimizer", "matplotlib.pyplot.axis", "tensorflow.set_random_seed", "tensorflow.square", "tensorflow.Session", "numpy.zeros", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
thispl/infac
[ "3d624e23f20e078cd07dbbb3afbb7f4341589396" ]
[ "infac/infac/doctype/contract_attendance_and_ot_upload/contract_attendance_and_ot_upload.py" ]
[ "# -*- coding: utf-8 -*-\n# Copyright (c) 2021, TeamPRO and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nfrom calendar import monthrange\nimport frappe\nfrom frappe.model.document import Document\nfrom dateutil.relativedelta import relativedelta\nfrom frappe.utils import cint, flt, nowdate, add_days, getdate, fmt_money, add_to_date, DATE_FORMAT, date_diff, money_in_words\nfrom frappe import _\nimport functools\nfrom datetime import datetime, timedelta\nfrom frappe.utils.csvutils import read_csv_content\n\nclass ContractAttendanceandOTUpload(Document):\n pass\n\[email protected]()\ndef get_end_date(start_date, frequency):\n start_date = getdate(start_date)\n frequency = frequency.lower() if frequency else 'monthly'\n kwargs = get_frequency_kwargs(frequency) if frequency != 'bimonthly' else get_frequency_kwargs('monthly')\n\n # weekly, fortnightly and daily intervals have fixed days so no problems\n end_date = add_to_date(start_date, **kwargs) - relativedelta(days=1)\n if frequency != 'bimonthly':\n return dict(end_date=end_date.strftime(DATE_FORMAT))\n\n else:\n return dict(end_date='')\n\ndef get_frequency_kwargs(frequency_name):\n frequency_dict = {\n 'monthly': {'months': 1},\n 'fortnightly': {'days': 14},\n 'weekly': {'days': 7},\n 'daily': {'days': 1}\n }\n return frequency_dict.get(frequency_name)\n\[email protected]()\ndef mark_attendance(file_url,start_date,end_date):\n #below is the method to get file from Frappe File manager\n from frappe.utils.file_manager import get_file\n #Method to fetch file using get_doc and stored as _file\n _file = frappe.get_doc(\"File\", {\"file_url\": file_url})\n #Path in the system\n filepath = get_file(file_url)\n #CSV Content stored as pps\n\n pps = read_csv_content(filepath[1])\n for pp in pps:\n frappe.errprint(pp)\n holiday_list = frappe.db.get_value(\"Employee\",{\"name\":pp[0]},[\"holiday_list\"])\n holiday_map = frappe._dict()\n\n # for d in holiday_list:\n # if d:\n holiday_list = frappe.db.sql('''select holiday_date from `tabHoliday`\n where parent=%s and holiday_date between %s and %s''', (holiday_list, start_date, end_date))\n holidays = []\n for holiday in holiday_list:\n holidays.append(holiday[0])\n import pandas as pd\n total_days = pd.date_range(start_date, end_date).tolist()\n day = 1\n for days in total_days:\n date = days.date()\n if date not in holidays:\n frappe.errprint(date)\n if int(pp[1]) >= day:\n attendance = frappe.new_doc(\"Attendance\")\n attendance.update({\n \"employee\":pp[0],\n \"attendance_date\":date,\n \"status\":\"Absent\"\n }).save(ignore_permissions = True)\n attendance.submit()\n frappe.db.commit()\n day = day+1\n if float(pp[2])>=1:\n ts = frappe.new_doc(\"Timesheet\")\n ts.employee = pp[0]\n ts.append(\"time_logs\",{\n \"activity_type\":\"Overtime\",\n \"from_time\":start_date,\n \"hours\":float(pp[2])\n })\n ts.save(ignore_permissions=True)\n ts.submit()\n frappe.db.commit()" ]
[ [ "pandas.date_range" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
GrassSunFlower/mxnet_tmp
[ "190f16172cbe80f751d4840847fd5a5df43552bd", "190f16172cbe80f751d4840847fd5a5df43552bd" ]
[ "python/mxnet/io.py", "python/mxnet/_ctypes/ndarray.py" ]
[ "\"\"\"Data iterators for common data formats.\"\"\"\nfrom __future__ import absolute_import\nfrom collections import OrderedDict, namedtuple\n\nimport sys\nimport ctypes\nimport logging\nimport threading\nimport numpy as np\nfrom .base import _LIB\nfrom .base import c_array, c_str, mx_uint, py_str\nfrom .base import DataIterHandle, NDArrayHandle\nfrom .base import mx_real_t\nfrom .base import check_call, build_param_doc as _build_param_doc\nfrom .ndarray import NDArray\nfrom .ndarray import array\nfrom .ndarray import concatenate\n\nclass DataDesc(namedtuple('DataDesc', ['name', 'shape'])):\n \"\"\"Data description\n\n Parameters\n ----------\n cls : DataDesc\n The class.\n name : str\n Data name.\n shape : tuple of int\n Data shape.\n dtype : np.dtype, optional\n Data type.\n layout : str, optional\n Data layout.\n \"\"\"\n def __new__(cls, name, shape, dtype=mx_real_t, layout='NCHW'):\n ret = super(cls, DataDesc).__new__(cls, name, shape)\n ret.dtype = dtype\n ret.layout = layout\n return ret\n\n def __repr__(self):\n return \"DataDesc[%s,%s,%s,%s]\" % (self.name, self.shape, self.dtype,\n self.layout)\n\n @staticmethod\n def get_batch_axis(layout):\n \"\"\"Get the dimension that corresponds to the batch size.\n\n When data parallelism is used, the data will be automatically split and\n concatenated along the batch-size dimension. Axis can be -1, which means\n the whole array will be copied for each data-parallelism device.\n\n Parameters\n ----------\n layout : str\n layout string. For example, \"NCHW\".\n\n Returns\n -------\n int\n An axis indicating the batch_size dimension.\n \"\"\"\n if layout is None:\n return 0\n return layout.find('N')\n\n @staticmethod\n def get_list(shapes, types):\n \"\"\"Get DataDesc list from attribute lists.\n\n Parameters\n ----------\n shapes : a tuple of (name, shape)\n types : a tuple of (name, type)\n \"\"\"\n if types is not None:\n type_dict = dict(types)\n return [DataDesc(x[0], x[1], type_dict[x[0]]) for x in shapes]\n else:\n return [DataDesc(x[0], x[1]) for x in shapes]\n\nclass DataBatch(object):\n \"\"\"A data batch.\n\n Parameters\n ----------\n data : list of NDArray\n A list of input data.\n label : list of NDArray\n A list of input labels.\n pad : int, optional\n The number of examples padded at the batch end. It is used when the\n examples read is less than the batch size.\n index : numpy.array, optional\n The example indices in this batch.\n bucket_key : int, optional\n The key of the bucket, used for bucket IO.\n provide_data : list of (name, shape), optional\n The *i*-th elements describes the name and shape of ``data[i]``.\n provide_label : list of (name, shape), optional\n The *i*-th elements describes the name and shape of ``label[i]``.\n \"\"\"\n def __init__(self, data, label, pad=None, index=None,\n bucket_key=None, provide_data=None, provide_label=None):\n if data is not None:\n assert isinstance(data, (list, tuple)), \"Data must be list of NDArrays\"\n if label is not None:\n assert isinstance(label, (list, tuple)), \"Label must be list of NDArrays\"\n self.data = data\n self.label = label\n self.pad = pad\n self.index = index\n\n self.bucket_key = bucket_key\n self.provide_data = provide_data\n self.provide_label = provide_label\n\n def __str__(self):\n data_shapes = [d.shape for d in self.data]\n label_shapes = [l.shape for l in self.label]\n return \"{}: data shapes: {} label shapes: {}\".format(\n self.__class__.__name__,\n data_shapes,\n label_shapes)\n\nclass DataIter(object):\n \"\"\"The base class of a data iterator.\n\n Parameters\n ----------\n batch_size : int, optional\n The batch size, namely the number of examples in a batch.\n \"\"\"\n def __init__(self, batch_size=0):\n self.batch_size = batch_size\n\n def __iter__(self):\n return self\n\n def reset(self):\n \"\"\"Reset the iterator to the begin of the data.\"\"\"\n pass\n\n def next(self):\n \"\"\"Get next data batch from iterator.\n\n Returns\n -------\n DataBatch\n The data of next batch.\n\n Raises\n ------\n StopIteration\n If the end of the data is reached.\n \"\"\"\n if self.iter_next():\n return DataBatch(data=self.getdata(), label=self.getlabel(), \\\n pad=self.getpad(), index=self.getindex())\n else:\n raise StopIteration\n\n def __next__(self):\n return self.next()\n\n def iter_next(self):\n \"\"\"Move to the next batch.\n\n Returns\n -------\n boolean\n Whether the move is successful.\n \"\"\"\n pass\n\n def getdata(self):\n \"\"\"Get data of current batch.\n\n Returns\n -------\n list of NDArray\n The data of the current batch.\n \"\"\"\n pass\n\n def getlabel(self):\n \"\"\"Get label of the current batch.\n\n Returns\n -------\n list of NDArray\n The label of the current batch.\n \"\"\"\n pass\n\n def getindex(self):\n \"\"\"Get index of the current batch.\n\n Returns\n -------\n index : numpy.array\n The indices of examples in the current batch.\n \"\"\"\n return None\n\n def getpad(self):\n \"\"\"Get the number of padding examples in the current batch.\n\n Returns\n -------\n int\n Number of padding examples in the current batch.\n \"\"\"\n pass\n\nclass ResizeIter(DataIter):\n \"\"\"Resize a data iterator to a given number of batches.\n\n Parameters\n ----------\n data_iter : DataIter\n The data iterator to be resized.\n size : int\n The number of batches per epoch to resize to.\n reset_internal : bool\n Whether to reset internal iterator on ResizeIter.reset.\n\n\n Examples\n --------\n >>> nd_iter = mx.io.NDArrayIter(mx.nd.ones((100,10)), batch_size=25)\n >>> resize_iter = mx.io.ResizeIter(nd_iter, 2)\n >>> for batch in resize_iter:\n ... print(batch.data)\n [<NDArray 25x10 @cpu(0)>]\n [<NDArray 25x10 @cpu(0)>]\n \"\"\"\n def __init__(self, data_iter, size, reset_internal=True):\n super(ResizeIter, self).__init__()\n self.data_iter = data_iter\n self.size = size\n self.reset_internal = reset_internal\n self.cur = 0\n self.current_batch = None\n\n self.provide_data = data_iter.provide_data\n self.provide_label = data_iter.provide_label\n self.batch_size = data_iter.batch_size\n if hasattr(data_iter, 'default_bucket_key'):\n self.default_bucket_key = data_iter.default_bucket_key\n\n def reset(self):\n self.cur = 0\n if self.reset_internal:\n self.data_iter.reset()\n\n def iter_next(self):\n if self.cur == self.size:\n return False\n try:\n self.current_batch = self.data_iter.next()\n except StopIteration:\n self.data_iter.reset()\n self.current_batch = self.data_iter.next()\n\n self.cur += 1\n return True\n\n def getdata(self):\n return self.current_batch.data\n\n def getlabel(self):\n return self.current_batch.label\n\n def getindex(self):\n return self.current_batch.index\n\n def getpad(self):\n return self.current_batch.pad\n\nclass PrefetchingIter(DataIter):\n \"\"\"Performs pre-fetch for other data iterators.\n\n This iterator will create another thread to perform ``iter_next`` and then\n store the data in memory. It potentially accelerates the data read, at the\n cost of more memory usage.\n\n Parameters\n ----------\n iters : DataIter or list of DataIter\n The data iterators to be pre-fetched.\n rename_data : None or list of dict\n The *i*-th element is a renaming map for the *i*-th iter, in the form of\n {'original_name' : 'new_name'}. Should have one entry for each entry\n in iter[i].provide_data.\n rename_label : None or list of dict\n Similar to ``rename_data``.\n\n Examples\n --------\n >>> iter1 = mx.io.NDArrayIter({'data':mx.nd.ones((100,10))}, batch_size=25)\n >>> iter2 = mx.io.NDArrayIter({'data':mx.nd.ones((100,10))}, batch_size=25)\n >>> piter = mx.io.PrefetchingIter([iter1, iter2],\n ... rename_data=[{'data': 'data_1'}, {'data': 'data_2'}])\n >>> print(piter.provide_data)\n [DataDesc[data_1,(25, 10L),<type 'numpy.float32'>,NCHW],\n DataDesc[data_2,(25, 10L),<type 'numpy.float32'>,NCHW]]\n \"\"\"\n def __init__(self, iters, rename_data=None, rename_label=None):\n super(PrefetchingIter, self).__init__()\n if not isinstance(iters, list):\n iters = [iters]\n self.n_iter = len(iters)\n assert self.n_iter > 0\n self.iters = iters\n self.rename_data = rename_data\n self.rename_label = rename_label\n self.batch_size = self.provide_data[0][1][0]\n self.data_ready = [threading.Event() for i in range(self.n_iter)]\n self.data_taken = [threading.Event() for i in range(self.n_iter)]\n for i in self.data_taken:\n i.set()\n self.started = True\n self.current_batch = [None for i in range(self.n_iter)]\n self.next_batch = [None for i in range(self.n_iter)]\n def prefetch_func(self, i):\n \"\"\"Thread entry\"\"\"\n while True:\n self.data_taken[i].wait()\n if not self.started:\n break\n try:\n self.next_batch[i] = self.iters[i].next()\n except StopIteration:\n self.next_batch[i] = None\n self.data_taken[i].clear()\n self.data_ready[i].set()\n self.prefetch_threads = [threading.Thread(target=prefetch_func, args=[self, i]) \\\n for i in range(self.n_iter)]\n for thread in self.prefetch_threads:\n thread.setDaemon(True)\n thread.start()\n\n def __del__(self):\n self.started = False\n for i in self.data_taken:\n i.set()\n for thread in self.prefetch_threads:\n thread.join()\n\n @property\n def provide_data(self):\n if self.rename_data is None:\n return sum([i.provide_data for i in self.iters], [])\n else:\n return sum([[\n DataDesc(r[x.name], x.shape, x.dtype)\n if isinstance(x, DataDesc) else DataDesc(*x)\n for x in i.provide_data\n ] for r, i in zip(self.rename_data, self.iters)], [])\n\n @property\n def provide_label(self):\n if self.rename_label is None:\n return sum([i.provide_label for i in self.iters], [])\n else:\n return sum([[\n DataDesc(r[x.name], x.shape, x.dtype)\n if isinstance(x, DataDesc) else DataDesc(*x)\n for x in i.provide_label\n ] for r, i in zip(self.rename_label, self.iters)], [])\n\n def reset(self):\n for i in self.data_ready:\n i.wait()\n for i in self.iters:\n i.reset()\n for i in self.data_ready:\n i.clear()\n for i in self.data_taken:\n i.set()\n\n def iter_next(self):\n for i in self.data_ready:\n i.wait()\n if self.next_batch[0] is None:\n for i in self.next_batch:\n assert i is None, \"Number of entry mismatches between iterators\"\n return False\n else:\n for batch in self.next_batch:\n assert batch.pad == self.next_batch[0].pad, \\\n \"Number of entry mismatches between iterators\"\n self.current_batch = DataBatch(sum([batch.data for batch in self.next_batch], []),\n sum([batch.label for batch in self.next_batch], []),\n self.next_batch[0].pad,\n self.next_batch[0].index,\n provide_data=self.provide_data,\n provide_label=self.provide_label)\n for i in self.data_ready:\n i.clear()\n for i in self.data_taken:\n i.set()\n return True\n\n def next(self):\n if self.iter_next():\n return self.current_batch\n else:\n raise StopIteration\n\n def getdata(self):\n return self.current_batch.data\n\n def getlabel(self):\n return self.current_batch.label\n\n def getindex(self):\n return self.current_batch.index\n\n def getpad(self):\n return self.current_batch.pad\n\ndef _init_data(data, allow_empty, default_name):\n \"\"\"Convert data into canonical form.\"\"\"\n assert (data is not None) or allow_empty\n if data is None:\n data = []\n\n if isinstance(data, (np.ndarray, NDArray)):\n data = [data]\n if isinstance(data, list):\n if not allow_empty:\n assert(len(data) > 0)\n if len(data) == 1:\n data = OrderedDict([(default_name, data[0])]) # pylint: disable=redefined-variable-type\n else:\n data = OrderedDict( # pylint: disable=redefined-variable-type\n [('_%d_%s' % (i, default_name), d) for i, d in enumerate(data)])\n if not isinstance(data, dict):\n raise TypeError(\"Input must be NDArray, numpy.ndarray, \" + \\\n \"a list of them or dict with them as values\")\n for k, v in data.items():\n if not isinstance(v, NDArray):\n try:\n data[k] = array(v)\n except:\n raise TypeError((\"Invalid type '%s' for %s, \" % (type(v), k)) + \\\n \"should be NDArray or numpy.ndarray\")\n\n return list(data.items())\n\nclass NDArrayIter(DataIter):\n \"\"\"Iterating on either ``mx.nd.NDArray`` or ``numpy.ndarray``.\n\n Parameters\n ----------\n data: array or list of array or dict of string to array\n Input data\n label: array or list of array or dict of string to array, optional\n Input label\n batch_size: int\n Batch Size\n shuffle: bool, optional\n Whether to shuffle the data\n last_batch_handle : str, optional\n How to handle the last batch, can be 'pad', 'discard' or\n 'roll_over'. 'roll_over' is intended for training and can cause problems\n if used for prediction.\n data_name : str, optional\n The data name\n label_name : str, optional\n The label name\n \"\"\"\n def __init__(self, data, label=None, batch_size=1, shuffle=False,\n last_batch_handle='pad', data_name='data',\n label_name='softmax_label'):\n super(NDArrayIter, self).__init__(batch_size)\n\n self.data = _init_data(data, allow_empty=False, default_name=data_name)\n self.label = _init_data(label, allow_empty=True, default_name=label_name)\n\n # shuffle data\n if shuffle:\n idx = np.arange(self.data[0][1].shape[0])\n np.random.shuffle(idx)\n self.data = [(k, array(v.asnumpy()[idx], v.context)) for k, v in self.data]\n self.label = [(k, array(v.asnumpy()[idx], v.context)) for k, v in self.label]\n\n # batching\n if last_batch_handle == 'discard':\n new_n = self.data[0][1].shape[0] - self.data[0][1].shape[0] % batch_size\n data_dict = OrderedDict(self.data)\n label_dict = OrderedDict(self.label)\n for k, _ in self.data:\n data_dict[k] = data_dict[k][:new_n]\n for k, _ in self.label:\n label_dict[k] = label_dict[k][:new_n]\n self.data = data_dict.items()\n self.label = label_dict.items()\n\n self.data_list = [x[1] for x in self.data] + [x[1] for x in self.label]\n self.num_source = len(self.data_list)\n self.num_data = self.data_list[0].shape[0]\n assert self.num_data >= batch_size, \\\n \"batch_size need to be smaller than data size.\"\n self.cursor = -batch_size\n self.batch_size = batch_size\n self.last_batch_handle = last_batch_handle\n\n @property\n def provide_data(self):\n \"\"\"The name and shape of data provided by this iterator.\"\"\"\n return [\n DataDesc(k, tuple([self.batch_size] + list(v.shape[1:])), v.dtype)\n for k, v in self.data\n ]\n\n @property\n def provide_label(self):\n \"\"\"The name and shape of label provided by this iterator.\"\"\"\n return [\n DataDesc(k, tuple([self.batch_size] + list(v.shape[1:])), v.dtype)\n for k, v in self.label\n ]\n\n def hard_reset(self):\n \"\"\"Ignore roll over data and set to start.\"\"\"\n self.cursor = -self.batch_size\n\n def reset(self):\n if self.last_batch_handle == 'roll_over' and self.cursor > self.num_data:\n self.cursor = -self.batch_size + (self.cursor%self.num_data)%self.batch_size\n else:\n self.cursor = -self.batch_size\n\n def iter_next(self):\n self.cursor += self.batch_size\n return self.cursor < self.num_data\n\n def next(self):\n if self.iter_next():\n return DataBatch(data=self.getdata(), label=self.getlabel(), \\\n pad=self.getpad(), index=None)\n else:\n raise StopIteration\n\n def _getdata(self, data_source):\n \"\"\"Load data from underlying arrays, internal use only.\"\"\"\n assert(self.cursor < self.num_data), \"DataIter needs reset.\"\n if self.cursor + self.batch_size <= self.num_data:\n return [x[1][self.cursor:self.cursor+self.batch_size] for x in data_source]\n else:\n pad = self.batch_size - self.num_data + self.cursor\n return [concatenate([x[1][self.cursor:], x[1][:pad]]) for x in data_source]\n\n def getdata(self):\n return self._getdata(self.data)\n\n def getlabel(self):\n return self._getdata(self.label)\n\n def getpad(self):\n if self.last_batch_handle == 'pad' and \\\n self.cursor + self.batch_size > self.num_data:\n return self.cursor + self.batch_size - self.num_data\n else:\n return 0\n\n\nclass MXDataIter(DataIter):\n \"\"\"A python wrapper a C++ data iterator.\n\n Parameters\n ----------\n handle : DataIterHandle\n The handle to the underlying C++ Data Iterator.\n \"\"\"\n def __init__(self, handle, data_name='data', label_name='softmax_label', **_):\n super(MXDataIter, self).__init__()\n self.handle = handle\n # debug option, used to test the speed with io effect eliminated\n self._debug_skip_load = False\n\n # load the first batch to get shape information\n self.first_batch = None\n self.first_batch = self.next()\n data = self.first_batch.data[0]\n label = self.first_batch.label[0]\n\n # properties\n self.provide_data = [DataDesc(data_name, data.shape, data.dtype)]\n self.provide_label = [DataDesc(label_name, label.shape, label.dtype)]\n self.batch_size = data.shape[0]\n\n\n def __del__(self):\n check_call(_LIB.MXDataIterFree(self.handle))\n\n def debug_skip_load(self):\n # Set the iterator to simply return always first batch. This can be used\n # to test the speed of network without taking the loading delay into\n # account.\n self._debug_skip_load = True\n logging.info('Set debug_skip_load to be true, will simply return first batch')\n\n def reset(self):\n self._debug_at_begin = True\n self.first_batch = None\n check_call(_LIB.MXDataIterBeforeFirst(self.handle))\n\n def next(self):\n if self._debug_skip_load and not self._debug_at_begin:\n return DataBatch(data=[self.getdata()], label=[self.getlabel()], pad=self.getpad(),\n index=self.getindex())\n if self.first_batch is not None:\n batch = self.first_batch\n self.first_batch = None\n return batch\n self._debug_at_begin = False\n next_res = ctypes.c_int(0)\n check_call(_LIB.MXDataIterNext(self.handle, ctypes.byref(next_res)))\n if next_res.value:\n return DataBatch(data=[self.getdata()], label=[self.getlabel()], pad=self.getpad(),\n index=self.getindex())\n else:\n raise StopIteration\n\n def iter_next(self):\n if self.first_batch is not None:\n return True\n next_res = ctypes.c_int(0)\n check_call(_LIB.MXDataIterNext(self.handle, ctypes.byref(next_res)))\n return next_res.value\n\n def getdata(self):\n hdl = NDArrayHandle()\n check_call(_LIB.MXDataIterGetData(self.handle, ctypes.byref(hdl)))\n return NDArray(hdl, False)\n\n def getlabel(self):\n hdl = NDArrayHandle()\n check_call(_LIB.MXDataIterGetLabel(self.handle, ctypes.byref(hdl)))\n return NDArray(hdl, False)\n\n def getindex(self):\n index_size = ctypes.c_uint64(0)\n index_data = ctypes.POINTER(ctypes.c_uint64)()\n check_call(_LIB.MXDataIterGetIndex(self.handle,\n ctypes.byref(index_data),\n ctypes.byref(index_size)))\n address = ctypes.addressof(index_data.contents)\n dbuffer = (ctypes.c_uint64* index_size.value).from_address(address)\n np_index = np.frombuffer(dbuffer, dtype=np.uint64)\n return np_index.copy()\n\n def getpad(self):\n pad = ctypes.c_int(0)\n check_call(_LIB.MXDataIterGetPadNum(self.handle, ctypes.byref(pad)))\n return pad.value\n\ndef _make_io_iterator(handle):\n \"\"\"Create an io iterator by handle.\"\"\"\n name = ctypes.c_char_p()\n desc = ctypes.c_char_p()\n num_args = mx_uint()\n arg_names = ctypes.POINTER(ctypes.c_char_p)()\n arg_types = ctypes.POINTER(ctypes.c_char_p)()\n arg_descs = ctypes.POINTER(ctypes.c_char_p)()\n\n check_call(_LIB.MXDataIterGetIterInfo( \\\n handle, ctypes.byref(name), ctypes.byref(desc), \\\n ctypes.byref(num_args), \\\n ctypes.byref(arg_names), \\\n ctypes.byref(arg_types), \\\n ctypes.byref(arg_descs)))\n iter_name = py_str(name.value)\n\n narg = int(num_args.value)\n param_str = _build_param_doc(\n [py_str(arg_names[i]) for i in range(narg)],\n [py_str(arg_types[i]) for i in range(narg)],\n [py_str(arg_descs[i]) for i in range(narg)])\n\n doc_str = ('%s\\n\\n' +\n '%s\\n' +\n 'Returns\\n' +\n '-------\\n' +\n 'MXDataIter\\n'+\n ' The result iterator.')\n doc_str = doc_str % (desc.value, param_str)\n\n def creator(*args, **kwargs):\n \"\"\"Create an iterator.\n The parameters listed below can be passed in as keyword arguments.\n\n Parameters\n ----------\n name : string, required.\n Name of the resulting data iterator.\n\n Returns\n -------\n dataiter: Dataiter\n The resulting data iterator.\n \"\"\"\n param_keys = []\n param_vals = []\n\n for k, val in kwargs.items():\n param_keys.append(c_str(k))\n param_vals.append(c_str(str(val)))\n # create atomic symbol\n param_keys = c_array(ctypes.c_char_p, param_keys)\n param_vals = c_array(ctypes.c_char_p, param_vals)\n iter_handle = DataIterHandle()\n check_call(_LIB.MXDataIterCreateIter(\n handle,\n mx_uint(len(param_keys)),\n param_keys, param_vals,\n ctypes.byref(iter_handle)))\n\n if len(args):\n raise TypeError('%s can only accept keyword arguments' % iter_name)\n\n return MXDataIter(iter_handle, **kwargs)\n\n creator.__name__ = iter_name\n creator.__doc__ = doc_str\n return creator\n\ndef _init_io_module():\n \"\"\"List and add all the data iterators to current module.\"\"\"\n plist = ctypes.POINTER(ctypes.c_void_p)()\n size = ctypes.c_uint()\n check_call(_LIB.MXListDataIters(ctypes.byref(size), ctypes.byref(plist)))\n module_obj = sys.modules[__name__]\n for i in range(size.value):\n hdl = ctypes.c_void_p(plist[i])\n dataiter = _make_io_iterator(hdl)\n setattr(module_obj, dataiter.__name__, dataiter)\n\n_init_io_module()\n", "# coding: utf-8\n# pylint: disable=invalid-name, protected-access, too-many-arguments, global-statement\n\"\"\"Symbolic configuration API.\"\"\"\nfrom __future__ import absolute_import as _abs\n\nimport ctypes\nimport sys as _sys\nimport numpy as np\n\nfrom ..base import _LIB\nfrom ..base import c_array, py_str, c_str, mx_uint\nfrom ..base import NDArrayHandle, OpHandle\nfrom ..base import check_call\nfrom ..ndarray_doc import _build_doc\n\n_ndarray_cls = None\n\nclass NDArrayBase(object):\n \"\"\"Base data structure for ndarray\"\"\"\n __slots__ = [\"handle\", \"writable\"]\n # pylint: disable= no-member\n def __init__(self, handle, writable=True):\n \"\"\"initialize a new NDArray\n\n Parameters\n ----------\n handle : NDArrayHandle\n NDArray handle of C API\n \"\"\"\n if handle is not None:\n assert isinstance(handle, NDArrayHandle)\n self.handle = handle\n self.writable = writable\n\n def __del__(self):\n check_call(_LIB.MXNDArrayFree(self.handle))\n\n def __reduce__(self):\n return (_ndarray_cls, (None,), self.__getstate__())\n\n\n# pylint: disable=too-many-locals, invalid-name\ndef _make_ndarray_function(handle, name):\n \"\"\"Create a NDArray function from the FunctionHandle.\"\"\"\n real_name = ctypes.c_char_p()\n desc = ctypes.c_char_p()\n num_args = mx_uint()\n arg_names = ctypes.POINTER(ctypes.c_char_p)()\n arg_types = ctypes.POINTER(ctypes.c_char_p)()\n arg_descs = ctypes.POINTER(ctypes.c_char_p)()\n key_var_num_args = ctypes.c_char_p()\n ret_type = ctypes.c_char_p()\n\n check_call(_LIB.MXSymbolGetAtomicSymbolInfo(\n handle, ctypes.byref(real_name), ctypes.byref(desc),\n ctypes.byref(num_args),\n ctypes.byref(arg_names),\n ctypes.byref(arg_types),\n ctypes.byref(arg_descs),\n ctypes.byref(key_var_num_args),\n ctypes.byref(ret_type)))\n narg = int(num_args.value)\n func_name = name\n key_var_num_args = py_str(key_var_num_args.value)\n ret_type = py_str(ret_type.value) if ret_type.value is not None else ''\n doc_str = _build_doc(func_name,\n py_str(desc.value),\n [py_str(arg_names[i]) for i in range(narg)],\n [py_str(arg_types[i]) for i in range(narg)],\n [py_str(arg_descs[i]) for i in range(narg)],\n key_var_num_args,\n ret_type)\n arguments = []\n for i in range(num_args.value):\n dtype = py_str(arg_types[i])\n if not (dtype.startswith('NDArray') or\n dtype.startswith('Symbol') or\n dtype.startswith('ndarray-or-symbol')):\n arguments.append(py_str(arg_names[i]))\n\n # Definition of internal functions.\n def generic_ndarray_function(*args, **kwargs):\n \"\"\"Invoke this function by passing in parameters\n\n Parameters\n ----------\n *args\n Positional arguments of input scalars and NDArray\n out : NDArray or tuple of NDArray, optional\n Output NDArray, used to hold the output result.\n\n Returns\n -------\n out : NDArray\n The result NDArray(tuple) of result of computation.\n \"\"\"\n ndargs = []\n pos_args = []\n for i in args:\n if isinstance(i, NDArrayBase):\n ndargs.append(i)\n else:\n pos_args.append(str(i))\n\n if len(pos_args) > len(arguments):\n raise ValueError(\"Too many positional arguments\")\n kwargs.update(zip(arguments[:len(pos_args)], pos_args))\n if 'dtype' in kwargs:\n kwargs['dtype'] = np.dtype(kwargs['dtype']).name\n\n original_output = None\n if 'out' in kwargs:\n output_vars = kwargs['out']\n original_output = output_vars\n del kwargs['out']\n if isinstance(output_vars, NDArrayBase):\n output_vars = (output_vars,)\n num_output = ctypes.c_int(len(output_vars))\n output_vars = c_array(NDArrayHandle, [v.handle for v in output_vars])\n output_vars = ctypes.cast(output_vars, ctypes.POINTER(NDArrayHandle))\n else:\n output_vars = ctypes.POINTER(NDArrayHandle)()\n num_output = ctypes.c_int(0)\n\n check_call(_LIB.MXImperativeInvoke(\n handle,\n ctypes.c_int(len(ndargs)),\n c_array(NDArrayHandle, [i.handle for i in ndargs]),\n ctypes.byref(num_output),\n ctypes.byref(output_vars),\n ctypes.c_int(len(kwargs)),\n c_array(ctypes.c_char_p, [c_str(key) for key in kwargs.keys()]),\n c_array(ctypes.c_char_p, [c_str(str(i)) for i in kwargs.values()])))\n if original_output is not None:\n return original_output\n if num_output.value == 1:\n return _ndarray_cls(ctypes.cast(output_vars[0], NDArrayHandle))\n else:\n return [_ndarray_cls(ctypes.cast(output_vars[i], NDArrayHandle))\n for i in range(num_output.value)]\n # End of function declaration\n generic_ndarray_function.__name__ = func_name\n generic_ndarray_function.__doc__ = doc_str\n generic_ndarray_function.__module__ = 'mxnet.ndarray'\n return generic_ndarray_function\n\n\ndef _set_ndarray_class(cls):\n \"\"\"Set the symbolic class to be cls\"\"\"\n global _ndarray_cls\n _ndarray_cls = cls\n\n\n# pylint: enable=too-many-locals, invalid-name\ndef _init_ndarray_module(ndarray_class, root_namespace):\n \"\"\"List and add all the ndarray functions to current module.\"\"\"\n _set_ndarray_class(ndarray_class)\n plist = ctypes.POINTER(ctypes.c_char_p)()\n size = ctypes.c_uint()\n\n check_call(_LIB.MXListAllOpNames(ctypes.byref(size),\n ctypes.byref(plist)))\n op_names = []\n for i in range(size.value):\n op_names.append(py_str(plist[i]))\n\n module_obj = _sys.modules[\"%s.ndarray\" % root_namespace]\n module_internal = _sys.modules[\"%s._ndarray_internal\" % root_namespace]\n module_contrib = _sys.modules[\"%s.contrib.ndarray\" % root_namespace]\n for name in op_names:\n hdl = OpHandle()\n check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl)))\n function = _make_ndarray_function(hdl, name)\n if function.__name__.startswith('_contrib_'):\n function.__name__ = function.__name__[9:]\n function.__module__ = 'mxnet.contrib.ndarray'\n setattr(module_contrib, function.__name__, function)\n elif function.__name__.startswith('_'):\n setattr(module_internal, function.__name__, function)\n else:\n setattr(module_obj, function.__name__, function)\n" ]
[ [ "numpy.frombuffer", "numpy.arange", "numpy.random.shuffle" ], [ "numpy.dtype" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
miguelusque/cudf
[ "52f5b324cafba4e0be3e17b844d807ff8342fda4" ]
[ "python/cudf/cudf/core/column/timedelta.py" ]
[ "# Copyright (c) 2020, NVIDIA CORPORATION.\nfrom __future__ import annotations\n\nimport datetime as dt\nfrom numbers import Number\nfrom typing import Any, Sequence, Tuple, Union, cast\n\nimport numpy as np\nimport pandas as pd\nimport pyarrow as pa\nfrom nvtx import annotate\n\nimport cudf\nfrom cudf import _lib as libcudf\nfrom cudf._typing import (\n BinaryOperand,\n DatetimeLikeScalar,\n Dtype,\n DtypeObj,\n ScalarLike,\n)\nfrom cudf.core.buffer import Buffer\nfrom cudf.core.column import ColumnBase, column, string\nfrom cudf.core.column.datetime import _numpy_to_pandas_conversion\nfrom cudf.utils.dtypes import is_scalar, np_to_pa_dtype\nfrom cudf.utils.utils import _fillna_natwise\n\n_dtype_to_format_conversion = {\n \"timedelta64[ns]\": \"%D days %H:%M:%S\",\n \"timedelta64[us]\": \"%D days %H:%M:%S\",\n \"timedelta64[ms]\": \"%D days %H:%M:%S\",\n \"timedelta64[s]\": \"%D days %H:%M:%S\",\n}\n\n\nclass TimeDeltaColumn(column.ColumnBase):\n def __init__(\n self,\n data: Buffer,\n dtype: Dtype,\n size: int = None,\n mask: Buffer = None,\n offset: int = 0,\n null_count: int = None,\n ):\n \"\"\"\n Parameters\n ----------\n data : Buffer\n The Timedelta values\n dtype : np.dtype\n The data type\n size : int\n Size of memory allocation.\n mask : Buffer; optional\n The validity mask\n offset : int\n Data offset\n null_count : int, optional\n The number of null values.\n If None, it is calculated automatically.\n \"\"\"\n dtype = np.dtype(dtype)\n if data.size % dtype.itemsize:\n raise ValueError(\"Buffer size must be divisible by element size\")\n if size is None:\n size = data.size // dtype.itemsize\n size = size - offset\n super().__init__(\n data,\n size=size,\n dtype=dtype,\n mask=mask,\n offset=offset,\n null_count=null_count,\n )\n\n if not (self.dtype.type is np.timedelta64):\n raise TypeError(f\"{self.dtype} is not a supported duration type\")\n\n self._time_unit, _ = np.datetime_data(self.dtype)\n\n def __contains__(self, item: DatetimeLikeScalar) -> bool:\n try:\n item = np.timedelta64(item, self._time_unit)\n except ValueError:\n # If item cannot be converted to duration type\n # np.timedelta64 raises ValueError, hence `item`\n # cannot exist in `self`.\n return False\n return item.view(\"int64\") in self.as_numerical\n\n def to_arrow(self) -> pa.Array:\n mask = None\n if self.nullable:\n mask = pa.py_buffer(self.mask_array_view.copy_to_host())\n data = pa.py_buffer(self.as_numerical.data_array_view.copy_to_host())\n pa_dtype = np_to_pa_dtype(self.dtype)\n return pa.Array.from_buffers(\n type=pa_dtype,\n length=len(self),\n buffers=[mask, data],\n null_count=self.null_count,\n )\n\n def to_pandas(\n self, index=None, nullable: bool = False, **kwargs\n ) -> pd.Series:\n # Workaround until following issue is fixed:\n # https://issues.apache.org/jira/browse/ARROW-9772\n\n # Pandas supports only `timedelta64[ns]`, hence the cast.\n pd_series = pd.Series(\n self.astype(\"timedelta64[ns]\").to_array(\"NAT\"), copy=False\n )\n\n if index is not None:\n pd_series.index = index\n\n return pd_series\n\n def _binary_op_floordiv(\n self, rhs: BinaryOperand\n ) -> Tuple[\"column.ColumnBase\", BinaryOperand, DtypeObj]:\n lhs = self # type: column.ColumnBase\n if pd.api.types.is_timedelta64_dtype(rhs.dtype):\n common_dtype = determine_out_dtype(self.dtype, rhs.dtype)\n lhs = lhs.astype(common_dtype).astype(\"float64\")\n if isinstance(rhs, cudf.Scalar):\n if rhs.is_valid:\n rhs = np.timedelta64(rhs.value)\n rhs = rhs.astype(common_dtype).astype(\"float64\")\n else:\n rhs = cudf.Scalar(None, \"float64\")\n else:\n rhs = rhs.astype(common_dtype).astype(\"float64\")\n out_dtype = np.dtype(\"int64\")\n elif rhs.dtype.kind in (\"f\", \"i\", \"u\"):\n out_dtype = self.dtype\n else:\n raise TypeError(\n f\"Floor Division of {self.dtype} with {rhs.dtype} \"\n f\"cannot be performed.\"\n )\n\n return lhs, rhs, out_dtype\n\n def _binary_op_mul(self, rhs: BinaryOperand) -> DtypeObj:\n if rhs.dtype.kind in (\"f\", \"i\", \"u\"):\n out_dtype = self.dtype\n else:\n raise TypeError(\n f\"Multiplication of {self.dtype} with {rhs.dtype} \"\n f\"cannot be performed.\"\n )\n return out_dtype\n\n def _binary_op_mod(self, rhs: BinaryOperand) -> DtypeObj:\n if pd.api.types.is_timedelta64_dtype(rhs.dtype):\n out_dtype = determine_out_dtype(self.dtype, rhs.dtype)\n elif rhs.dtype.kind in (\"f\", \"i\", \"u\"):\n out_dtype = self.dtype\n else:\n raise TypeError(\n f\"Modulus of {self.dtype} with {rhs.dtype} \"\n f\"cannot be performed.\"\n )\n return out_dtype\n\n def _binary_op_eq_ne(self, rhs: BinaryOperand) -> DtypeObj:\n if pd.api.types.is_timedelta64_dtype(rhs.dtype):\n out_dtype = np.bool\n else:\n raise TypeError(\n f\"Equality of {self.dtype} with {rhs.dtype} \"\n f\"cannot be performed.\"\n )\n return out_dtype\n\n def _binary_op_lt_gt_le_ge(self, rhs: BinaryOperand) -> DtypeObj:\n if pd.api.types.is_timedelta64_dtype(rhs.dtype):\n return np.bool\n else:\n raise TypeError(\n f\"Invalid comparison between dtype={self.dtype}\"\n f\" and {rhs.dtype}\"\n )\n\n def _binary_op_truediv(\n self, rhs: BinaryOperand\n ) -> Tuple[\"column.ColumnBase\", BinaryOperand, DtypeObj]:\n lhs = self # type: column.ColumnBase\n if pd.api.types.is_timedelta64_dtype(rhs.dtype):\n common_dtype = determine_out_dtype(self.dtype, rhs.dtype)\n lhs = lhs.astype(common_dtype).astype(\"float64\")\n if isinstance(rhs, cudf.Scalar):\n if rhs.is_valid():\n rhs = rhs.value.astype(common_dtype).astype(\"float64\")\n else:\n rhs = cudf.Scalar(None, \"float64\")\n else:\n rhs = rhs.astype(common_dtype).astype(\"float64\")\n\n out_dtype = np.dtype(\"float64\")\n elif rhs.dtype.kind in (\"f\", \"i\", \"u\"):\n out_dtype = self.dtype\n else:\n raise TypeError(\n f\"Division of {self.dtype} with {rhs.dtype} \"\n f\"cannot be performed.\"\n )\n\n return lhs, rhs, out_dtype\n\n def binary_operator(\n self, op: str, rhs: BinaryOperand, reflect: bool = False\n ) -> \"column.ColumnBase\":\n lhs, rhs = self, rhs\n\n if op in (\"eq\", \"ne\"):\n out_dtype = self._binary_op_eq_ne(rhs)\n elif op in (\"lt\", \"gt\", \"le\", \"ge\"):\n out_dtype = self._binary_op_lt_gt_le_ge(rhs)\n elif op == \"mul\":\n out_dtype = self._binary_op_mul(rhs)\n elif op == \"mod\":\n out_dtype = self._binary_op_mod(rhs)\n elif op == \"truediv\":\n lhs, rhs, out_dtype = self._binary_op_truediv(rhs) # type: ignore\n elif op == \"floordiv\":\n lhs, rhs, out_dtype = self._binary_op_floordiv(rhs) # type: ignore\n op = \"truediv\"\n elif op == \"add\":\n out_dtype = _timedelta_add_result_dtype(lhs, rhs)\n elif op == \"sub\":\n out_dtype = _timedelta_sub_result_dtype(lhs, rhs)\n else:\n raise TypeError(\n f\"Series of dtype {self.dtype} cannot perform \"\n f\"the operation {op}\"\n )\n\n if reflect:\n lhs, rhs = rhs, lhs # type: ignore\n\n return binop(lhs, rhs, op=op, out_dtype=out_dtype)\n\n def normalize_binop_value(self, other) -> BinaryOperand:\n if isinstance(other, cudf.Scalar):\n return other\n\n if isinstance(other, np.ndarray) and other.ndim == 0:\n other = other.item()\n\n if isinstance(other, dt.timedelta):\n other = np.timedelta64(other)\n elif isinstance(other, pd.Timestamp):\n other = other.to_datetime64()\n elif isinstance(other, pd.Timedelta):\n other = other.to_timedelta64()\n if isinstance(other, np.timedelta64):\n other_time_unit = cudf.utils.dtypes.get_time_unit(other)\n if np.isnat(other):\n return cudf.Scalar(None, dtype=self.dtype)\n\n if other_time_unit not in (\"s\", \"ms\", \"ns\", \"us\"):\n other = other.astype(\"timedelta64[s]\")\n else:\n common_dtype = determine_out_dtype(self.dtype, other.dtype)\n other = other.astype(common_dtype)\n return cudf.Scalar(other)\n elif np.isscalar(other):\n return cudf.Scalar(other)\n else:\n raise TypeError(f\"cannot normalize {type(other)}\")\n\n @property\n def as_numerical(self) -> \"cudf.core.column.NumericalColumn\":\n return cast(\n \"cudf.core.column.NumericalColumn\",\n column.build_column(\n data=self.base_data,\n dtype=np.int64,\n mask=self.base_mask,\n offset=self.offset,\n size=self.size,\n ),\n )\n\n def default_na_value(self) -> ScalarLike:\n \"\"\"Returns the default NA value for this column\n \"\"\"\n return np.timedelta64(\"nat\", self.time_unit)\n\n @property\n def time_unit(self) -> str:\n return self._time_unit\n\n def fillna(\n self, fill_value: Any = None, method: str = None, dtype: Dtype = None\n ) -> TimeDeltaColumn:\n if fill_value is not None:\n if cudf.utils.utils.isnat(fill_value):\n return _fillna_natwise(self)\n col = self # type: column.ColumnBase\n if is_scalar(fill_value):\n if isinstance(fill_value, np.timedelta64):\n dtype = determine_out_dtype(self.dtype, fill_value.dtype)\n fill_value = fill_value.astype(dtype)\n col = col.astype(dtype)\n if not isinstance(fill_value, cudf.Scalar):\n fill_value = cudf.Scalar(fill_value, dtype=dtype)\n else:\n fill_value = column.as_column(fill_value, nan_as_null=False)\n return cast(TimeDeltaColumn, ColumnBase.fillna(col, fill_value))\n else:\n return super().fillna(method=method)\n\n def as_numerical_column(\n self, dtype: Dtype\n ) -> \"cudf.core.column.NumericalColumn\":\n return cast(\n \"cudf.core.column.NumericalColumn\", self.as_numerical.astype(dtype)\n )\n\n def as_datetime_column(\n self, dtype: Dtype, **kwargs\n ) -> \"cudf.core.column.DatetimeColumn\":\n raise TypeError(\n f\"cannot astype a timedelta from [{self.dtype}] to [{dtype}]\"\n )\n\n def as_string_column(\n self, dtype: Dtype, format=None\n ) -> \"cudf.core.column.StringColumn\":\n if format is None:\n format = _dtype_to_format_conversion.get(\n self.dtype.name, \"%D days %H:%M:%S\"\n )\n if len(self) > 0:\n return string._timedelta_to_str_typecast_functions[\n np.dtype(self.dtype)\n ](self, format=format)\n else:\n return cast(\n \"cudf.core.column.StringColumn\",\n column.column_empty(0, dtype=\"object\", masked=False),\n )\n\n def as_timedelta_column(self, dtype: Dtype, **kwargs) -> TimeDeltaColumn:\n dtype = np.dtype(dtype)\n if dtype == self.dtype:\n return self\n return libcudf.unary.cast(self, dtype=dtype)\n\n def mean(self, skipna=None, dtype: Dtype = np.float64) -> pd.Timedelta:\n return pd.Timedelta(\n self.as_numerical.mean(skipna=skipna, dtype=dtype),\n unit=self.time_unit,\n )\n\n def median(self, skipna: bool = None) -> pd.Timedelta:\n return pd.Timedelta(\n self.as_numerical.median(skipna=skipna), unit=self.time_unit\n )\n\n def quantile(\n self, q: Union[float, Sequence[float]], interpolation: str, exact: bool\n ) -> \"column.ColumnBase\":\n result = self.as_numerical.quantile(\n q=q, interpolation=interpolation, exact=exact\n )\n if isinstance(q, Number):\n return pd.Timedelta(result, unit=self.time_unit)\n return result.astype(self.dtype)\n\n def sum(\n self, skipna: bool = None, dtype: Dtype = None, min_count=0\n ) -> pd.Timedelta:\n if len(self) == 0:\n return pd.Timedelta(None, unit=self.time_unit)\n else:\n return pd.Timedelta(\n self.as_numerical.sum(\n skipna=skipna, dtype=dtype, min_count=min_count\n ),\n unit=self.time_unit,\n )\n\n def std(\n self, skipna: bool = None, ddof: int = 1, dtype: Dtype = np.float64\n ) -> pd.Timedelta:\n return pd.Timedelta(\n self.as_numerical.std(skipna=skipna, ddof=ddof, dtype=dtype),\n unit=self.time_unit,\n )\n\n def components(self, index=None) -> \"cudf.DataFrame\":\n \"\"\"\n Return a Dataframe of the components of the Timedeltas.\n\n Returns\n -------\n DataFrame\n\n Examples\n --------\n >>> s = pd.Series(pd.to_timedelta(np.arange(5), unit='s'))\n >>> s = cudf.Series([12231312123, 1231231231, 1123236768712, 2135656,\n ... 3244334234], dtype='timedelta64[ms]')\n >>> s\n 0 141 days 13:35:12.123\n 1 14 days 06:00:31.231\n 2 13000 days 10:12:48.712\n 3 0 days 00:35:35.656\n 4 37 days 13:12:14.234\n dtype: timedelta64[ms]\n >>> s.dt.components\n days hours minutes seconds milliseconds microseconds nanoseconds\n 0 141 13 35 12 123 0 0\n 1 14 6 0 31 231 0 0\n 2 13000 10 12 48 712 0 0\n 3 0 0 35 35 656 0 0\n 4 37 13 12 14 234 0 0\n \"\"\" # noqa: E501\n\n return cudf.DataFrame(\n data={\n \"days\": self\n // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"D\"], \"ns\")\n ),\n \"hours\": (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"D\"], \"ns\")\n )\n )\n // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"h\"], \"ns\")\n ),\n \"minutes\": (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"h\"], \"ns\")\n )\n )\n // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"m\"], \"ns\")\n ),\n \"seconds\": (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"m\"], \"ns\")\n )\n )\n // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"s\"], \"ns\")\n ),\n \"milliseconds\": (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"s\"], \"ns\")\n )\n )\n // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"ms\"], \"ns\")\n ),\n \"microseconds\": (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"ms\"], \"ns\")\n )\n )\n // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"us\"], \"ns\")\n ),\n \"nanoseconds\": (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"us\"], \"ns\")\n )\n )\n // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"ns\"], \"ns\")\n ),\n },\n index=index,\n )\n\n @property\n def days(self) -> \"cudf.core.column.NumericalColumn\":\n \"\"\"\n Number of days for each element.\n\n Returns\n -------\n NumericalColumn\n \"\"\"\n return self // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"D\"], \"ns\")\n )\n\n @property\n def seconds(self) -> \"cudf.core.column.NumericalColumn\":\n \"\"\"\n Number of seconds (>= 0 and less than 1 day).\n\n Returns\n -------\n NumericalColumn\n \"\"\"\n # This property must return the number of seconds (>= 0 and\n # less than 1 day) for each element, hence first performing\n # mod operation to remove the number of days and then performing\n # division operation to extract the number of seconds.\n\n return (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"D\"], \"ns\")\n )\n ) // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"s\"], \"ns\")\n )\n\n @property\n def microseconds(self) -> \"cudf.core.column.NumericalColumn\":\n \"\"\"\n Number of microseconds (>= 0 and less than 1 second).\n\n Returns\n -------\n NumericalColumn\n \"\"\"\n # This property must return the number of microseconds (>= 0 and\n # less than 1 second) for each element, hence first performing\n # mod operation to remove the number of seconds and then performing\n # division operation to extract the number of microseconds.\n\n return (\n self % np.timedelta64(_numpy_to_pandas_conversion[\"s\"], \"ns\")\n ) // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"us\"], \"ns\")\n )\n\n @property\n def nanoseconds(self) -> \"cudf.core.column.NumericalColumn\":\n \"\"\"\n Return the number of nanoseconds (n), where 0 <= n < 1 microsecond.\n\n Returns\n -------\n NumericalColumn\n \"\"\"\n # This property must return the number of nanoseconds (>= 0 and\n # less than 1 microsecond) for each element, hence first performing\n # mod operation to remove the number of microseconds and then\n # performing division operation to extract the number\n # of nanoseconds.\n\n return (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"us\"], \"ns\")\n )\n ) // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"ns\"], \"ns\")\n )\n\n\n@annotate(\"BINARY_OP\", color=\"orange\", domain=\"cudf_python\")\ndef binop(\n lhs: \"column.ColumnBase\",\n rhs: \"column.ColumnBase\",\n op: str,\n out_dtype: DtypeObj,\n) -> \"cudf.core.column.ColumnBase\":\n out = libcudf.binaryop.binaryop(lhs, rhs, op, out_dtype)\n return out\n\n\ndef determine_out_dtype(lhs_dtype: Dtype, rhs_dtype: Dtype) -> Dtype:\n if np.can_cast(np.dtype(lhs_dtype), np.dtype(rhs_dtype)):\n return rhs_dtype\n elif np.can_cast(np.dtype(rhs_dtype), np.dtype(lhs_dtype)):\n return lhs_dtype\n else:\n raise TypeError(f\"Cannot type-cast {lhs_dtype} and {rhs_dtype}\")\n\n\ndef _timedelta_add_result_dtype(\n lhs: BinaryOperand, rhs: BinaryOperand\n) -> Dtype:\n if pd.api.types.is_timedelta64_dtype(rhs.dtype):\n out_dtype = determine_out_dtype(lhs.dtype, rhs.dtype)\n elif pd.api.types.is_datetime64_dtype(rhs.dtype):\n units = [\"s\", \"ms\", \"us\", \"ns\"]\n lhs_time_unit = cudf.utils.dtypes.get_time_unit(lhs)\n lhs_unit = units.index(lhs_time_unit)\n rhs_time_unit = cudf.utils.dtypes.get_time_unit(rhs)\n rhs_unit = units.index(rhs_time_unit)\n out_dtype = np.dtype(f\"datetime64[{units[max(lhs_unit, rhs_unit)]}]\")\n else:\n raise TypeError(\n f\"Addition of {lhs.dtype} with {rhs.dtype} \"\n f\"cannot be performed.\"\n )\n\n return out_dtype\n\n\ndef _timedelta_sub_result_dtype(\n lhs: BinaryOperand, rhs: BinaryOperand\n) -> Dtype:\n if pd.api.types.is_timedelta64_dtype(\n lhs.dtype\n ) and pd.api.types.is_timedelta64_dtype(rhs.dtype):\n out_dtype = determine_out_dtype(lhs.dtype, rhs.dtype)\n elif pd.api.types.is_timedelta64_dtype(\n rhs.dtype\n ) and pd.api.types.is_datetime64_dtype(lhs.dtype):\n units = [\"s\", \"ms\", \"us\", \"ns\"]\n lhs_time_unit = cudf.utils.dtypes.get_time_unit(lhs)\n lhs_unit = units.index(lhs_time_unit)\n rhs_time_unit = cudf.utils.dtypes.get_time_unit(rhs)\n rhs_unit = units.index(rhs_time_unit)\n out_dtype = np.dtype(f\"datetime64[{units[max(lhs_unit, rhs_unit)]}]\")\n else:\n raise TypeError(\n f\"Subtraction of {lhs.dtype} with {rhs.dtype} \"\n f\"cannot be performed.\"\n )\n\n return out_dtype\n" ]
[ [ "numpy.datetime_data", "pandas.api.types.is_datetime64_dtype", "numpy.isnat", "numpy.dtype", "pandas.Timedelta", "numpy.timedelta64", "numpy.isscalar", "pandas.api.types.is_timedelta64_dtype" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
zbmain/PGL
[ "dbded6a1543248b0a33c05eb476ddc513401a774", "dbded6a1543248b0a33c05eb476ddc513401a774", "dbded6a1543248b0a33c05eb476ddc513401a774", "dbded6a1543248b0a33c05eb476ddc513401a774", "dbded6a1543248b0a33c05eb476ddc513401a774" ]
[ "legacy/examples/distribute_deepwalk/reader.py", "ogb_examples/lsc/MAG240M/dataset/data_generator.py", "examples/kddcup2021/WikiKG90M/feature/walk_probability/h2r.py", "examples/deploy_gnn/convert_to_static.py", "legacy/pgl/tests/test_metapath_randomwalk.py" ]
[ "# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\n Reader file.\n\"\"\"\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport time\nimport io\nimport os\n\nimport numpy as np\nimport paddle\nfrom pgl.utils.logger import log\nfrom pgl.sample import node2vec_sample\nfrom pgl.sample import deepwalk_sample\nfrom pgl.sample import alias_sample\nfrom pgl.graph_kernel import skip_gram_gen_pair\nfrom pgl.graph_kernel import alias_sample_build_table\nfrom pgl.utils import mp_reader\n\n\nclass DeepwalkReader(object):\n def __init__(self,\n graph,\n batch_size=512,\n walk_len=40,\n win_size=5,\n neg_num=5,\n train_files=None,\n walkpath_files=None,\n neg_sample_type=\"average\"):\n \"\"\"\n Args:\n walkpath_files: if is not None, read walk path from walkpath_files\n \"\"\"\n self.graph = graph\n self.batch_size = batch_size\n self.walk_len = walk_len\n self.win_size = win_size\n self.neg_num = neg_num\n self.train_files = train_files\n self.walkpath_files = walkpath_files\n self.neg_sample_type = neg_sample_type\n\n def walk_from_files(self):\n bucket = []\n while True:\n for filename in self.walkpath_files:\n with io.open(filename) as inf:\n for line in inf:\n #walk = [hash_map[x] for x in line.strip('\\n\\t').split('\\t')]\n walk = [int(x) for x in line.strip('\\n\\t').split('\\t')]\n bucket.append(walk)\n if len(bucket) == self.batch_size:\n yield bucket\n bucket = []\n if len(bucket):\n yield bucket\n\n def walk_from_graph(self):\n def node_generator():\n if self.train_files is None:\n while True:\n for nodes in self.graph.node_batch_iter(self.batch_size):\n yield nodes\n else:\n nodes = []\n while True:\n for filename in self.train_files:\n with io.open(filename) as inf:\n for line in inf:\n node = int(line.strip('\\n\\t'))\n nodes.append(node)\n if len(nodes) == self.batch_size:\n yield nodes\n nodes = []\n if len(nodes):\n yield nodes\n\n if \"alias\" in self.graph.node_feat and \"events\" in self.graph.node_feat:\n log.info(\"Deepwalk using alias sample\")\n for nodes in node_generator():\n if \"alias\" in self.graph.node_feat and \"events\" in self.graph.node_feat:\n walks = deepwalk_sample(self.graph, nodes, self.walk_len,\n \"alias\", \"events\")\n else:\n walks = deepwalk_sample(self.graph, nodes, self.walk_len)\n yield walks\n\n def walk_generator(self):\n if self.walkpath_files is not None:\n for i in self.walk_from_files():\n yield i\n else:\n for i in self.walk_from_graph():\n yield i\n\n def __call__(self):\n np.random.seed(os.getpid())\n if self.neg_sample_type == \"outdegree\":\n outdegree = self.graph.outdegree()\n distribution = 1. * outdegree / outdegree.sum()\n alias, events = alias_sample_build_table(distribution)\n max_len = int(self.batch_size * self.walk_len * (\n (1 + self.win_size) - 0.3))\n for walks in self.walk_generator():\n try:\n src_list, pos_list = [], []\n for walk in walks:\n s, p = skip_gram_gen_pair(walk, self.win_size)\n src_list.append(s[:max_len]), pos_list.append(p[:max_len])\n src = [s for x in src_list for s in x]\n pos = [s for x in pos_list for s in x]\n src = np.array(src, dtype=np.int64),\n pos = np.array(pos, dtype=np.int64)\n src, pos = np.reshape(src, [-1, 1, 1]), np.reshape(pos,\n [-1, 1, 1])\n\n neg_sample_size = [len(pos), self.neg_num, 1]\n if src.shape[0] == 0:\n continue\n if self.neg_sample_type == \"average\":\n negs = np.random.randint(\n low=0, high=self.graph.num_nodes, size=neg_sample_size)\n elif self.neg_sample_type == \"outdegree\":\n negs = alias_sample(neg_sample_size, alias, events)\n elif self.neg_sample_type == \"inbatch\":\n pass\n dst = np.concatenate([pos, negs], 1)\n # [batch_size, 1, 1] [batch_size, neg_num+1, 1]\n yield src[:max_len], dst[:max_len]\n except Exception as e:\n log.exception(e)\n", "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport tqdm\nimport yaml\nimport pgl\nimport time\nimport copy\nimport numpy as np\nimport os.path as osp\nfrom pgl.utils.logger import log\nfrom pgl.graph import Graph\nfrom pgl import graph_kernel\nfrom pgl.sampling.custom import subgraph\nfrom ogb.lsc import MAG240MDataset, MAG240MEvaluator\nfrom dataset.base_dataset import BaseDataGenerator\nimport time\n\n\nclass MAG240M(object):\n \"\"\"Iterator\"\"\"\n\n def __init__(self, data_dir, seed=123):\n self.data_dir = data_dir\n self.num_features = 768\n self.num_classes = 153\n self.seed = seed\n\n def prepare_data(self):\n dataset = MAG240MDataset(self.data_dir)\n edge_path = f'{dataset.dir}/paper_to_paper_symmetric_pgl'\n\n t = time.perf_counter()\n if not osp.exists(edge_path):\n log.info('Converting adjacency matrix...')\n edge_index = dataset.edge_index('paper', 'cites', 'paper')\n edge_index = edge_index.T\n\n edges_new = np.zeros((edge_index.shape[0], 2))\n edges_new[:, 0] = edge_index[:, 1]\n edges_new[:, 1] = edge_index[:, 0]\n\n edge_index = np.vstack((edge_index, edges_new))\n edge_index = np.unique(edge_index, axis=0)\n\n graph = Graph(edge_index, sorted=True)\n graph.adj_dst_index\n graph.dump(edge_path)\n log.info(f'Done! [{time.perf_counter() - t:.2f}s]')\n\n np.random.seed(self.seed)\n self.train_idx = dataset.get_idx_split('train')\n np.random.shuffle(self.train_idx)\n\n self.val_idx = dataset.get_idx_split('valid')\n self.test_idx = dataset.get_idx_split('test')\n\n self.x = dataset.paper_feat\n self.y = dataset.all_paper_label\n\n self.graph = Graph.load(edge_path, mmap_mode='r+')\n log.info(f'Done! [{time.perf_counter() - t:.2f}s]')\n\n @property\n def train_examples(self, ):\n # Filters\n trainer_id = int(os.getenv(\"PADDLE_TRAINER_ID\", \"0\"))\n trainer_num = int(os.getenv(\"PADDLE_TRAINERS_NUM\", \"1\"))\n count_line = 0\n\n #np.random.shuffle(self.train_idx)\n for idx in self.train_idx:\n count_line += 1\n if count_line % trainer_num == trainer_id:\n yield idx\n\n @property\n def eval_examples(self, ):\n for idx in self.val_idx:\n yield idx\n\n @property\n def test_examples(self, ):\n for idx in self.test_idx:\n yield idx\n\n\ndef add_self_loop(graph, sub_nodes=None):\n '''add_self_loop_for_subgraph\n '''\n assert not graph.is_tensor(), \"You must call Graph.numpy() first.\"\n\n if sub_nodes is not None:\n self_loop_edges = np.zeros((sub_nodes.shape[0], 2))\n self_loop_edges[:, 0] = self_loop_edges[:, 1] = sub_nodes\n else:\n self_loop_edges = np.zeros((graph.num_nodes, 2))\n self_loop_edges[:, 0] = self_loop_edges[:, 1] = np.arange(\n graph.num_nodes)\n edges = np.vstack((graph.edges, self_loop_edges))\n edges = np.unique(edges, axis=0)\n new_g = Graph(\n edges=edges,\n num_nodes=graph.num_nodes,\n node_feat=graph.node_feat,\n edge_feat=graph.edge_feat)\n return new_g\n\n\ndef traverse(item):\n \"\"\"traverse\n \"\"\"\n if isinstance(item, list) or isinstance(item, np.ndarray):\n for i in iter(item):\n for j in traverse(i):\n yield j\n else:\n yield item\n\n\ndef flat_node_and_edge(nodes):\n \"\"\"flat_node_and_edge\n \"\"\"\n nodes = list(set(traverse(nodes)))\n return nodes\n\n\ndef neighbor_sample(graph, nodes, samples):\n assert not graph.is_tensor(), \"You must call Graph.numpy() first.\"\n\n graph_list = []\n for max_deg in samples:\n start_nodes = copy.deepcopy(nodes)\n edges = []\n if max_deg == -1:\n pred_nodes = graph.predecessor(start_nodes)\n else:\n pred_nodes = graph.sample_predecessor(\n start_nodes, max_degree=max_deg)\n\n for dst_node, src_nodes in zip(start_nodes, pred_nodes):\n for src_node in src_nodes:\n edges.append((src_node, dst_node))\n\n neigh_nodes = [start_nodes, pred_nodes]\n neigh_nodes = flat_node_and_edge(neigh_nodes)\n\n from_reindex = {x: i for i, x in enumerate(neigh_nodes)}\n sub_node_index = graph_kernel.map_nodes(nodes, from_reindex)\n\n sg = subgraph(\n graph,\n nodes=neigh_nodes,\n edges=edges,\n with_node_feat=False,\n with_edge_feat=False)\n\n # sg = add_self_loop(sg, sub_node_index)\n sg = add_self_loop(sg, sub_node_index)\n\n graph_list.append((sg, neigh_nodes, sub_node_index))\n nodes = neigh_nodes\n\n graph_list = graph_list[::-1]\n return graph_list\n\n\nclass DataGenerator(BaseDataGenerator):\n def __init__(self, dataset, samples, batch_size, num_workers, data_type):\n\n super(DataGenerator, self).__init__(\n buf_size=1000,\n batch_size=batch_size,\n num_workers=num_workers,\n shuffle=True if data_type == 'train' else False)\n\n self.dataset = dataset\n self.samples = samples\n if data_type == 'train':\n self.line_examples = self.dataset.train_examples\n elif data_type == 'eval':\n self.line_examples = self.dataset.eval_examples\n else:\n self.line_examples = self.dataset.test_examples\n\n def batch_fn(self, batch_nodes):\n\n graph_list = neighbor_sample(self.dataset.graph, batch_nodes,\n self.samples)\n\n neigh_nodes = graph_list[0][1]\n\n # x = self.dataset.x[neigh_nodes]\n\n y = self.dataset.y[batch_nodes]\n return graph_list, neigh_nodes, y\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n########################################################################\n#\n# Copyright (c) 2021 Baidu.com, Inc. All Rights Reserved\n#\n# File: a.py\n# Author: suweiyue([email protected])\n# Date: 2021/04/13 21:58:37\n#\n########################################################################\n\"\"\"\n Comment.\n\"\"\"\n\nimport numpy as np\nimport pickle\nfrom tqdm import tqdm\n\n\ntrain_hrt = np.load(\"./dataset/wikikg90m_kddcup2021/processed/train_hrt.npy\", mmap_mode=\"r\")\n\ndata = dict()\n\nfor h, r, t in tqdm(train_hrt):\n if h not in data:\n data[h] = dict()\n if not r in data[h]:\n data[h][r] = 1\n else:\n data[h][r] += 1\n\ndel train_hrt\n\nfor h in data:\n h_sum = sum(data[h].values())\n for r in data[h]:\n data[h][r] /= h_sum\n\npickle.dump(data, open(\"feature_output/h2r_prob2.pkl\", \"wb\"))\n", "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\n\nimport paddle\nimport pgl\npaddle.enable_static()\n\nimport paddle.nn as nn\nimport pgl.nn as gnn\nfrom ogb.utils import smiles2graph\nimport paddle.static as static\n\ngraph_obj = smiles2graph('O=C1C=CC(O1)C(c1ccccc1C)O')\n\n\nclass GNNModel(nn.Layer):\n def __init__(self, input_size, output_size, num_layers=3):\n super(GNNModel, self).__init__()\n self.conv_fn = nn.LayerList()\n self.conv_fn.append(gnn.GCNConv(input_size, output_size))\n for i in range(num_layers - 1):\n self.conv_fn.append(gnn.GCNConv(output_size, output_size))\n self.pool_fn = gnn.GraphPool(\"sum\")\n\n def forward(self, num_nodes, edges, feature):\n graph = pgl.Graph(num_nodes=num_nodes, edges=edges)\n for fn in self.conv_fn:\n feature = fn(graph, feature)\n output = self.pool_fn(graph, feature)\n return output\n\n\n# Build Model in Static\nmodel = GNNModel(graph_obj[\"node_feat\"].shape[-1], 10)\n\nnum_nodes = static.data(name='num_nodes', shape=[-1], dtype='int32')\nedges = static.data(name='edges', shape=[-1, 2], dtype='int32')\nfeature = static.data(\n name=\"feature\",\n shape=[-1, graph_obj[\"node_feat\"].shape[-1]],\n dtype=\"float32\")\n\noutput = model(num_nodes, edges, feature)\n\nplace = paddle.CPUPlace()\nexe = static.Executor(place)\nexe.run(static.default_startup_program())\n\n# Load DyGraph Model\nstate_dict = paddle.load(\"gnn.pdparam\")\nmodel.set_state_dict(state_dict)\n\nprog = static.default_main_program()\n\nfeed_dict = {\n \"num_nodes\": np.array(\n [graph_obj[\"node_feat\"].shape[0]], dtype=\"int32\"),\n \"edges\": np.array(\n graph_obj[\"edge_index\"].T, dtype=\"int32\"),\n \"feature\": graph_obj[\"node_feat\"].astype(\"float32\")\n}\n\nout = exe.run(prog, feed=feed_dict, fetch_list=[output])\nprint(out)\n", "# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"test_metapath_randomwalk\"\"\"\nimport time\nimport unittest\nimport json\nimport os\n\nimport numpy as np\nfrom pgl.sample import metapath_randomwalk\nfrom pgl.graph import Graph\nfrom pgl import heter_graph\n\nnp.random.seed(1)\n\n\nclass MetapathRandomwalkTest(unittest.TestCase):\n \"\"\"metapath_randomwalk test\n \"\"\"\n\n def setUp(self):\n edges = {}\n # for test no successor\n edges['c2p'] = [(1, 4), (0, 5), (1, 9), (1, 8), (2, 8), (2, 5), (3, 6),\n (3, 7), (3, 4), (3, 8)]\n edges['p2c'] = [(v, u) for u, v in edges['c2p']]\n edges['p2a'] = [(4, 10), (4, 11), (4, 12), (4, 14), (4, 13), (6, 12),\n (6, 11), (6, 14), (7, 12), (7, 11), (8, 14), (9, 10)]\n edges['a2p'] = [(v, u) for u, v in edges['p2a']]\n\n # for test speed\n # edges['c2p'] = [(0, 4), (0, 5), (1, 9), (1,8), (2,8), (2,5), (3,6), (3,7), (3,4), (3,8)]\n # edges['p2c'] = [(v,u) for u, v in edges['c2p']]\n # edges['p2a'] = [(4,10), (4,11), (4,12), (4,14), (5,13), (6,13), (6,11), (6,14), (7,12), (7,11), (8,14), (9,13)]\n # edges['a2p'] = [(v,u) for u, v in edges['p2a']]\n\n self.node_types = ['c' for _ in range(4)] + [\n 'p' for _ in range(6)\n ] + ['a' for _ in range(5)]\n node_types = [(i, t) for i, t in enumerate(self.node_types)]\n\n self.graph = heter_graph.HeterGraph(\n num_nodes=len(node_types), edges=edges, node_types=node_types)\n\n def test_metapath_randomwalk(self):\n meta_path = 'c2p-p2a-a2p-p2c'\n path = ['c', 'p', 'a', 'p', 'c']\n start_nodes = [0, 1, 2, 3]\n walk_len = 10\n walks = metapath_randomwalk(\n graph=self.graph,\n start_nodes=start_nodes,\n metapath=meta_path,\n walk_length=walk_len)\n\n self.assertEqual(len(walks), 4)\n\n for walk in walks:\n for i in range(len(walk)):\n idx = i % (len(path) - 1)\n self.assertEqual(self.node_types[walk[i]], path[idx])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.concatenate", "numpy.array", "numpy.reshape", "numpy.random.randint" ], [ "numpy.random.seed", "numpy.unique", "numpy.arange", "numpy.random.shuffle", "numpy.zeros", "numpy.vstack" ], [ "numpy.load" ], [ "numpy.array" ], [ "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
guoqingbao/DeepAdipose
[ "62af7a767f8f0f91e06b3f0b556dde5f9ead5d32" ]
[ "DICOM2TIF.py" ]
[ "import numpy as np\nimport pandas as pd\nimport SimpleITK as itk # simpleitk is required\n\n\nimport gc\ngc.enable()\n\n# path of dicom\ndata_path = \"./data/dicom/\" # folder contains all dicoms\noutput_path = \"./data/tiff/\" # output folder for tiff files\n\ndata_path = './DICOMs/'\noutput_path = './OutputTiff/'\n\n\nimport os\nbackIndex = 0\npath_lst = [f.path +\"/\" for f in os.scandir(data_path) if f.is_dir() ] \n\n#convert dicom to tiffs\nimport yaml\nd = {}\nindex = 0\ncur =0\n\ntotal = len(path_lst)\nfor item in path_lst:\n print(item)\n if index + 1 < backIndex:\n index = index + 1\n continue\n \n print( \"Reading Dicom directory:\", item )\n lef = item[len(data_path):]\n pa = lef[0:lef.find(\"/\")]\n if os.path.exists(output_path + pa + \".tif\"):\n print(\"Skipping \", item)\n else:\n reader = itk.ImageSeriesReader()\n\n dicom_names = reader.GetGDCMSeriesFileNames(item)\n reader.SetFileNames(dicom_names)\n reader.MetaDataDictionaryArrayUpdateOn()\n reader.LoadPrivateTagsOn()\n\n image = reader.Execute()\n\n \n for k in reader.GetMetaDataKeys(slice=0):\n v = reader.GetMetaData(key=k,slice=0)\n d[k] = v\n\n np.save(output_path + pa + \".npy\", np.array(d))\n\n size = image.GetSize()\n\n print( \"Image size:\", size[0], size[1], size[2] )\n\n\n a = yaml.load(str(np.array(d)))\n images = itk.GetArrayFromImage(image).astype(np.int16)\n images[images < -1024] = -1024\n if a['0020|0013'] == '1 ': #do not need to flip\n del image\n image = itk.GetImageFromArray(images)\n print( \"Writing image:\", output_path + pa + \".tif\" )\n itk.WriteImage( image, output_path + pa + \".tif\" )\n del reader\n del image\n del images\n else:\n # some of the cases need to flip\n print( \"Flipping image...\")\n images2 = itk.GetImageFromArray(np.flip(images,0))\n print( \"Writing image:\", output_path + pa + \".tif\" )\n\n itk.WriteImage( images2, output_path + pa + \".tif\" )\n del reader\n del image\n del images\n del images2\n gc.collect()\n print(\"Writing down.\")\n index += 1\n if cur != int(index/total *100):\n cur = int(index/total *100)\n print(\"Progress {} %, curIndex {}\".format(cur, index))\n \n\n\n# import pickle\n# for item in path_lst:\n# # print(item)\n# lef = item[len(data_path):]\n# pa = lef[0:lef.find(\"/\")]\n# print(output_path + pa + \".npy\")\n# pkl = np.load(open(output_path + pa + \".npy\", \"rb\"), allow_pickle=True)\n\n# pickle.dump(pkl, open(output_path + pa + \".npy2\",\"wb\"), protocol=2)\n\n\n\n" ]
[ [ "numpy.array", "numpy.flip" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sarahyurick/dask-sql
[ "4dab94973c0285b1f9c49e38044f8df5333aa8ae" ]
[ "dask_sql/physical/rel/custom/create_experiment.py" ]
[ "import logging\n\nimport dask.dataframe as dd\nimport pandas as pd\n\nfrom dask_sql.datacontainer import ColumnContainer, DataContainer\nfrom dask_sql.java import org\nfrom dask_sql.physical.rel.base import BaseRelPlugin\nfrom dask_sql.utils import convert_sql_kwargs, import_class\n\nlogger = logging.getLogger(__name__)\n\n\nclass CreateExperimentPlugin(BaseRelPlugin):\n \"\"\"\n Creates an Experiment for hyperparameter tuning or automl like behaviour,\n i.e evaluates models with different hyperparameters and registers the best performing\n model in the context with the name same as experiment name,\n which can be used for prediction\n\n sql syntax:\n CREATE EXPERIMENT <name> WITH ( key = value )\n AS <some select query>\n\n OPTIONS:\n * model_class: Full path to the class of the model which has to be tuned.\n Any model class with sklearn interface is valid, but might or\n might not work well with Dask dataframes.\n Have a look into the\n [dask-ml documentation](https://ml.dask.org/index.html)\n for more information on which models work best.\n You might need to install necessary packages to use\n the models.\n * experiment_class : Full path of the Hyperparameter tuner\n from dask_ml, choose dask tuner class carefully based on what you\n exactly need (memory vs compute constrains), refer:\n [dask-ml documentation](https://ml.dask.org/hyper-parameter-search.html)\n (for tuning hyperparameter of the models both model_class and experiment class are\n required parameters.)\n * tune_parameters:\n Key-value of pairs of Hyperparameters to tune, i.e Search Space for\n particular model to tune\n * automl_class : Full path of the class which is sklearn compatible and\n able to distribute work to dask clusters, currently tested with\n tpot automl framework.\n Refer : [Tpot example](https://examples.dask.org/machine-learning/tpot.html)\n * target_column: Which column from the data to use as target.\n Currently this parameter is required field, because tuning and automl\n behaviour is implemented only for supervised algorithms.\n * automl_kwargs:\n Key-value pairs of arguments to be passed to automl class .\n Refer : [Using Tpot parameters](https://epistasislab.github.io/tpot/using/)\n * experiment_kwargs:\n Use this parameter for passing any keyword arguments to experiment class\n * tune_fit_kwargs:\n Use this parameter for passing any keyword arguments to experiment.fit() method\n\n example:\n for Hyperparameter tuning : (Train and evaluate same model with different parameters)\n\n CREATE EXPERIMENT my_exp WITH(\n model_class = 'sklearn.ensemble.GradientBoostingClassifier',\n experiment_class = 'dask_ml.model_selection.GridSearchCV',\n tune_parameters = (n_estimators = ARRAY [16, 32, 2],\n learning_rate = ARRAY [0.1,0.01,0.001],\n max_depth = ARRAY [3,4,5,10]\n ),\n target_column = 'target'\n ) AS (\n SELECT x, y, x*y > 0 AS target\n FROM timeseries\n LIMIT 100\n )\n\n for automl : (Train different different model with different parameter)\n\n CREATE EXPERIMENT my_exp WITH (\n automl_class = 'tpot.TPOTClassifier',\n automl_kwargs = (population_size = 2 ,\n generations=2,\n cv=2,\n n_jobs=-1,\n use_dask=True,\n max_eval_time_mins=1),\n target_column = 'target'\n ) AS (\n SELECT x, y, x*y > 0 AS target\n FROM timeseries\n LIMIT 100\n )\n\n \"\"\"\n\n class_name = \"com.dask.sql.parser.SqlCreateExperiment\"\n\n def convert(\n self, sql: \"org.apache.calcite.sql.SqlNode\", context: \"dask_sql.Context\"\n ) -> DataContainer:\n select = sql.getSelect()\n schema_name, experiment_name = context.fqn(sql.getExperimentName())\n kwargs = convert_sql_kwargs(sql.getKwargs())\n\n if experiment_name in context.schema[schema_name].experiments:\n if sql.getIfNotExists():\n return\n elif not sql.getReplace():\n raise RuntimeError(\n f\"A experiment with the name {experiment_name} is already present.\"\n )\n\n logger.debug(\n f\"Creating Experiment {experiment_name} from query {select} with options {kwargs}\"\n )\n model_class = None\n automl_class = None\n experiment_class = None\n if \"model_class\" in kwargs:\n model_class = kwargs.pop(\"model_class\")\n # when model class was provided, must provide experiment_class also for tuning\n if \"experiment_class\" not in kwargs:\n raise ValueError(\n f\"Parameters must include a 'experiment_class' parameter for tuning {model_class}.\"\n )\n experiment_class = kwargs.pop(\"experiment_class\")\n elif \"automl_class\" in kwargs:\n automl_class = kwargs.pop(\"automl_class\")\n else:\n raise ValueError(\n \"Parameters must include a 'model_class' or 'automl_class' parameter.\"\n )\n target_column = kwargs.pop(\"target_column\", \"\")\n tune_fit_kwargs = kwargs.pop(\"tune_fit_kwargs\", {})\n parameters = kwargs.pop(\"tune_parameters\", {})\n experiment_kwargs = kwargs.pop(\"experiment_kwargs\", {})\n automl_kwargs = kwargs.pop(\"automl_kwargs\", {})\n logger.info(parameters)\n\n select_query = context._to_sql_string(select)\n training_df = context.sql(select_query)\n if not target_column:\n raise ValueError(\n \"Unsupervised Algorithm cannot be tuned Automatically,\"\n \"Consider providing 'target column'\"\n )\n non_target_columns = [\n col for col in training_df.columns if col != target_column\n ]\n X = training_df[non_target_columns]\n y = training_df[target_column]\n\n if model_class and experiment_class:\n try:\n ModelClass = import_class(model_class)\n except ImportError:\n raise ValueError(\n f\"Can not import model {model_class}. Make sure you spelled it correctly and have installed all packages.\"\n )\n try:\n ExperimentClass = import_class(experiment_class)\n except ImportError:\n raise ValueError(\n f\"Can not import tuner {experiment_class}. Make sure you spelled it correctly and have installed all packages.\"\n )\n\n try:\n from dask_ml.wrappers import ParallelPostFit\n except ImportError: # pragma: no cover\n raise ValueError(\n \"dask_ml must be installed to use automl and tune hyperparameters\"\n )\n\n model = ModelClass()\n\n search = ExperimentClass(model, {**parameters}, **experiment_kwargs)\n logger.info(tune_fit_kwargs)\n search.fit(X, y, **tune_fit_kwargs)\n df = pd.DataFrame(search.cv_results_)\n df[\"model_class\"] = model_class\n\n context.register_model(\n experiment_name,\n ParallelPostFit(estimator=search.best_estimator_),\n X.columns,\n schema_name=schema_name,\n )\n\n if automl_class:\n\n try:\n AutoMLClass = import_class(automl_class)\n except ImportError:\n raise ValueError(\n f\"Can not import automl model {automl_class}. Make sure you spelled it correctly and have installed all packages.\"\n )\n\n try:\n from dask_ml.wrappers import ParallelPostFit\n except ImportError: # pragma: no cover\n raise ValueError(\n \"dask_ml must be installed to use automl and tune hyperparameters\"\n )\n\n automl = AutoMLClass(**automl_kwargs)\n # should be avoided if data doesn't fit in memory\n automl.fit(X.compute(), y.compute())\n df = (\n pd.DataFrame(automl.evaluated_individuals_)\n .T.reset_index()\n .rename({\"index\": \"models\"}, axis=1)\n )\n\n context.register_model(\n experiment_name,\n ParallelPostFit(estimator=automl.fitted_pipeline_),\n X.columns,\n schema_name=schema_name,\n )\n\n context.register_experiment(\n experiment_name, experiment_results=df, schema_name=schema_name\n )\n cc = ColumnContainer(df.columns)\n dc = DataContainer(dd.from_pandas(df, npartitions=1), cc)\n return dc\n" ]
[ [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
ainfosec/gr-j2497
[ "f5a325a9e8089fea28580a4462a66c91503e5c1a" ]
[ "python/j2497_decoder_for_tagger.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# MIT License\n# \n# Copyright (c) 2019, 2020 Assured Information Security, Inc.\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# \n\nimport numpy\nfrom gnuradio import gr\nimport pmt\nimport socket\n\nclass j2497_decoder_for_tagger(gr.sync_block):\n \"\"\"\n docstring for block j2497_decoder_for_tagger\n \"\"\"\n def __init__(self,do_udp,udp_port):\n gr.sync_block.__init__(self,\n name=\"j2497_decoder_for_tagger\",\n in_sig=[numpy.float32],\n out_sig=[])\n \n self.message_port_register_out(pmt.intern(\"out\"))\n self.start_tag = 0\n self.end_tag = 0\n self.if_data = numpy.array([], dtype=numpy.float32)\n self.do_analysis = False\n self.message_number = 0\n self.prev_time = 0\n self.do_udp = do_udp\n self.udp_port = udp_port\n \n # Create UDP Socket\n if self.do_udp:\n self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n \n\n def work(self, input_items, output_items):\n in0 = input_items[0]\n in0_len = len(in0)\n window_start = self.nitems_read(0)\n\n # Locate Tags\n tags = self.get_tags_in_window(0, 0, in0_len, pmt.string_to_symbol(\"burst\"))\n\n # Tag Exists\n for tag in tags: #.offset, .key, .value\n \n # Record on Start\n if str(tag.value) == \"start\":\n self.start_tag = tag.offset\n self.if_data = numpy.append(self.if_data, in0[self.start_tag-window_start:])\n\n # Stop Recording on Stop\n if str(tag.value) == \"end\":\n self.end_tag = tag.offset\n burst_size = self.end_tag - self.start_tag\n\n # Perfect Size\n if burst_size > 4000 and burst_size < 50000: # 1 Sync + 1 MID + 20? Characters + 1 Checksum + Gap = 23 characters * 10 bits * 100 us = 23000 + Gap\n self.do_analysis = True\n\n # Multiple Windows\n if len(self.if_data) > 0:\n self.if_data = numpy.append(self.if_data, in0[:self.end_tag-window_start])\n \n # One Window\n else:\n self.if_data = in0[self.start_tag-window_start:self.end_tag-window_start]\n\n # Ignore and Reset\n else:\n self.start_tag = 0\n self.end_tag = 0\n self.if_data = numpy.array([], dtype=numpy.float32)\n\n # Whole Window with no Stop Tag\n if len(tags) == 0 and len(self.if_data) < 50000 and len(self.if_data) > 0:\n self.if_data = numpy.append(self.if_data, in0)\n\n # Do Analysis on all the Data\n if self.do_analysis is True:\n\n # Obtain Bitstream\n get_bits = self.getBitstream()\n\n # Parse Bits\n if len(get_bits) > 8:\n get_message, get_message_hex = self.getFields(get_bits)\n\n # Print to Output Port\n self.message_port_pub(pmt.intern(\"out\"), pmt.to_pmt(get_message))\n\n # Send Message to UDP Port\n if self.do_udp and len(get_message_hex) > 0:\n self.sendUDP(get_message_hex)\n\n # Reset\n self.start_tag = 0\n self.end_tag = 0\n self.if_data = numpy.array([], dtype=numpy.float32)\n self.do_analysis = False\n\n return in0_len\n\n\n def getBitstream(self):\n \"\"\" Prints out the bitstream from the peaks in the correlation estimation.\n \"\"\"\n try:\n bitstream = \"1\"\n \n # Find the First Peak\n peak_amplitude = numpy.amax(self.if_data[0:150])\n peak_sample = int(numpy.where(self.if_data[0:150] == peak_amplitude)[0])\n \n # Find Four Consecutive Peaks (Sync)\n sync_found = False\n prev_peak_amplitude = peak_amplitude\n \n for n in range(1,4):\n \n # Check for Peak within 50% of Previous Peak\n if self.if_data[peak_sample+n*100] > 0.5*prev_peak_amplitude:\n prev_peak_amplitude = self.if_data[peak_sample+n*100]\n sync_found = True\n else:\n sync_found = False\n break\n \n # Sync Found\n if sync_found is True:\n \n # Get Bitstream from Peaks\n for n in range(peak_sample,len(self.if_data),100):\n \n # High Peak\n if self.if_data[n] > 0.5*prev_peak_amplitude:\n prev_peak_amplitude = self.if_data[n]\n current_peak = 1\n \n # Low Peak\n else:\n current_peak = 0\n \n # Current Peak is 0, Flip\n if current_peak == 0:\n if bitstream[-1] is \"0\":\n bitstream = bitstream + \"1\"\n else:\n bitstream = bitstream + \"0\"\n \n # Current Peak is 1, Keep Previous\n else:\n bitstream = bitstream + bitstream[-1]\n \n # Error \n except:\n bitstream = \"-1\"\n\n return bitstream\n\n\n def getFields(self, bits):\n \"\"\" Prints out the content of the message fields from the bitstream.\n \"\"\"\n # Update Count\n self.message_number = self.message_number + 1\n\n # Get Time\n start_time = self.start_tag / 1e6 # 1e6 = Sampling Rate\n delta_time = start_time - self.prev_time\n\n # Find the Fields from Start/Stop Bits\n start_bit = False\n bit_counter = 0\n data_bytes = \"\"\n\n for n in range(0, len(bits)):\n\n # Start Bit Found\n if start_bit is True:\n data_bytes = data_bytes + bits[n]\n bit_counter = bit_counter + 1\n\n # Reached End of Byte\n if bit_counter == 8:\n start_bit = False\n bit_counter = 0\n\n # Detect New Start Bit\n else: \n if bits[n] is \"0\" and start_bit is False:\n start_bit = True\n\n # Get Fields from Data Bits\n if len(data_bytes) >= 24:\n mid = data_bytes[0:8]\n data = data_bytes[8:-8]\n checksum = data_bytes[-8:]\n\n # Construct the Output Message\n message = \"\"\n message = message + \"MESSAGE NUMBER: \" + str(self.message_number) + \"\\t\\t\"\n message = message + \"TIME: \" + str(start_time) + ' s' + \"\\t\\t\"\n message = message + \"DELTA: \" + str(delta_time) + ' s' + \"\\n\"\n message = message + \"MID: \" + '0x%0*X' % (2,int(mid[::-1],2)) + \"\\t\\t\"\n message_hex = '%0*X' % (2,int(mid[::-1],2))\n\n # Valid Bitstream\n if len(data) % 8 == 0:\n \n # Order Bytes Correctly from Reversed Bitstream\n wrong_hex_order = ('%0*X' % (2,int(data[::-1],2))).zfill(len(data)/4)\n correct_hex_order = \"\"\n for m in range(0,len(wrong_hex_order),2):\n correct_hex_order = wrong_hex_order[m:m+2] + correct_hex_order\n message = message + \"DATA: \" + '0x' + correct_hex_order + \"\\t\\t\"\n message_hex = message_hex + correct_hex_order\n\n # Invalid Bitstream\n else:\n message = message + \"DATA: BITS MISSING\\t\\t\"\n\n message = message + \"CHECKSUM: \" + '0x%0*X' % (2,int(checksum[::-1],2))\n message_hex = message_hex + '%0*X' % (2,int(checksum[::-1],2))\n\n # Not Enough Bits\n else:\n \n # Construct the Output Message\n message = \"\"\n message = message + \"MESSAGE NUMBER: \" + str(self.message_number) + \"\\t\\t\"\n message = message + \"TIME: \" + str(start_time) + ' s' + \"\\t\\t\"\n message = message + \"DELTA: \" + str(delta_time) + ' s' + \"\\t\\t\"\n message = message + \"MID: NOT FOUND\\t\\t\"\n message = message + \"DATA: NOT FOUND\\t\\t\"\n message = message + \"CHECKSUM: NOT FOUND\"\n message_hex = \"\"\n\n # Store Time\n self.prev_time = start_time\n\n return message, message_hex\n\n\n def sendUDP(self, message_hex):\n \"\"\" Converts a message to bytes and sends it to a specified UDP port.\n \"\"\"\n # Convert Message\n udp_message = message_hex.decode('hex')\n \n # Send Message\n self.udp_socket.sendto(udp_message,(\"127.0.0.1\", self.udp_port))\n\n\n" ]
[ [ "numpy.append", "numpy.array", "numpy.where", "numpy.amax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yngtodd/jeopardy
[ "c8a58ae0996544f0733a7efb2a18d3e7ccdebb65" ]
[ "jeopardy/data/data.py" ]
[ "import os\nimport numpy as np\n\nfrom .utils import download_url, makedir_exist_ok\n\n\nclass JeopardyData:\n \"\"\"Jeopardy Dataset.\n\n Parameters\n ----------\n root str :\n Root directory of dataset where ``processed/training.npy`` lives.\n\n download : bool, optional\n If true, downloads the dataset from the internet and\n puts it in root directory. If dataset is already downloaded, it is not\n downloaded again.\n \"\"\"\n urls = [\n 'https://raw.githubusercontent.com/utkML/data/master/jeopardy/x_train.npy',\n 'https://raw.githubusercontent.com/utkML/data/master/jeopardy/y_train.npy',\n ]\n\n data_file = 'data.npy'\n label_file = 'labels.npy'\n\n def __init__(self, root, download=False):\n self.root = os.path.expanduser(root)\n\n if download:\n self.download()\n\n if not self._check_exists():\n raise RuntimeError('Dataset not found.' +\n ' You can use download=True to download it')\n\n data_file = self.data_file\n label_file = self.label_file\n\n self.data = np.load(os.path.join(self.processed_folder, data_file))\n self.targets = np.load(os.path.join(self.processed_folder, label_file))\n\n def __len__(self):\n return len(self.data)\n\n def load_data(self):\n return self.data, self.targets\n\n @property\n def raw_folder(self):\n return os.path.join(self.root, self.__class__.__name__, 'raw')\n\n @property\n def processed_folder(self):\n return os.path.join(self.root, self.__class__.__name__, 'processed')\n\n def _check_exists(self):\n return os.path.exists(os.path.join(self.processed_folder, self.data_file)) and \\\n os.path.exists(os.path.join(self.processed_folder, self.label_file))\n\n @staticmethod\n def extract_array(path, remove_finished=False):\n print('Extracting {}'.format(path))\n arry = np.load(path)\n if remove_finished:\n os.unlink(path)\n\n def download(self):\n \"\"\"Download the jeopardy data if it doesn't exist in processed_folder already.\"\"\"\n\n if self._check_exists():\n return\n\n makedir_exist_ok(self.raw_folder)\n makedir_exist_ok(self.processed_folder)\n\n # download files\n for url in self.urls:\n filename = url.rpartition('/')[2]\n file_path = os.path.join(self.raw_folder, filename)\n download_url(url, root=self.raw_folder, filename=filename, md5=None)\n self.extract_array(path=file_path, remove_finished=False)\n\n # process and save as numpy files\n print('Processing...')\n\n training_set = (\n np.load(os.path.join(self.raw_folder, 'x_train.npy')),\n np.load(os.path.join(self.raw_folder, 'y_train.npy'))\n )\n\n # Save processed training data\n train_data_path = os.path.join(self.processed_folder, self.data_file)\n np.save(train_data_path, training_set[0])\n train_label_path = os.path.join(self.processed_folder, self.label_file)\n np.save(train_label_path, training_set[1])\n\n print('Done!')\n\n def __repr__(self):\n fmt_str = 'Dataset ' + self.__class__.__name__ + '\\n'\n fmt_str += ' Number of datapoints: {}\\n'.format(self.__len__())\n fmt_str += ' Root Location: {}\\n'.format(self.root)\n return fmt_str\n" ]
[ [ "numpy.load", "numpy.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
da0c/DL_Course_SamU
[ "2f11e07373af5fc46b35ec03e6b481e6a4952924" ]
[ "lab_3/scripts/solver.py" ]
[ "from __future__ import print_function, division\nfrom future import standard_library\n\nstandard_library.install_aliases()\nfrom builtins import range\nfrom builtins import object\nimport os\nimport pickle as pickle\n\nimport numpy as np\n\nfrom scripts import optim\n\n\nclass Solver(object):\n \"\"\"\n A Solver encapsulates all the logic necessary for training classification\n models. The Solver performs stochastic gradient descent using different\n update rules defined in optim.py.\n\n The solver accepts both training and validataion data and labels so it can\n periodically check classification accuracy on both training and validation\n data to watch out for overfitting.\n\n To train a model, you will first construct a Solver instance, passing the\n model, dataset, and various options (learning rate, batch size, etc) to the\n constructor. You will then call the train() method to run the optimization\n procedure and train the model.\n\n After the train() method returns, model.params will contain the parameters\n that performed best on the validation set over the course of training.\n In addition, the instance variable solver.loss_history will contain a list\n of all losses encountered during training and the instance variables\n solver.train_acc_history and solver.val_acc_history will be lists of the\n accuracies of the model on the training and validation set at each epoch.\n\n Example usage might look something like this:\n\n data = {\n 'X_train': # training data\n 'y_train': # training labels\n 'X_val': # validation data\n 'y_val': # validation labels\n }\n model = MyAwesomeModel(hidden_size=100, reg=10)\n solver = Solver(model, data,\n update_rule='sgd',\n optim_config={\n 'learning_rate': 1e-3,\n },\n lr_decay=0.95,\n num_epochs=10, batch_size=100,\n print_every=100)\n solver.train()\n\n\n A Solver works on a model object that must conform to the following API:\n\n - model.params must be a dictionary mapping string parameter names to numpy\n arrays containing parameter values.\n\n - model.loss(X, y) must be a function that computes training-time loss and\n gradients, and test-time classification scores, with the following inputs\n and outputs:\n\n Inputs:\n - X: Array giving a minibatch of input data of shape (N, d_1, ..., d_k)\n - y: Array of labels, of shape (N,) giving labels for X where y[i] is the\n label for X[i].\n\n Returns:\n If y is None, run a test-time forward pass and return:\n - scores: Array of shape (N, C) giving classification scores for X where\n scores[i, c] gives the score of class c for X[i].\n\n If y is not None, run a training time forward and backward pass and\n return a tuple of:\n - loss: Scalar giving the loss\n - grads: Dictionary with the same keys as self.params mapping parameter\n names to gradients of the loss with respect to those parameters.\n \"\"\"\n\n def __init__(self, model, data, **kwargs):\n \"\"\"\n Construct a new Solver instance.\n\n Required arguments:\n - model: A model object conforming to the API described above\n - data: A dictionary of training and validation data containing:\n 'X_train': Array, shape (N_train, d_1, ..., d_k) of training images\n 'X_val': Array, shape (N_val, d_1, ..., d_k) of validation images\n 'y_train': Array, shape (N_train,) of labels for training images\n 'y_val': Array, shape (N_val,) of labels for validation images\n\n Optional arguments:\n - update_rule: A string giving the name of an update rule in optim.py.\n Default is 'sgd'.\n - optim_config: A dictionary containing hyperparameters that will be\n passed to the chosen update rule. Each update rule requires different\n hyperparameters (see optim.py) but all update rules require a\n 'learning_rate' parameter so that should always be present.\n - lr_decay: A scalar for learning rate decay; after each epoch the\n learning rate is multiplied by this value.\n - batch_size: Size of minibatches used to compute loss and gradient\n during training.\n - num_epochs: The number of epochs to run for during training.\n - print_every: Integer; training losses will be printed every\n print_every iterations.\n - verbose: Boolean; if set to false then no output will be printed\n during training.\n - num_train_samples: Number of training samples used to check training\n accuracy; default is 1000; set to None to use entire training set.\n - num_val_samples: Number of validation samples to use to check val\n accuracy; default is None, which uses the entire validation set.\n - checkpoint_name: If not None, then save model checkpoints here every\n epoch.\n \"\"\"\n self.model = model\n self.X_train = data[\"X_train\"]\n self.y_train = data[\"y_train\"]\n self.X_val = data[\"X_val\"]\n self.y_val = data[\"y_val\"]\n\n # Unpack keyword arguments\n self.update_rule = kwargs.pop(\"update_rule\", \"sgd\")\n self.optim_config = kwargs.pop(\"optim_config\", {})\n self.lr_decay = kwargs.pop(\"lr_decay\", 1.0)\n self.batch_size = kwargs.pop(\"batch_size\", 100)\n self.num_epochs = kwargs.pop(\"num_epochs\", 10)\n self.num_train_samples = kwargs.pop(\"num_train_samples\", 1000)\n self.num_val_samples = kwargs.pop(\"num_val_samples\", None)\n\n self.checkpoint_name = kwargs.pop(\"checkpoint_name\", None)\n self.print_every = kwargs.pop(\"print_every\", 10)\n self.verbose = kwargs.pop(\"verbose\", True)\n\n # Throw an error if there are extra keyword arguments\n if len(kwargs) > 0:\n extra = \", \".join('\"%s\"' % k for k in list(kwargs.keys()))\n raise ValueError(\"Unrecognized arguments %s\" % extra)\n\n # Make sure the update rule exists, then replace the string\n # name with the actual function\n if not hasattr(optim, self.update_rule):\n raise ValueError('Invalid update_rule \"%s\"' % self.update_rule)\n self.update_rule = getattr(optim, self.update_rule)\n\n self._reset()\n\n def _reset(self):\n \"\"\"\n Set up some book-keeping variables for optimization. Don't call this\n manually.\n \"\"\"\n # Set up some variables for book-keeping\n self.epoch = 0\n self.best_val_acc = 0\n self.best_params = {}\n self.loss_history = []\n self.train_acc_history = []\n self.val_acc_history = []\n\n # Make a deep copy of the optim_config for each parameter\n self.optim_configs = {}\n for p in self.model.params:\n d = {k: v for k, v in self.optim_config.items()}\n self.optim_configs[p] = d\n\n def _step(self):\n \"\"\"\n Make a single gradient update. This is called by train() and should not\n be called manually.\n \"\"\"\n # Make a minibatch of training data\n num_train = self.X_train.shape[0]\n batch_mask = np.random.choice(num_train, self.batch_size)\n X_batch = self.X_train[batch_mask]\n y_batch = self.y_train[batch_mask]\n\n # Compute loss and gradient\n loss, grads = self.model.loss(X_batch, y_batch)\n self.loss_history.append(loss)\n\n # Perform a parameter update\n for p, w in self.model.params.items():\n dw = grads[p]\n config = self.optim_configs[p]\n next_w, next_config = self.update_rule(w, dw, config)\n self.model.params[p] = next_w\n self.optim_configs[p] = next_config\n\n def _save_checkpoint(self):\n if self.checkpoint_name is None:\n return\n checkpoint = {\n \"model\": self.model,\n \"update_rule\": self.update_rule,\n \"lr_decay\": self.lr_decay,\n \"optim_config\": self.optim_config,\n \"batch_size\": self.batch_size,\n \"num_train_samples\": self.num_train_samples,\n \"num_val_samples\": self.num_val_samples,\n \"epoch\": self.epoch,\n \"loss_history\": self.loss_history,\n \"train_acc_history\": self.train_acc_history,\n \"val_acc_history\": self.val_acc_history,\n }\n filename = \"%s_epoch_%d.pkl\" % (self.checkpoint_name, self.epoch)\n if self.verbose:\n print('Saving checkpoint to \"%s\"' % filename)\n with open(filename, \"wb\") as f:\n pickle.dump(checkpoint, f)\n\n def check_accuracy(self, X, y, num_samples=None, batch_size=100):\n \"\"\"\n Check accuracy of the model on the provided data.\n\n Inputs:\n - X: Array of data, of shape (N, d_1, ..., d_k)\n - y: Array of labels, of shape (N,)\n - num_samples: If not None, subsample the data and only test the model\n on num_samples datapoints.\n - batch_size: Split X and y into batches of this size to avoid using\n too much memory.\n\n Returns:\n - acc: Scalar giving the fraction of instances that were correctly\n classified by the model.\n \"\"\"\n\n # Maybe subsample the data\n N = X.shape[0]\n if num_samples is not None and N > num_samples:\n mask = np.random.choice(N, num_samples)\n N = num_samples\n X = X[mask]\n y = y[mask]\n\n # Compute predictions in batches\n num_batches = N // batch_size\n if N % batch_size != 0:\n num_batches += 1\n y_pred = []\n for i in range(num_batches):\n start = i * batch_size\n end = (i + 1) * batch_size\n scores = self.model.loss(X[start:end])\n y_pred.append(np.argmax(scores, axis=1))\n y_pred = np.hstack(y_pred)\n acc = np.mean(y_pred == y)\n\n return acc\n\n def train(self):\n \"\"\"\n Run optimization to train the model.\n \"\"\"\n num_train = self.X_train.shape[0]\n iterations_per_epoch = max(num_train // self.batch_size, 1)\n num_iterations = self.num_epochs * iterations_per_epoch\n\n for t in range(num_iterations):\n self._step()\n\n # Maybe print training loss\n if self.verbose and t % self.print_every == 0:\n print(\n \"(Iteration %d / %d) loss: %f\"\n % (t + 1, num_iterations, self.loss_history[-1])\n )\n\n # At the end of every epoch, increment the epoch counter and decay\n # the learning rate.\n epoch_end = (t + 1) % iterations_per_epoch == 0\n if epoch_end:\n self.epoch += 1\n for k in self.optim_configs:\n self.optim_configs[k][\"learning_rate\"] *= self.lr_decay\n\n # Check train and val accuracy on the first iteration, the last\n # iteration, and at the end of each epoch.\n first_it = t == 0\n last_it = t == num_iterations - 1\n if first_it or last_it or epoch_end:\n train_acc = self.check_accuracy(\n self.X_train, self.y_train, num_samples=self.num_train_samples\n )\n val_acc = self.check_accuracy(\n self.X_val, self.y_val, num_samples=self.num_val_samples\n )\n self.train_acc_history.append(train_acc)\n self.val_acc_history.append(val_acc)\n self._save_checkpoint()\n\n if self.verbose:\n print(\n \"(Epoch %d / %d) train acc: %f; val_acc: %f\"\n % (self.epoch, self.num_epochs, train_acc, val_acc)\n )\n\n # Keep track of the best model\n if val_acc > self.best_val_acc:\n self.best_val_acc = val_acc\n self.best_params = {}\n for k, v in self.model.params.items():\n self.best_params[k] = v.copy()\n\n # At the end of training swap the best params into the model\n self.model.params = self.best_params\n" ]
[ [ "numpy.hstack", "numpy.argmax", "numpy.mean", "numpy.random.choice" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pauldmccarthy/fsleyes
[ "453a6b91ec7763c39195814d635257e3766acf83" ]
[ "fsleyes/gl/textures/texture.py" ]
[ "#!/usr/bin/env python\n#\n# texture.py - The Texture and Texture2D classes.\n#\n# Author: Paul McCarthy <[email protected]>\n#\n\"\"\"This module provides the :class:`Texture` class, which is the base classes\nfor all other FSLeyes texture types. See also the :class:`.Texture2D` and\n:class:`.Texture3D` classes.\n\"\"\"\n\n\nimport logging\nimport contextlib\nimport functools as ft\n\nimport numpy as np\nimport OpenGL.GL as gl\n\nimport fsl.utils.idle as idle\n\nimport fsl.utils.notifier as notifier\nimport fsl.transform.affine as affine\nimport fsleyes_widgets.utils.status as status\nimport fsleyes.strings as strings\nfrom . import data as texdata\n\n\nlog = logging.getLogger(__name__)\n\n\nclass TextureBase(object):\n \"\"\"Base mixin class used by the :class:`Texture` class.\n\n This class provides logic for texture lifecycle management\n (creation/destruction) and usage.\n\n\n .. autosummary::\n :nosignatures:\n\n name\n handle\n target\n ndim\n nvals\n isBound\n bound\n bindTexture\n unbindTexture\n\n\n The :meth:`bound` method (which uses :meth:`bindTexture` and\n :meth:`unbindTexture`) method allows you to bind a texture object to a GL\n texture unit. For example, let's say we have a texture object called\n ``tex``, and we want to configure and use it::\n\n import OpenGL.GL as gl\n\n # When we want to use the texture in a\n # scene render, we need to bind it to\n # a texture unit.\n with tex.bound(gl.GL_TEXTURE0):\n\n # use linear interpolation\n tex.interp = gl.GL_LINEAR\n\n # ...\n # Do the render\n # ...\n \"\"\"\n\n\n def __init__(self, name, ndims, nvals):\n \"\"\"Create a ``TextureBase``.\n\n :arg name: The name of this texture - should be unique.\n :arg ndims: Number of dimensions - must be 1, 2 or 3.\n :arg nvals: Number of values stored in each texture element.\n \"\"\"\n if ndims == 1: ttype = gl.GL_TEXTURE_1D\n elif ndims == 2: ttype = gl.GL_TEXTURE_2D\n elif ndims == 3: ttype = gl.GL_TEXTURE_3D\n else: raise ValueError('Invalid number of dimensions')\n\n self.__texture = int(gl.glGenTextures(1))\n self.__ttype = ttype\n self.__name = name\n self.__ndims = ndims\n self.__nvals = nvals\n self.__bound = 0\n self.__textureUnit = None\n\n\n def __del__(self):\n \"\"\"Prints a log message.\"\"\"\n\n # log might get deleted before us\n try:\n log.debug('%s.del (%s)', type(self).__name__, id(self))\n except Exception:\n pass\n\n\n def destroy(self):\n \"\"\"Must be called when this ``TextureBase`` is no longer needed.\n Deletes the texture handle.\n \"\"\"\n\n log.debug('Deleting %s (%s) for %s: %s',\n type(self).__name__, id(self),\n self.__name, self.__texture)\n\n gl.glDeleteTextures(self.__texture)\n self.__texture = None\n\n\n @property\n def name(self):\n \"\"\"Returns the name of this texture. This is not the GL texture name,\n rather it is the unique name passed into :meth:`__init__`.\n \"\"\"\n return self.__name\n\n\n @property\n def handle(self):\n \"\"\"Returns the GL texture handle for this texture. \"\"\"\n return self.__texture\n\n\n @property\n def target(self):\n \"\"\"Returns the type of this texture - ``GL_TEXTURE_1D``,\n ``GL_TEXTURE_2D`` or ``GL_TEXTURE_3D``.\n \"\"\"\n return self.__ttype\n\n\n @property\n def ndim(self):\n \"\"\"Return the number of dimensions of this texture - 1, 2, or 3. \"\"\"\n return self.__ndims\n\n\n @property\n def nvals(self):\n \"\"\"Return the number of values stored at each point in this texture.\n \"\"\"\n return self.__nvals\n\n\n def isBound(self):\n \"\"\"Returns ``True`` if this texture is currently bound, ``False``\n otherwise.\n\n .. note:: This method assumes that the :meth:`bindTexture` and\n :meth:`unbindTexture` methods are called in pairs.\n \"\"\"\n return self.__bound > 0\n\n\n @contextlib.contextmanager\n def bound(self, textureUnit=None):\n \"\"\"Context manager which can be used to bind and unbind this texture,\n instead of manually calling :meth:`bindTexture` and\n :meth:`unbindTexture`\n\n :arg textureUnit: The texture unit to bind this texture to, e.g.\n ``GL_TEXTURE0``.\n \"\"\"\n try:\n self.bindTexture(textureUnit)\n yield\n finally:\n self.unbindTexture()\n\n\n def bindTexture(self, textureUnit=None):\n \"\"\"Activates and binds this texture.\n\n :arg textureUnit: The texture unit to bind this texture to, e.g.\n ``GL_TEXTURE0``.\n \"\"\"\n\n if self.__bound == 0:\n\n if textureUnit is not None:\n gl.glActiveTexture(textureUnit)\n\n gl.glBindTexture(self.__ttype, self.__texture)\n\n self.__textureUnit = textureUnit\n\n self.__bound += 1\n\n\n def unbindTexture(self):\n \"\"\"Unbinds this texture. \"\"\"\n\n if self.__bound == 1:\n if self.__textureUnit is not None:\n gl.glActiveTexture(self.__textureUnit)\n\n gl.glBindTexture(self.__ttype, 0)\n\n self.__textureUnit = None\n\n self.__bound = max(0, self.__bound - 1)\n\n\nclass TextureSettingsMixin(object):\n \"\"\"Mixin class used by the :class:`Texture` class.\n\n\n This class provides methods to get/set various settings which can\n be used to manipulate the texture. All of the logic which uses\n these settings is in the ``Texture`` class.\n\n\n The following settings can be changed:\n\n .. autosummary::\n :nosignatures:\n\n interp\n prefilter\n prefilterRange\n normalise\n normaliseRange\n border\n scales\n resolution\n\n Additional settings can be added via the ``settings`` argument to\n :meth:`__init__`. All settings can be changed via the :meth:`update`\n method.\n \"\"\"\n\n def __init__(self, settings=None):\n \"\"\"Create a ``TextureSettingsMixin``.\n\n :arg settings: Sequence of additional settings to make available.\n \"\"\"\n\n defaults = ['interp',\n 'prefilter', 'prefilterRange',\n 'normalise', 'normaliseRange',\n 'border', 'resolution', 'scales']\n\n if settings is None: settings = defaults\n else: settings = defaults + list(settings)\n\n self.__settings = {s : None for s in settings}\n\n\n @property\n def interp(self):\n \"\"\"Return the current texture interpolation setting - either\n ``GL_NEAREST`` or ``GL_LINEAR``.\n \"\"\"\n return self.__settings['interp']\n\n\n @interp.setter\n def interp(self, interp):\n \"\"\"Sets the texture interpolation. \"\"\"\n self.update(interp=interp)\n\n\n @property\n def prefilter(self):\n \"\"\"Return the current prefilter function - texture data is passed\n through this function before being uploaded to the GPU.\n\n If this function changes the range of the data, you must also\n provide a ``prefilterRange`` function - see :meth:`prefilterRange`.\n \"\"\"\n return self.__settings['prefilter']\n\n\n @prefilter.setter\n def prefilter(self, prefilter):\n \"\"\"Set the prefilter function \"\"\"\n self.update(prefilter=prefilter)\n\n\n @property\n def prefilterRange(self):\n \"\"\"Return the current prefilter range function - if the ``prefilter``\n function changes the data range, this function must be provided. It\n is passed two parameters - the known data minimum and maximum, and\n must adjust these values so that they reflect the adjusted range of\n the data that was passed to the ``prefilter`` function.\n \"\"\"\n return self.__settings['prefilterRange']\n\n\n @prefilterRange.setter\n def prefilterRange(self, prefilterRange):\n \"\"\"Set the prefilter range function. \"\"\"\n self.update(prefilter=prefilterRange)\n\n\n @property\n def normalise(self):\n \"\"\"Return the current normalisation state.\n\n If ``normalise=True``, the data is normalised to lie in the range\n ``[0, 1]`` (or normalised to the full range, if being stored as\n integers) before being stored. The data is normalised according to\n the minimum/maximum of the data, or to a normalise range set via\n the :meth:`normaliseRange`.\n\n Set this to ``False`` to disable normalisation.\n\n .. note:: If the data is not of a type that can be stored natively\n as a texture, the data is automatically normalised,\n regardless of the value specified here.\n \"\"\"\n return self.__settings['normalise']\n\n\n @normalise.setter\n def normalise(self, normalise):\n \"\"\"Enable/disable normalisation. \"\"\"\n self.update(normalise=normalise)\n\n\n @property\n def normaliseRange(self):\n \"\"\"Return the current normalise range.\n\n If normalisation is enabled (see :meth:`normalise`), or necessary,\n the data is normalised according to either its minimum/maximum, or\n to the range specified via this method.\n\n This parameter must be a sequence of two values, containing the\n ``(min, max)`` normalisation range. The data is then normalised to\n lie in the range ``[0, 1]`` (or normalised to the full range, if being\n stored as integers) before being stored.\n\n If ``None``, the data minimum/maximum are calculated and used.\n \"\"\"\n return self.__settings['normaliseRange']\n\n\n @normaliseRange.setter\n def normaliseRange(self, normaliseRange):\n \"\"\"Set the normalise range. \"\"\"\n self.update(normaliseRange=normaliseRange)\n\n\n @property\n def border(self):\n \"\"\"Return the texture border colour. Set this to a tuple of four values\n in the range 0 to 1, or ``None`` for no border (in which case the\n texture coordinates will be clamped to edges).\n \"\"\"\n return self.__settings['border']\n\n\n @border.setter\n def border(self, border):\n \"\"\"Return the texture border colour.\"\"\"\n self.update(border=border)\n\n\n @property\n def scales(self):\n \"\"\"Return the scaling factors for each axis of the texture data.\n\n These values are solely used to calculate the sub-sampling rate if the\n resolution (as set by :meth:`resolution`) is in terms of something\n other than data indices (e.g. :class:`.Image` pixdims).\n \"\"\"\n return self.__settings['scales']\n\n\n @scales.setter\n def scales(self, scales):\n \"\"\"Set the texture data axis scaling factors. \"\"\"\n self.update(scales=scales)\n\n\n @property\n def resolution(self):\n \"\"\"Return the current texture data resolution - this value is passed\n to the :func:`.routines.subsample` function, in the\n :func:`.prepareData` function.\n \"\"\"\n return self.__settings['resolution']\n\n\n @resolution.setter\n def resolution(self, resolution):\n \"\"\"Set the texture data resolution. \"\"\"\n self.update(resolution=resolution)\n\n\n def update(self, **kwargs):\n \"\"\"Set any parameters on this ``TextureSettingsMixin``. Valid keyword\n arguments are:\n\n ================== ==========================\n ``interp`` See :meth:`interp`.\n ``prefilter`` See :meth:`prefilter`.\n ``prefilterRange`` See :meth:`prefilterRange`\n ``normalise`` See :meth:`normalise.`\n ``normaliseRange`` See :meth:`normaliseRange`\n ``border`` See :meth:`border`\n ``scales`` See :meth:`scales`.\n ``resolution`` See :meth:`resolution`\n ================== ==========================\n\n :returns: A ``dict`` of ``{attr : changed}`` mappings, indicating\n which properties have changed value.\n \"\"\"\n\n changed = {}\n for s in self.__settings.keys():\n oldval = self.__settings[s]\n newval = kwargs.get(s, self.__settings[s])\n changed[s] = oldval != newval\n self.__settings[s] = newval\n return changed\n\n\nclass Texture(notifier.Notifier, TextureBase, TextureSettingsMixin):\n \"\"\"The ``Texture`` class is the base class for all other texture types in\n *FSLeyes*. This class is not intended to be used directly - use one of the\n sub-classes instead.\n\n\n A texture can be bound and unbound via the methods of the\n :class:`TextureBase` class. Various texture settings can be changed\n via the methods of the :class:`TextureSettingsMixin` class. In the majority\n of cases, in order to draw or configure a texture, it needs to be bound\n (although this depends on the sub-class).\n\n\n In order to use a texture, at the very least you need to provide some\n data, or specify a type and shape. This can be done either via the\n :meth:`data`/:meth:`shape`/:meth:`dtype` methods, or by the :meth:`set`\n method. If you specify a shape and data type, any previously specified\n data will be lost, and vice versa.\n\n\n Calling :meth:`set` will usually cause the texture to be reconfigured and\n refreshed, although you can also force a refresh by calling the\n :meth:`refresh` method directly.\n\n\n The following properties can be queried to retrieve information about the\n tetxure; some will return ``None`` until you have provided some data (or\n a shape and type):\n\n .. autosummary::\n :nosignatures:\n\n voxValXform\n invVoxValXform\n shape\n dtype\n textureType\n baseFormat\n internalFormat\n data\n preparedData\n\n\n When a ``Texture`` is created, and when its settings are changed, it may\n need to prepare the data to be passed to OpenGL - for large textures, this\n can be a time consuming process, so this may be performed on a separate\n thread using the :mod:`.idle` module (unless the ``threaded`` parameter to\n :meth:`__init__` is set to ``False``). The :meth:`ready` method returns\n ``True`` or ``False`` to indicate whether the ``Texture`` is ready to be\n used.\n\n\n Furthermore, the ``Texture`` class derives from :class:`.Notifier`, so\n listeners can register to be notified when an ``Texture`` is ready to\n be used.\n\n\n For textures with multiple values per voxel, it is assumed that these\n values are indexed with the first dimension of the texture data (as passed\n to :meth:`data` or :meth:`set`).\n\n\n ``Texture`` sub-classes (e.g. :class:`.Texture2D`, :class:`.Texture3D`,\n :class:`.ColourMapTexture`) must override the :meth:`doRefresh` method\n such that it performs the GL calls required to configure the textureb.\n\n\n See the :mod:`.resources` module for a method of sharing texture resources.\n \"\"\"\n\n\n def __init__(self,\n name,\n ndims,\n nvals,\n threaded=False,\n settings=None,\n textureFormat=None,\n internalFormat=None,\n **kwargs):\n \"\"\"Create a ``Texture``.\n\n :arg name: The name of this texture - should be unique.\n\n :arg ndims: Number of dimensions - must be 1, 2 or 3.\n\n :arg nvals: Number of values stored in each texture element.\n\n :arg threaded: If ``True``, the texture data will be prepared on\n a separate thread (on calls to\n :meth:`refresh`). If ``False``, the texture data\n is prepared on the calling thread, and the\n :meth:`refresh` call will block until it has been\n prepared.\n\n :arg settings: Additional settings to make available through the\n :class:`TextureSettingsMixin`.\n\n :arg textureFormat: Texture format to use - if not specified, this is\n automatically determined. If specified, an\n ``internalFormat`` must also be specified.\n\n :arg internalFormat: Internal texture format to use - if not specified,\n this is automatically determined.\n\n All other arguments are passed through to the initial call to\n :meth:`set`.\n\n .. note:: All subclasses must accept a ``name`` as the first parameter\n to their ``__init__`` method, and must pass said ``name``\n through to the :meth:`__init__` method.\n\n .. note:: In normal cases, the ``textureFormat`` and ``internalFormat``\n do not need to be specified - they will be automatically\n determined using the :func:`.data.getTextureType` function.\n However, there can be instances where a specific texture type\n needs to be used. In these instances, it is up to the calling\n code to ensure that the texture data can be coerced into\n the correct GL data type.\n \"\"\"\n\n TextureBase .__init__(self, name, ndims, nvals)\n TextureSettingsMixin.__init__(self, settings)\n\n if ((textureFormat is not None) and (internalFormat is None)) or \\\n ((textureFormat is None) and (internalFormat is not None)):\n raise ValueError('Both textureFormat and internalFormat '\n 'must be specified')\n\n self.__ready = False\n self.__threaded = threaded\n\n # The data, type and shape are\n # refreshed on every call to\n # set or refresh (the former\n # calls the latter)\n self.__data = None\n self.__dtype = None\n self.__shape = None\n self.__preparedData = None\n\n # The data is refreshed on\n # every call to set or refresh\n # These attributes are set by\n # the __determineTextureType\n # and __prepareTextureData\n # methods (which are called\n # by refresh)\n self.__voxValXform = None\n self.__invVoxValXform = None\n\n self.__autoTexFmt = textureFormat is None\n self.__texFmt = textureFormat\n self.__texIntFmt = internalFormat\n self.__texDtype = None\n\n # If threading is enabled, texture\n # refreshes are performed with an\n # idle.TaskThread.\n if threaded:\n self.__taskThread = idle.TaskThread()\n self.__taskName = '{}_{}_refresh'.format(type(self).__name__,\n id(self))\n\n self.__taskThread.daemon = True\n self.__taskThread.start()\n else:\n self.__taskThread = None\n self.__taskName = None\n\n self.set(**kwargs)\n\n\n def destroy(self):\n \"\"\"Must be called when this ``Texture`` is no longer needed.\n \"\"\"\n TextureBase.destroy(self)\n\n if self.__taskThread is not None:\n self.__taskThread.stop()\n\n self.__taskThread = None\n self.__data = None\n self.__preparedData = None\n\n\n\n def ready(self):\n \"\"\"Returns ``True`` if this ``Texture`` is ready to be used,\n ``False`` otherwise.\n \"\"\"\n return self.__ready\n\n\n @property\n def voxValXform(self):\n \"\"\"Return a transformation matrix that can be used to transform\n values read from the texture back to the original data range.\n \"\"\"\n return self.__voxValXform\n\n\n @property\n def invVoxValXform(self):\n \"\"\"Return a transformation matrix that can be used to transform\n values in the original data range to values as read from the texture.\n \"\"\"\n return self.__invVoxValXform\n\n\n def texCoordXform(self, origShape):\n \"\"\"Returns a transformation matrix which can be used to adjust a set of\n 3D texture coordinates so they can index the underlying texture, which\n may be 2D.\n\n This implementation returns an identity matrix, but it is overridden\n by the .Texture2D sub-class, which is sometimes used to store 3D image\n data.\n\n :arg origShape: Original data shape.\n \"\"\"\n return np.eye(4)\n\n\n def invTexCoordXform(self, origShape):\n \"\"\"Returns the inverse of :meth:`texCoordXform`. \"\"\"\n return affine.invert(self.texCoordXform(origShape))\n\n\n @property\n def shape(self):\n \"\"\"Return a tuple containing the texture data shape. \"\"\"\n return self.__shape\n\n\n @shape.setter\n def shape(self, shape):\n \"\"\"Set the texture data shape. \"\"\"\n return self.set(shape=shape)\n\n\n @property\n def dtype(self):\n \"\"\"Return the ``numpy`` data type of the texture data.\"\"\"\n return self.__dtype\n\n\n @dtype.setter\n def dtype(self, dtype):\n \"\"\"Set the ``numpy`` data type for the texture data.\"\"\"\n self.set(dtype=dtype)\n\n\n @property\n def textureType(self):\n \"\"\"Return the texture data type, e.g. ``gl.GL_UNSIGNED_BYTE``. \"\"\"\n return self.__texDtype\n\n\n @property\n def baseFormat(self):\n \"\"\"Return the base texture format, e.g. ``gl.GL_ALPHA``. \"\"\"\n return self.__texFmt\n\n\n @property\n def internalFormat(self):\n \"\"\"Return the sized/internal texture format, e.g. ``gl.GL_ALPHA8``. \"\"\"\n return self.__texIntFmt\n\n\n @property\n def data(self):\n \"\"\"Returns the data that has been passed to the :meth:`set` method. \"\"\"\n return self.__data\n\n\n @data.setter\n def data(self, data):\n \"\"\"Set the texture data - this get passed through to :meth:`set`. \"\"\"\n self.set(data=data)\n\n\n @property\n def preparedData(self):\n \"\"\"Returns the prepared data, i.e. the data as it has been copied\n to the GPU.\n \"\"\"\n return self.__preparedData\n\n\n def shapeData(self, data, oldShape=None):\n \"\"\"Shape the data so that it is ready for use as texture data.\n\n This implementation returns the data unchanged, but it is overridden\n by the ``Texture2D`` class, which is sometimes used to store 3D image\n data.\n\n :arg data: ``numpy`` array containing the data to be shaped\n :arg oldShape: Original data shape, if this is a sub-array. If not\n provided, taken from ``data``.\n \"\"\"\n return data\n\n\n def set(self, **kwargs):\n \"\"\"Set any parameters on this ``Texture``. Valid keyword arguments are:\n\n ================== ==============================================\n ``interp`` See :meth:`.interp`.\n ``data`` See :meth:`.data`.\n ``shape`` See :meth:`.shape`.\n ``dtype`` See :meth:`.dtype`.\n ``prefilter`` See :meth:`.prefilter`.\n ``prefilterRange`` See :meth:`.prefilterRange`\n ``normalise`` See :meth:`.normalise.`\n ``normaliseRange`` See :meth:`.normaliseRange`.\n ``scales`` See :meth:`.scales`.\n ``resolution`` See :meth:`.resolution`.\n ``refresh`` If ``True`` (the default), the :meth:`refresh`\n function is called (but only if a setting has\n changed).\n ``callback`` Optional function which will be called (via\n :func:`.idle.idle`) when the texture has been\n refreshed. Only called if ``refresh`` is\n ``True``, and a setting has changed.\n ``notify`` Passed through to the :meth:`refresh` method.\n ================== ==============================================\n\n :returns: ``True`` if any settings have changed and the\n ``Texture`` is being/needs to be refreshed, ``False``\n otherwise.\n \"\"\"\n\n changed = TextureSettingsMixin.update(self, **kwargs)\n data = kwargs.get('data', None)\n shape = kwargs.get('shape', self.shape)\n dtype = kwargs.get('dtype', self.dtype)\n refresh = kwargs.get('refresh', True)\n notify = kwargs.get('notify', True)\n callback = kwargs.get('callback', None)\n\n changed['data'] = data is not None\n changed['shape'] = shape != self.shape\n changed['dtype'] = dtype != self.dtype\n\n if not any(changed.values()):\n return False\n\n if data is not None:\n\n # The dtype attribute is set\n # later in __prepareTextureData,\n # as it may be different from\n # the dtype of the passed-in\n # data\n self.__data = data\n self.__dtype = None\n dtype = data.dtype\n\n # The first dimension is assumed to contain the\n # values, for multi-valued (e.g. RGB) textures\n if self.nvals > 1: self.__shape = data.shape[1:]\n else: self.__shape = data.shape\n\n # If the data is of a type which cannot\n # be stored natively as an OpenGL texture,\n # and we don't have support for floating\n # point textures, the data must be\n # normalised. See determineType and\n # prepareData in the data module\n self.normalise = self.normalise or \\\n (not texdata.canUseFloatTextures()[0] and\n (dtype not in (np.uint8, np.int8, np.uint16, np.int16)))\n\n # If the caller has not provided\n # a normalisation range, we have\n # to calculate it.\n if (data is not None) and \\\n self.normalise and \\\n (self.normaliseRange is None):\n self.normaliseRange = np.nanmin(data), np.nanmax(data)\n log.debug('Calculated %s data range for normalisation: '\n '[%s - %s]', self.name, *self.normaliseRange)\n\n elif changed['shape'] or changed['dtype']:\n self.__data = None\n self.__dtype = dtype\n self.__shape = shape\n\n refreshData = any((changed['data'],\n changed['prefilter'],\n changed['prefilterRange'],\n changed['normaliseRange'] and self.normalise,\n changed['resolution'],\n changed['scales'],\n changed['normalise']))\n\n if refresh:\n self.refresh(refreshData=refreshData,\n notify=notify,\n callback=callback)\n\n return True\n\n\n def refresh(self, refreshData=True, notify=True, callback=None):\n \"\"\"(Re-)configures the OpenGL texture.\n\n :arg refreshData: If ``True`` (the default), the texture data is\n refreshed.\n\n :arg notify: If ``True`` (the default), a notification is\n triggered via the :class:`.Notifier` base-class,\n when this ``Texture3D`` has been refreshed, and\n is ready to use. Otherwise, the notification is\n suppressed.\n\n :arg callback: Optional function which will be called (via\n :func:`.idle.idle`) when the texture has been\n refreshed. Only called if ``refresh`` is\n ``True``, and a setting has changed.\n\n .. note:: The texture data may be generated on a separate thread, using\n the :func:`.idle.run` function. This is controlled by the\n ``threaded`` parameter, passed to :meth:`__init__`.\n \"\"\"\n\n # Don't bother if data\n # or shape/type hasn't\n # been set\n data = self.__data\n shape = self.__shape\n dtype = self.__dtype\n\n # We either need some data, or\n # we need a shape and data type.\n if data is None and (shape is None or dtype is None):\n return\n\n refreshData = refreshData and (data is not None)\n self.__ready = False\n\n # This can take a long time for big\n # data, so we do it in a separate\n # thread using the idle module.\n def genData():\n\n # Another genData function is\n # already queued - don't run.\n # The TaskThreadVeto error\n # will stop the TaskThread from\n # calling configTexture as well.\n if self.__taskThread is not None and \\\n self.__taskThread.isQueued(self.__taskName):\n raise idle.TaskThreadVeto()\n\n self.__determineTextureType()\n\n if refreshData:\n self.__prepareTextureData()\n\n # Once genData is finished, we pass the\n # result (see __prepareTextureData) to\n # the sub-class doRefresh method.\n def doRefresh():\n\n self.doRefresh()\n\n self.__ready = True\n\n if notify:\n self.notify()\n if callback is not None:\n callback()\n\n # Wrap the above functions in a report\n # decorator in case an error occurs\n title = strings.messages[self, 'dataError']\n msg = strings.messages[self, 'dataError']\n\n # the genData function is called on a separate thread,\n # but doRefresh is called on the idle/mainloop. So we\n # can use the reportErrorDecorator for the latter, but\n # not the former.\n doRefresh = status.reportErrorDecorator(title, msg)(doRefresh)\n genDataError = ft.partial(status.reportError, title, msg)\n\n # Run asynchronously if we are\n # threaded, and we have data to\n # prepare - if we don't have\n # data, we run genData on the\n # current thread, because it\n # shouldn't do anything\n if self.__threaded and (data is not None):\n\n # TODO the task is already queued,\n # but a callback function has been\n # specified, should you queue the\n # callback function?\n\n # Don't queue the texture\n # refresh task twice\n if not self.__taskThread.isQueued(self.__taskName):\n self.__taskThread.enqueue(genData,\n taskName=self.__taskName,\n onFinish=doRefresh,\n onError=genDataError)\n\n else:\n genData()\n doRefresh()\n\n\n def patchData(self, data, offset):\n \"\"\"This is a shortcut method which can be used to replace part\n of the image texture data without having to regenerate the entire\n texture.\n\n The :meth:`set` and :meth:`refresh` methods are quite heavyweight, and\n are written in such a way that partial texture updates are not\n possible. This method allows small parts of the image texture to be\n quickly updated.\n \"\"\"\n data = np.asarray(data)\n\n if len(data.shape) < self.ndim:\n newshape = list(data.shape) + [1] * (self.ndim - len(data.shape))\n data = data.reshape(newshape)\n\n data = texdata.prepareData(\n data,\n prefilter=self.prefilter,\n prefilterRange=self.prefilterRange,\n resolution=self.resolution,\n scales=self.scales,\n normalise=self.normalise,\n normaliseRange=self.normaliseRange)[0]\n\n self.doPatch(data, offset)\n\n self.notify()\n\n\n def doRefresh(self):\n \"\"\"Must be overridden by sub-classes to configure the texture.\n\n This method is not intended to be called externally - call\n :meth:`refresh` instead.\n\n This method should use the :meth:`preparedData`, or the :meth:`shape`,\n to configure the texture. Sub-classes can assume that at least one\n of these will not be ``None``.\n\n If ``preparedData`` is not ``None``, the ``shape`` should be ignored,\n and inferred from ``preparedData``.\n \"\"\"\n raise NotImplementedError('Must be implemented by subclasses')\n\n\n def doPatch(self, data, offset):\n \"\"\"Must be overridden by sub-classes to quickly update part of\n the texture data.\n\n This method is not intended to be called externally - call\n :meth:`patchData` instead.\n \"\"\"\n raise NotImplementedError('Must be implemented by subclasses')\n\n\n def __determineTextureType(self):\n \"\"\"Figures out how the texture data should be stored as an OpenGL\n texture. See the :func:`.data.getTextureType` function.\n\n This method sets the following attributes on this ``Texture`` instance:\n\n ==================== ==============================================\n ``__texFmt`` The texture format (e.g. ``GL_RGB``,\n ``GL_LUMINANCE``, etc).\n\n ``__texIntFmt`` The internal texture format used by OpenGL for\n storage (e.g. ``GL_RGB16``, ``GL_LUMINANCE8``,\n etc).\n\n ``__texDtype`` The raw type of the texture data (e.g.\n ``GL_UNSIGNED_SHORT``)\n ==================== ==============================================\n \"\"\"\n\n if self.nvals not in (1, 3, 4):\n raise ValueError('Cannot create texture representation for {} '\n '(nvals: {})'.format(self.dtype, self.nvals))\n\n if self.__data is None: dtype = self.__dtype\n else: dtype = self.__data.dtype\n\n normalise = self.normalise\n nvals = self.nvals\n texDtype, texFmt, intFmt = texdata.getTextureType(\n normalise, dtype, nvals)\n\n if not self.__autoTexFmt:\n texFmt = self.__texFmt\n intFmt = self.__texIntFmt\n\n log.debug('Texture (%s) is to be stored as %s/%s/%s '\n '(normalised: %s)',\n self.name,\n texdata.GL_TYPE_NAMES[texDtype],\n texdata.GL_TYPE_NAMES[texFmt],\n texdata.GL_TYPE_NAMES[intFmt],\n normalise)\n\n self.__texFmt = texFmt\n self.__texIntFmt = intFmt\n self.__texDtype = texDtype\n\n\n def __prepareTextureData(self):\n \"\"\"Prepare the texture data.\n\n This method passes the stored data to the :func:`.data.prepareData`\n function and then stores references to its return valuesa as\n attributes on this ``Texture`` instance:\n\n ==================== =============================================\n ``__preparedata`` A ``numpy`` array containing the image data,\n ready to be copied to the GPU.\n\n ``__voxValXform`` An affine transformation matrix which encodes\n an offset and a scale, which may be used to\n transform the texture data from the range\n ``[0.0, 1.0]`` to its raw data range.\n\n ``__invVoxValXform`` Inverse of ``voxValXform``.\n ==================== =============================================\n \"\"\"\n\n data, voxValXform, invVoxValXform = texdata.prepareData(\n self.__data,\n prefilter=self.prefilter,\n prefilterRange=self.prefilterRange,\n resolution=self.resolution,\n scales=self.scales,\n normalise=self.normalise,\n normaliseRange=self.normaliseRange)\n\n self.__preparedData = data\n self.__dtype = data.dtype\n self.__voxValXform = voxValXform\n self.__invVoxValXform = invVoxValXform\n" ]
[ [ "numpy.asarray", "numpy.nanmax", "numpy.eye", "numpy.nanmin" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
KyounghyunPark/hrv_analysis
[ "d4d8aa38e0ea5794e6aefa9e861aa5e24a138bcd", "d4d8aa38e0ea5794e6aefa9e861aa5e24a138bcd" ]
[ "env/lib/python3.5/site-packages/mne/tests/test_chpi.py", "env/lib/python3.5/site-packages/mne/viz/_brain/_brain.py" ]
[ "# Author: Eric Larson <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport os.path as op\n\nimport numpy as np\nfrom numpy.testing import assert_allclose, assert_array_less\nfrom scipy.interpolate import interp1d\nfrom scipy.spatial.distance import cdist\nimport pytest\n\nfrom mne import pick_types, pick_info\nfrom mne.forward._compute_forward import _MAG_FACTOR\nfrom mne.io import (read_raw_fif, read_raw_artemis123, read_raw_ctf, read_info,\n RawArray)\nfrom mne.io.constants import FIFF\nfrom mne.chpi import (compute_chpi_amplitudes, compute_chpi_locs,\n compute_head_pos, _setup_ext_proj,\n _chpi_locs_to_times_dig, _compute_good_distances,\n extract_chpi_locs_ctf, head_pos_to_trans_rot_t,\n read_head_pos, write_head_pos, filter_chpi,\n _get_hpi_info, _get_hpi_initial_fit)\nfrom mne.transforms import rot_to_quat, _angle_between_quats\nfrom mne.simulation import add_chpi\nfrom mne.utils import run_tests_if_main, catch_logging, assert_meg_snr, verbose\nfrom mne.datasets import testing\n\nbase_dir = op.join(op.dirname(__file__), '..', 'io', 'tests', 'data')\nctf_fname = op.join(base_dir, 'test_ctf_raw.fif')\nhp_fif_fname = op.join(base_dir, 'test_chpi_raw_sss.fif')\nhp_fname = op.join(base_dir, 'test_chpi_raw_hp.txt')\nraw_fname = op.join(base_dir, 'test_raw.fif')\n\ndata_path = testing.data_path(download=False)\nsample_fname = op.join(\n data_path, 'MEG', 'sample', 'sample_audvis_trunc_raw.fif')\nchpi_fif_fname = op.join(data_path, 'SSS', 'test_move_anon_raw.fif')\npos_fname = op.join(data_path, 'SSS', 'test_move_anon_raw.pos')\nsss_fif_fname = op.join(data_path, 'SSS', 'test_move_anon_raw_sss.fif')\nsss_hpisubt_fname = op.join(data_path, 'SSS', 'test_move_anon_hpisubt_raw.fif')\nchpi5_fif_fname = op.join(data_path, 'SSS', 'chpi5_raw.fif')\nchpi5_pos_fname = op.join(data_path, 'SSS', 'chpi5_raw_mc.pos')\nctf_chpi_fname = op.join(data_path, 'CTF', 'testdata_ctf_mc.ds')\nctf_chpi_pos_fname = op.join(data_path, 'CTF', 'testdata_ctf_mc.pos')\n\nart_fname = op.join(data_path, 'ARTEMIS123', 'Artemis_Data_2017-04-04' +\n '-15h-44m-22s_Motion_Translation-z.bin')\nart_mc_fname = op.join(data_path, 'ARTEMIS123', 'Artemis_Data_2017-04-04' +\n '-15h-44m-22s_Motion_Translation-z_mc.pos')\n\n\[email protected]_testing_data\ndef test_chpi_adjust():\n \"\"\"Test cHPI logging and adjustment.\"\"\"\n raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes')\n with catch_logging() as log:\n _get_hpi_initial_fit(raw.info, adjust=True, verbose='debug')\n _get_hpi_info(raw.info, verbose='debug')\n # Ran MaxFilter (with -list, -v, -movecomp, etc.), and got:\n msg = ['HPIFIT: 5 coils digitized in order 5 1 4 3 2',\n 'HPIFIT: 3 coils accepted: 1 2 4',\n 'Hpi coil moments (3 5):',\n '2.08542e-15 -1.52486e-15 -1.53484e-15',\n '2.14516e-15 2.09608e-15 7.30303e-16',\n '-3.2318e-16 -4.25666e-16 2.69997e-15',\n '5.21717e-16 1.28406e-15 1.95335e-15',\n '1.21199e-15 -1.25801e-19 1.18321e-15',\n 'HPIFIT errors: 0.3, 0.3, 5.3, 0.4, 3.2 mm.',\n 'HPI consistency of isotrak and hpifit is OK.',\n 'HP fitting limits: err = 5.0 mm, gval = 0.980.',\n 'Using 5 HPI coils: 83 143 203 263 323 Hz', # actually came earlier\n ]\n\n log = log.getvalue().splitlines()\n assert set(log) == set(msg), '\\n' + '\\n'.join(set(msg) - set(log))\n\n # Then took the raw file, did this:\n raw.info['dig'][5]['r'][2] += 1.\n # And checked the result in MaxFilter, which changed the logging as:\n msg = msg[:8] + [\n 'HPIFIT errors: 0.3, 0.3, 5.3, 999.7, 3.2 mm.',\n 'Note: HPI coil 3 isotrak is adjusted by 5.3 mm!',\n 'Note: HPI coil 5 isotrak is adjusted by 3.2 mm!'] + msg[-2:]\n with catch_logging() as log:\n _get_hpi_initial_fit(raw.info, adjust=True, verbose='debug')\n _get_hpi_info(raw.info, verbose='debug')\n log = log.getvalue().splitlines()\n assert set(log) == set(msg), '\\n' + '\\n'.join(set(msg) - set(log))\n\n\[email protected]_testing_data\ndef test_read_write_head_pos(tmpdir):\n \"\"\"Test reading and writing head position quaternion parameters.\"\"\"\n temp_name = op.join(str(tmpdir), 'temp.pos')\n # This isn't a 100% valid quat matrix but it should be okay for tests\n head_pos_rand = np.random.RandomState(0).randn(20, 10)\n # This one is valid\n head_pos_read = read_head_pos(pos_fname)\n for head_pos_orig in (head_pos_rand, head_pos_read):\n write_head_pos(temp_name, head_pos_orig)\n head_pos = read_head_pos(temp_name)\n assert_allclose(head_pos_orig, head_pos, atol=1e-3)\n # Degenerate cases\n pytest.raises(TypeError, write_head_pos, 0, head_pos_read) # not filename\n pytest.raises(ValueError, write_head_pos, temp_name, 'foo') # not array\n pytest.raises(ValueError, write_head_pos, temp_name, head_pos_read[:, :9])\n pytest.raises(TypeError, read_head_pos, 0)\n pytest.raises(IOError, read_head_pos, temp_name + 'foo')\n\n\[email protected]_testing_data\ndef test_hpi_info(tmpdir):\n \"\"\"Test getting HPI info.\"\"\"\n temp_name = op.join(str(tmpdir), 'temp_raw.fif')\n for fname in (chpi_fif_fname, sss_fif_fname):\n raw = read_raw_fif(fname, allow_maxshield='yes').crop(0, 0.1)\n assert len(raw.info['hpi_subsystem']) > 0\n raw.save(temp_name, overwrite=True)\n info = read_info(temp_name)\n assert len(info['hpi_subsystem']) == len(raw.info['hpi_subsystem'])\n\n\ndef _assert_quats(actual, desired, dist_tol=0.003, angle_tol=5., err_rtol=0.5,\n gof_rtol=0.001, vel_atol=2e-3): # 2 mm/s\n \"\"\"Compare estimated cHPI positions.\"\"\"\n __tracebackhide__ = True\n trans_est, rot_est, t_est = head_pos_to_trans_rot_t(actual)\n trans, rot, t = head_pos_to_trans_rot_t(desired)\n quats_est = rot_to_quat(rot_est)\n gofs, errs, vels = desired[:, 7:].T\n gofs_est, errs_est, vels_est = actual[:, 7:].T\n del actual, desired\n\n # maxfilter produces some times that are implausibly large (weird)\n if not np.isclose(t[0], t_est[0], atol=1e-1): # within 100 ms\n raise AssertionError('Start times not within 100 ms: %0.3f != %0.3f'\n % (t[0], t_est[0]))\n use_mask = (t >= t_est[0]) & (t <= t_est[-1])\n t = t[use_mask]\n trans = trans[use_mask]\n quats = rot_to_quat(rot)\n quats = quats[use_mask]\n gofs, errs, vels = gofs[use_mask], errs[use_mask], vels[use_mask]\n\n # double-check our angle function\n for q in (quats, quats_est):\n angles = _angle_between_quats(q, q)\n assert_allclose(angles, 0., atol=1e-5)\n\n # limit translation difference between MF and our estimation\n trans_est_interp = interp1d(t_est, trans_est, axis=0)(t)\n distances = np.sqrt(np.sum((trans - trans_est_interp) ** 2, axis=1))\n assert np.isfinite(distances).all()\n arg_worst = np.argmax(distances)\n assert distances[arg_worst] <= dist_tol, (\n '@ %0.3f seconds: %0.3f > %0.3f mm'\n % (t[arg_worst], 1000 * distances[arg_worst], 1000 * dist_tol))\n\n # limit rotation difference between MF and our estimation\n # (note that the interpolation will make this slightly worse)\n quats_est_interp = interp1d(t_est, quats_est, axis=0)(t)\n angles = 180 * _angle_between_quats(quats_est_interp, quats) / np.pi\n arg_worst = np.argmax(angles)\n assert angles[arg_worst] <= angle_tol, (\n '@ %0.3f seconds: %0.3f > %0.3f deg'\n % (t[arg_worst], angles[arg_worst], angle_tol))\n\n # error calculation difference\n errs_est_interp = interp1d(t_est, errs_est)(t)\n assert_allclose(errs_est_interp, errs, rtol=err_rtol, atol=1e-3,\n err_msg='err') # 1 mm\n\n # gof calculation difference\n gof_est_interp = interp1d(t_est, gofs_est)(t)\n assert_allclose(gof_est_interp, gofs, rtol=gof_rtol, atol=1e-7,\n err_msg='gof')\n\n # velocity calculation difference\n vel_est_interp = interp1d(t_est, vels_est)(t)\n assert_allclose(vel_est_interp, vels, atol=vel_atol,\n err_msg='velocity')\n\n\ndef _decimate_chpi(raw, decim=4):\n \"\"\"Decimate raw data (with aliasing) in cHPI-fitting compatible way.\"\"\"\n raw_dec = RawArray(\n raw._data[:, ::decim], raw.info, first_samp=raw.first_samp // decim)\n raw_dec.info['sfreq'] /= decim\n for coil in raw_dec.info['hpi_meas'][0]['hpi_coils']:\n if coil['coil_freq'] > raw_dec.info['sfreq']:\n coil['coil_freq'] = np.mod(coil['coil_freq'],\n raw_dec.info['sfreq'])\n if coil['coil_freq'] > raw_dec.info['sfreq'] / 2.:\n coil['coil_freq'] = raw_dec.info['sfreq'] - coil['coil_freq']\n return raw_dec\n\n\n# A shortcut method for testing that does both steps\n@verbose\ndef _calculate_chpi_positions(raw, t_step_min=0.01, t_step_max=1.,\n t_window='auto', too_close='raise',\n dist_limit=0.005, gof_limit=0.98,\n ext_order=1, verbose=None):\n chpi_amplitudes = compute_chpi_amplitudes(\n raw, t_step_min=t_step_min, t_window=t_window,\n ext_order=ext_order, verbose=verbose)\n chpi_locs = compute_chpi_locs(\n raw.info, chpi_amplitudes, t_step_max=t_step_max,\n too_close=too_close, verbose=verbose)\n head_pos = compute_head_pos(\n raw.info, chpi_locs, dist_limit=dist_limit, gof_limit=gof_limit,\n verbose=verbose)\n return head_pos\n\n\[email protected]\[email protected]_testing_data\ndef test_calculate_chpi_positions_vv():\n \"\"\"Test calculation of cHPI positions.\"\"\"\n # Check to make sure our fits match MF decently\n mf_quats = read_head_pos(pos_fname)\n raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes')\n raw.crop(0, 5).load_data()\n # This is a little hack (aliasing while decimating) to make it much faster\n # for testing purposes only. We can relax this later if we find it breaks\n # something.\n raw_dec = _decimate_chpi(raw, 15)\n with catch_logging() as log:\n with pytest.warns(RuntimeWarning, match='cannot determine'):\n py_quats = _calculate_chpi_positions(raw_dec, t_window=0.2,\n verbose='debug')\n log = log.getvalue()\n assert '\\nHPIFIT' in log\n assert 'Computing 4385 HPI location guesses' in log\n _assert_quats(py_quats, mf_quats, dist_tol=0.001, angle_tol=0.7)\n\n # degenerate conditions\n raw_no_chpi = read_raw_fif(sample_fname)\n with pytest.raises(RuntimeError, match='cHPI information not found'):\n _calculate_chpi_positions(raw_no_chpi)\n raw_bad = raw.copy()\n del raw_bad.info['hpi_meas'][0]['hpi_coils'][0]['coil_freq']\n with pytest.raises(RuntimeError, match='cHPI information not found'):\n _calculate_chpi_positions(raw_bad)\n raw_bad = raw.copy()\n for d in raw_bad.info['dig']:\n if d['kind'] == FIFF.FIFFV_POINT_HPI:\n d['coord_frame'] = FIFF.FIFFV_COORD_UNKNOWN\n break\n with pytest.raises(RuntimeError, match='coordinate frame incorrect'):\n _calculate_chpi_positions(raw_bad)\n for d in raw_bad.info['dig']:\n if d['kind'] == FIFF.FIFFV_POINT_HPI:\n d['coord_frame'] = FIFF.FIFFV_COORD_HEAD\n d['r'] = np.ones(3)\n raw_bad.crop(0, 1.)\n picks = np.concatenate([np.arange(306, len(raw_bad.ch_names)),\n pick_types(raw_bad.info, meg=True)[::16]])\n raw_bad.pick_channels([raw_bad.ch_names[pick] for pick in picks])\n with pytest.warns(RuntimeWarning, match='Discrepancy'):\n with catch_logging() as log_file:\n _calculate_chpi_positions(raw_bad, t_step_min=1., verbose=True)\n # ignore HPI info header and [done] footer\n assert '0/5 good HPI fits' in log_file.getvalue()\n\n # half the rate cuts off cHPI coils\n raw.info['lowpass'] /= 2.\n with pytest.raises(RuntimeError, match='above the'):\n _calculate_chpi_positions(raw)\n\n\ndef test_calculate_chpi_positions_artemis():\n \"\"\"Test on 5k artemis data.\"\"\"\n raw = read_raw_artemis123(art_fname, preload=True)\n mf_quats = read_head_pos(art_mc_fname)\n mf_quats[:, 8:] /= 100 # old code errantly had this factor\n py_quats = _calculate_chpi_positions(raw, t_step_min=2., verbose='debug')\n _assert_quats(\n py_quats, mf_quats,\n dist_tol=0.001, angle_tol=1., err_rtol=0.7, vel_atol=1e-2)\n\n\ndef test_initial_fit_redo():\n \"\"\"Test that initial fits can be redone based on moments.\"\"\"\n raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes')\n slopes = np.array(\n [[c['slopes'] for c in raw.info['hpi_meas'][0]['hpi_coils']]])\n amps = np.linalg.norm(slopes, axis=-1)\n amps /= slopes.shape[-1]\n assert_array_less(amps, 5e-11)\n assert_array_less(1e-12, amps)\n proj, _, _ = _setup_ext_proj(raw.info, ext_order=1)\n chpi_amplitudes = dict(times=np.zeros(1), slopes=slopes, proj=proj)\n chpi_locs = compute_chpi_locs(raw.info, chpi_amplitudes)\n\n # check GOF\n coil_gof = raw.info['hpi_results'][0]['goodness']\n assert_allclose(chpi_locs['gofs'][0], coil_gof, atol=0.3) # XXX not good\n\n # check moment\n # XXX our forward and theirs differ by an extra mult by _MAG_FACTOR\n coil_moment = raw.info['hpi_results'][0]['moments'] / _MAG_FACTOR\n py_moment = chpi_locs['moments'][0]\n coil_amp = np.linalg.norm(coil_moment, axis=-1, keepdims=True)\n py_amp = np.linalg.norm(py_moment, axis=-1, keepdims=True)\n assert_allclose(coil_amp, py_amp, rtol=0.2)\n coil_ori = coil_moment / coil_amp\n py_ori = py_moment / py_amp\n angles = np.rad2deg(np.arccos(np.abs(np.sum(coil_ori * py_ori, axis=1))))\n assert_array_less(angles, 20)\n\n # check resulting dev_head_t\n head_pos = compute_head_pos(raw.info, chpi_locs)\n assert head_pos.shape == (1, 10)\n nm_pos = raw.info['dev_head_t']['trans']\n dist = 1000 * np.linalg.norm(nm_pos[:3, 3] - head_pos[0, 4:7])\n assert 0.1 < dist < 2\n angle = np.rad2deg(_angle_between_quats(\n rot_to_quat(nm_pos[:3, :3]), head_pos[0, 1:4]))\n assert 0.1 < angle < 2\n gof = head_pos[0, 7]\n assert_allclose(gof, 0.9999, atol=1e-4)\n\n\[email protected]_testing_data\ndef test_calculate_head_pos_chpi_on_chpi5_in_one_second_steps():\n \"\"\"Comparing estimated cHPI positions with MF results (one second).\"\"\"\n # Check to make sure our fits match MF decently\n mf_quats = read_head_pos(chpi5_pos_fname)\n raw = read_raw_fif(chpi5_fif_fname, allow_maxshield='yes')\n # the last two seconds contain a maxfilter problem!\n # fiff file timing: 26. to 43. seconds\n # maxfilter estimates a wrong head position for interval 16: 41.-42. sec\n raw = _decimate_chpi(raw.crop(0., 10.).load_data(), decim=8)\n # needs no interpolation, because maxfilter pos files comes with 1 s steps\n py_quats = _calculate_chpi_positions(\n raw, t_step_min=1.0, t_step_max=1.0, t_window=1.0, verbose='debug')\n _assert_quats(py_quats, mf_quats, dist_tol=0.002, angle_tol=1.2,\n vel_atol=3e-3) # 3 mm/s\n\n\[email protected]\[email protected]_testing_data\ndef test_calculate_head_pos_chpi_on_chpi5_in_shorter_steps():\n \"\"\"Comparing estimated cHPI positions with MF results (smaller steps).\"\"\"\n # Check to make sure our fits match MF decently\n mf_quats = read_head_pos(chpi5_pos_fname)\n raw = read_raw_fif(chpi5_fif_fname, allow_maxshield='yes')\n raw = _decimate_chpi(raw.crop(0., 5.).load_data(), decim=8)\n with pytest.warns(RuntimeWarning, match='cannot determine'):\n py_quats = _calculate_chpi_positions(\n raw, t_step_min=0.1, t_step_max=0.1, t_window=0.1, verbose='debug')\n # needs interpolation, tolerance must be increased\n _assert_quats(py_quats, mf_quats, dist_tol=0.002, angle_tol=1.2,\n vel_atol=0.02) # 2 cm/s is not great but probably fine\n\n\ndef test_simulate_calculate_head_pos_chpi():\n \"\"\"Test calculation of cHPI positions with simulated data.\"\"\"\n # Read info dict from raw FIF file\n info = read_info(raw_fname)\n # Tune the info structure\n chpi_channel = u'STI201'\n ncoil = len(info['hpi_results'][0]['order'])\n coil_freq = 10 + np.arange(ncoil) * 5\n hpi_subsystem = {'event_channel': chpi_channel,\n 'hpi_coils': [{'event_bits': np.array([256, 0, 256, 256],\n dtype=np.int32)},\n {'event_bits': np.array([512, 0, 512, 512],\n dtype=np.int32)},\n {'event_bits':\n np.array([1024, 0, 1024, 1024],\n dtype=np.int32)},\n {'event_bits':\n np.array([2048, 0, 2048, 2048],\n dtype=np.int32)}],\n 'ncoil': ncoil}\n\n info['hpi_subsystem'] = hpi_subsystem\n for l, freq in enumerate(coil_freq):\n info['hpi_meas'][0]['hpi_coils'][l]['coil_freq'] = freq\n picks = pick_types(info, meg=True, stim=True, eeg=False, exclude=[])\n info['sfreq'] = 100. # this will speed it up a lot\n info = pick_info(info, picks)\n info['chs'][info['ch_names'].index('STI 001')]['ch_name'] = 'STI201'\n info._update_redundant()\n info['projs'] = []\n\n info_trans = info['dev_head_t']['trans'].copy()\n\n dev_head_pos_ini = np.concatenate([rot_to_quat(info_trans[:3, :3]),\n info_trans[:3, 3]])\n ez = np.array([0, 0, 1]) # Unit vector in z-direction of head coordinates\n\n # Define some constants\n duration = 10 # Time / s\n\n # Quotient of head position sampling frequency\n # and raw sampling frequency\n head_pos_sfreq_quotient = 0.01\n\n # Round number of head positions to the next integer\n S = int(duration * info['sfreq'] * head_pos_sfreq_quotient)\n assert S == 10\n dz = 0.001 # Shift in z-direction is 0.1mm for each step\n\n dev_head_pos = np.zeros((S, 10))\n dev_head_pos[:, 0] = np.arange(S) * info['sfreq'] * head_pos_sfreq_quotient\n dev_head_pos[:, 1:4] = dev_head_pos_ini[:3]\n dev_head_pos[:, 4:7] = dev_head_pos_ini[3:] + \\\n np.outer(np.arange(S) * dz, ez)\n dev_head_pos[:, 7] = 1.0\n\n # m/s\n dev_head_pos[:, 9] = dz / (info['sfreq'] * head_pos_sfreq_quotient)\n\n # Round number of samples to the next integer\n raw_data = np.zeros((len(picks), int(duration * info['sfreq'] + 0.5)))\n raw = RawArray(raw_data, info)\n add_chpi(raw, dev_head_pos)\n quats = _calculate_chpi_positions(\n raw, t_step_min=raw.info['sfreq'] * head_pos_sfreq_quotient,\n t_step_max=raw.info['sfreq'] * head_pos_sfreq_quotient, t_window=1.0)\n _assert_quats(quats, dev_head_pos, dist_tol=0.001, angle_tol=1.,\n vel_atol=4e-3) # 4 mm/s\n\n\ndef _calculate_chpi_coil_locs(raw, verbose):\n \"\"\"Wrap to facilitate change diff.\"\"\"\n chpi_amplitudes = compute_chpi_amplitudes(raw, verbose=verbose)\n chpi_locs = compute_chpi_locs(raw.info, chpi_amplitudes, verbose=verbose)\n return _chpi_locs_to_times_dig(chpi_locs)\n\n\ndef _check_dists(info, cHPI_digs, n_bad=0, bad_low=0.02, bad_high=0.04):\n __tracebackhide__ = True\n orig = _get_hpi_initial_fit(info)\n hpi_coil_distances = cdist(orig, orig)\n new_pos = np.array([d['r'] for d in cHPI_digs])\n mask, distances = _compute_good_distances(hpi_coil_distances, new_pos)\n good_idx = np.where(mask)[0]\n assert len(good_idx) >= 3\n meds = np.empty(len(orig))\n for ii in range(len(orig)):\n idx = np.setdiff1d(good_idx, ii)\n meds[ii] = np.median(distances[ii][idx])\n meds = np.array(meds)\n assert_array_less(meds[good_idx], 0.003)\n bad_idx = np.where(~mask)[0]\n if len(bad_idx):\n bads = meds[bad_idx]\n assert_array_less(bad_low, bads)\n assert_array_less(bads, bad_high)\n\n\[email protected]_testing_data\ndef test_calculate_chpi_coil_locs_artemis():\n \"\"\"Test computing just cHPI locations.\"\"\"\n raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes', preload=True)\n # This is a little hack (aliasing while decimating) to make it much faster\n # for testing purposes only. We can relax this later if we find it breaks\n # something.\n raw_dec = _decimate_chpi(raw, 15)\n times, cHPI_digs = _calculate_chpi_coil_locs(raw_dec, verbose='debug')\n\n # spot check\n assert_allclose(times[0], 9., atol=1e-2)\n assert_allclose(cHPI_digs[0][2]['r'],\n [-0.01937833, 0.00346804, 0.06331209], atol=1e-3)\n assert_allclose(cHPI_digs[0][2]['gof'], 0.9957, atol=1e-3)\n\n assert_allclose(cHPI_digs[0][4]['r'],\n [-0.0655, 0.0755, 0.0004], atol=3e-3)\n assert_allclose(cHPI_digs[0][4]['gof'], 0.9323, atol=1e-3)\n _check_dists(raw.info, cHPI_digs[0], n_bad=1)\n\n # test on 5k artemis data\n raw = read_raw_artemis123(art_fname, preload=True)\n times, cHPI_digs = _calculate_chpi_coil_locs(raw, verbose='debug')\n\n assert_allclose(times[5], 1.5, atol=1e-3)\n assert_allclose(cHPI_digs[5][0]['gof'], 0.995, atol=5e-3)\n assert_allclose(cHPI_digs[5][0]['r'],\n [-0.0157, 0.0655, 0.0018], atol=1e-3)\n _check_dists(raw.info, cHPI_digs[5])\n coil_amplitudes = compute_chpi_amplitudes(raw)\n with pytest.raises(ValueError, match='too_close'):\n compute_chpi_locs(raw, coil_amplitudes, too_close='foo')\n # ensure values are in a reasonable range\n amps = np.linalg.norm(coil_amplitudes['slopes'], axis=-1)\n amps /= coil_amplitudes['slopes'].shape[-1]\n assert amps.shape == (len(coil_amplitudes['times']), 3)\n assert_array_less(amps, 1e-11)\n assert_array_less(1e-13, amps)\n\n\ndef assert_suppressed(new, old, suppressed, retained):\n \"\"\"Assert that some frequencies are suppressed and others aren't.\"\"\"\n __tracebackhide__ = True\n from scipy.signal import welch\n picks = pick_types(new.info, meg='grad')\n sfreq = new.info['sfreq']\n new = new.get_data(picks)\n old = old.get_data(picks)\n f, new = welch(new, sfreq, 'hann', nperseg=1024)\n _, old = welch(old, sfreq, 'hann', nperseg=1024)\n new = np.median(new, axis=0)\n old = np.median(old, axis=0)\n for freqs, lim in ((suppressed, (10, 60)), (retained, (-3, 3))):\n for freq in freqs:\n fidx = np.argmin(np.abs(f - freq))\n this_new = np.median(new[fidx])\n this_old = np.median(old[fidx])\n suppression = -10 * np.log10(this_new / this_old)\n assert lim[0] < suppression < lim[1], freq\n\n\[email protected]_testing_data\ndef test_chpi_subtraction_filter_chpi():\n \"\"\"Test subtraction of cHPI signals.\"\"\"\n raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes', preload=True)\n raw.info['bads'] = ['MEG0111']\n raw.del_proj()\n raw_orig = raw.copy().crop(0, 16)\n with catch_logging() as log:\n with pytest.deprecated_call(match='\"auto\"'):\n filter_chpi(raw, include_line=False, verbose=True)\n assert 'No average EEG' not in log.getvalue()\n assert '5 cHPI' in log.getvalue()\n # MaxFilter doesn't do quite as well as our algorithm with the last bit\n raw.crop(0, 16)\n # remove cHPI status chans\n raw_c = read_raw_fif(sss_hpisubt_fname).crop(0, 16).load_data()\n raw_c.pick_types(\n meg=True, eeg=True, eog=True, ecg=True, stim=True, misc=True)\n assert_meg_snr(raw, raw_c, 143, 624)\n # cHPI suppressed but not line freqs (or others)\n assert_suppressed(raw, raw_orig, np.arange(83, 324, 60), [30, 60, 150])\n raw = raw_orig.copy()\n with catch_logging() as log:\n with pytest.deprecated_call(match='\"auto\"'):\n filter_chpi(raw, include_line=True, verbose=True)\n log = log.getvalue()\n assert '5 cHPI' in log\n assert '6 line' in log\n # cHPI and line freqs suppressed\n suppressed = np.sort(np.concatenate([\n np.arange(83, 324, 60), np.arange(60, 301, 60),\n ]))\n assert_suppressed(raw, raw_orig, suppressed, [30, 150])\n\n # No HPI information\n raw = read_raw_fif(sample_fname, preload=True)\n raw_orig = raw.copy()\n assert raw.info['line_freq'] is None\n with pytest.raises(RuntimeError, match='line_freq.*consider setting it'):\n filter_chpi(raw, t_window=0.2)\n raw.info['line_freq'] = 60.\n with pytest.raises(RuntimeError, match='cHPI information not found'):\n filter_chpi(raw, t_window=0.2)\n # but this is allowed\n with catch_logging() as log:\n filter_chpi(raw, t_window='auto', allow_line_only=True, verbose=True)\n log = log.getvalue()\n assert '0 cHPI' in log\n assert '1 line' in log\n # Our one line freq suppressed but not others\n assert_suppressed(raw, raw_orig, [60], [30, 45, 75])\n\n # When MaxFliter downsamples, like::\n # $ maxfilter -nosss -ds 2 -f test_move_anon_raw.fif \\\n # -o test_move_anon_ds2_raw.fif\n # it can strip out some values of info, which we emulate here:\n raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes')\n raw = raw.crop(0, 1).load_data().resample(600., npad='auto')\n raw.info['lowpass'] = 200.\n del raw.info['maxshield']\n del raw.info['hpi_results'][0]['moments']\n del raw.info['hpi_subsystem']['event_channel']\n with catch_logging() as log:\n filter_chpi(raw, t_window='auto', verbose=True)\n with pytest.raises(ValueError, match='must be > 0'):\n filter_chpi(raw, t_window=-1)\n assert '2 cHPI' in log.getvalue()\n\n\ndef calculate_head_pos_ctf(raw):\n \"\"\"Wrap to facilitate API change.\"\"\"\n chpi_locs = extract_chpi_locs_ctf(raw)\n return compute_head_pos(raw.info, chpi_locs)\n\n\[email protected]_testing_data\ndef test_calculate_head_pos_ctf():\n \"\"\"Test extracting of cHPI positions from ctf data.\"\"\"\n raw = read_raw_ctf(ctf_chpi_fname)\n quats = calculate_head_pos_ctf(raw)\n mc_quats = read_head_pos(ctf_chpi_pos_fname)\n mc_quats[:, 9] /= 10000 # had old factor in there twice somehow...\n _assert_quats(quats, mc_quats, dist_tol=0.004, angle_tol=2.5, err_rtol=1.,\n vel_atol=7e-3) # 7 mm/s\n\n raw = read_raw_fif(ctf_fname)\n with pytest.raises(RuntimeError, match='Could not find'):\n calculate_head_pos_ctf(raw)\n\n\nrun_tests_if_main()\n", "# Authors: Alexandre Gramfort <[email protected]>\n# Eric Larson <[email protected]>\n# Oleh Kozynets <[email protected]>\n# Guillaume Favelier <[email protected]>\n# jona-sassenhagen <[email protected]>\n# Joan Massich <[email protected]>\n#\n# License: Simplified BSD\n\nimport os\nimport os.path as op\n\nimport numpy as np\nfrom scipy import sparse\n\nfrom .colormap import calculate_lut\nfrom .surface import Surface\nfrom .view import lh_views_dict, rh_views_dict, View\n\nfrom .._3d import _process_clim, _handle_time\n\nfrom ...morph import _hemi_morph\nfrom ...label import read_label\nfrom ...utils import _check_option, logger, verbose, fill_doc, _validate_type\n\n\nclass _Brain(object):\n \"\"\"Class for visualizing a brain.\n\n It is used for creating meshes of the given subject's\n cortex. The activation data can be shown on a mesh using add_data\n method. Figures, meshes, activation data and other information\n are stored as attributes of a class instance.\n\n Parameters\n ----------\n subject_id : str\n Subject name in Freesurfer subjects dir.\n hemi : str\n Hemisphere id (ie 'lh', 'rh', 'both', or 'split'). In the case\n of 'both', both hemispheres are shown in the same window.\n In the case of 'split' hemispheres are displayed side-by-side\n in different viewing panes.\n surf : str\n freesurfer surface mesh name (ie 'white', 'inflated', etc.).\n title : str\n Title for the window.\n cortex : str or None\n Specifies how the cortical surface is rendered.\n The name of one of the preset cortex styles can be:\n ``'classic'`` (default), ``'high_contrast'``,\n ``'low_contrast'``, or ``'bone'`` or a valid color name.\n Setting this to ``None`` is equivalent to ``(0.5, 0.5, 0.5)``.\n alpha : float in [0, 1]\n Alpha level to control opacity of the cortical surface.\n size : int | array-like, shape (2,)\n The size of the window, in pixels. can be one number to specify\n a square window, or a length-2 sequence to specify (width, height).\n background : tuple(int, int, int)\n The color definition of the background: (red, green, blue).\n foreground : matplotlib color\n Color of the foreground (will be used for colorbars and text).\n None (default) will use black or white depending on the value\n of ``background``.\n figure : list of Figure | None | int\n If None (default), a new window will be created with the appropriate\n views. For single view plots, the figure can be specified as int to\n retrieve the corresponding Mayavi window.\n subjects_dir : str | None\n If not None, this directory will be used as the subjects directory\n instead of the value set using the SUBJECTS_DIR environment\n variable.\n views : list | str\n views to use.\n offset : bool\n If True, aligs origin with medial wall. Useful for viewing inflated\n surface where hemispheres typically overlap (Default: True).\n show_toolbar : bool\n If True, toolbars will be shown for each view.\n offscreen : bool\n If True, rendering will be done offscreen (not shown). Useful\n mostly for generating images or screenshots, but can be buggy.\n Use at your own risk.\n interaction : str\n Not supported yet.\n Can be \"trackball\" (default) or \"terrain\", i.e. a turntable-style\n camera.\n units : str\n Can be 'm' or 'mm' (default).\n\n Attributes\n ----------\n geo : dict\n A dictionary of pysurfer.Surface objects for each hemisphere.\n overlays : dict\n The overlays.\n\n Notes\n -----\n This table shows the capabilities of each Brain backend (\"✓\" for full\n support, and \"-\" for partial support):\n\n .. table::\n :widths: auto\n\n +---------------------------+--------------+-----------------------+\n | 3D function: | surfer.Brain | mne.viz._brain._Brain |\n +===========================+==============+=======================+\n | add_data | ✓ | - |\n +---------------------------+--------------+-----------------------+\n | add_foci | ✓ | - |\n +---------------------------+--------------+-----------------------+\n | add_label | ✓ | - |\n +---------------------------+--------------+-----------------------+\n | add_text | ✓ | - |\n +---------------------------+--------------+-----------------------+\n | close | ✓ | ✓ |\n +---------------------------+--------------+-----------------------+\n | data | ✓ | ✓ |\n +---------------------------+--------------+-----------------------+\n | foci | ✓ | |\n +---------------------------+--------------+-----------------------+\n | labels | ✓ | |\n +---------------------------+--------------+-----------------------+\n | labels_dict | ✓ | |\n +---------------------------+--------------+-----------------------+\n | remove_data | ✓ | |\n +---------------------------+--------------+-----------------------+\n | remove_foci | ✓ | |\n +---------------------------+--------------+-----------------------+\n | remove_labels | ✓ | - |\n +---------------------------+--------------+-----------------------+\n | save_image | ✓ | ✓ |\n +---------------------------+--------------+-----------------------+\n | screenshot | ✓ | ✓ |\n +---------------------------+--------------+-----------------------+\n | show_view | ✓ | - |\n +---------------------------+--------------+-----------------------+\n | TimeViewer | ✓ | ✓ |\n +---------------------------+--------------+-----------------------+\n\n \"\"\"\n\n def __init__(self, subject_id, hemi, surf, title=None,\n cortex=None, alpha=1.0, size=800, background=\"black\",\n foreground=None, figure=None, subjects_dir=None,\n views=['lateral'], offset=True, show_toolbar=False,\n offscreen=False, interaction=None, units='mm'):\n from ..backends.renderer import backend, _get_renderer\n from matplotlib.colors import colorConverter\n\n if interaction is not None:\n raise ValueError('\"interaction\" parameter is not supported.')\n\n if hemi in ('both', 'split'):\n self._hemis = ('lh', 'rh')\n elif hemi in ('lh', 'rh'):\n self._hemis = (hemi, )\n else:\n raise KeyError('hemi has to be either \"lh\", \"rh\", \"split\", '\n 'or \"both\"')\n\n if isinstance(background, str):\n background = colorConverter.to_rgb(background)\n if isinstance(foreground, str):\n foreground = colorConverter.to_rgb(foreground)\n if isinstance(views, str):\n views = [views]\n n_row = len(views)\n col_dict = dict(lh=1, rh=1, both=1, split=2)\n n_col = col_dict[hemi]\n\n size = tuple(np.atleast_1d(size).round(0).astype(int).flat)\n if len(size) not in (1, 2):\n raise ValueError('\"size\" parameter must be an int or length-2 '\n 'sequence of ints.')\n fig_size = size if len(size) == 2 else size * 2 # 1-tuple to 2-tuple\n\n self._foreground = foreground\n self._hemi = hemi\n self._units = units\n self._title = title\n self._subject_id = subject_id\n self._subjects_dir = subjects_dir\n self._views = views\n self._times = None\n # for now only one color bar can be added\n # since it is the same for all figures\n self._colorbar_added = False\n # for now only one time label can be added\n # since it is the same for all figures\n self._time_label_added = False\n # array of data used by TimeViewer\n self._data = {}\n self.geo, self._hemi_meshes, self._overlays = {}, {}, {}\n self.set_time_interpolation('nearest')\n\n # load geometry for one or both hemispheres as necessary\n offset = None if (not offset or hemi != 'both') else 0.0\n\n if figure is not None and not isinstance(figure, int):\n backend._check_3d_figure(figure)\n if title is None:\n self._title = subject_id\n else:\n self._title = title\n self._renderer = _get_renderer(name=self._title, size=fig_size,\n bgcolor=background,\n shape=(n_row, n_col),\n fig=figure)\n\n for h in self._hemis:\n # Initialize a Surface object as the geometry\n geo = Surface(subject_id, h, surf, subjects_dir, offset,\n units=self._units)\n # Load in the geometry and curvature\n geo.load_geometry()\n geo.load_curvature()\n self.geo[h] = geo\n\n for ri, v in enumerate(views):\n for hi, h in enumerate(['lh', 'rh']):\n views_dict = lh_views_dict if hemi == 'lh' else rh_views_dict\n if not (hemi in ['lh', 'rh'] and h != hemi):\n ci = hi if hemi == 'split' else 0\n self._renderer.subplot(ri, ci)\n mesh_data = self._renderer.mesh(\n x=self.geo[h].coords[:, 0],\n y=self.geo[h].coords[:, 1],\n z=self.geo[h].coords[:, 2],\n triangles=self.geo[h].faces,\n color=self.geo[h].grey_curv,\n opacity=alpha,\n )\n if isinstance(mesh_data, tuple):\n _, mesh = mesh_data\n # add metadata to the mesh for picking\n mesh._hemi = h\n else:\n _, mesh = mesh_data, None\n self._hemi_meshes[h] = mesh\n self._renderer.set_camera(azimuth=views_dict[v].azim,\n elevation=views_dict[v].elev)\n\n # Force rendering\n self._renderer.show()\n\n @verbose\n def add_data(self, array, fmin=None, fmid=None, fmax=None,\n thresh=None, center=None, transparent=False, colormap=\"auto\",\n alpha=1, vertices=None, smoothing_steps=None, time=None,\n time_label=\"auto\", colorbar=True,\n hemi=None, remove_existing=None, time_label_size=None,\n initial_time=None, scale_factor=None, vector_alpha=None,\n clim=None, verbose=None):\n \"\"\"Display data from a numpy array on the surface.\n\n This provides a similar interface to\n :meth:`surfer.Brain.add_overlay`, but it displays\n it with a single colormap. It offers more flexibility over the\n colormap, and provides a way to display four-dimensional data\n (i.e., a timecourse) or five-dimensional data (i.e., a\n vector-valued timecourse).\n\n .. note:: ``fmin`` sets the low end of the colormap, and is separate\n from thresh (this is a different convention from\n :meth:`surfer.Brain.add_overlay`).\n\n Parameters\n ----------\n array : numpy array, shape (n_vertices[, 3][, n_times])\n Data array. For the data to be understood as vector-valued\n (3 values per vertex corresponding to X/Y/Z surface RAS),\n then ``array`` must be have all 3 dimensions.\n If vectors with no time dimension are desired, consider using a\n singleton (e.g., ``np.newaxis``) to create a \"time\" dimension\n and pass ``time_label=None`` (vector values are not supported).\n fmin : float\n Minimum value in colormap (uses real fmin if None).\n fmid : float\n Intermediate value in colormap (fmid between fmin and\n fmax if None).\n fmax : float\n Maximum value in colormap (uses real max if None).\n thresh : None or float\n Not supported yet.\n if not None, values below thresh will not be visible\n center : float or None\n if not None, center of a divergent colormap, changes the meaning of\n fmin, fmax and fmid.\n transparent : bool\n if True: use a linear transparency between fmin and fmid\n and make values below fmin fully transparent (symmetrically for\n divergent colormaps)\n colormap : str, list of color, or array\n name of matplotlib colormap to use, a list of matplotlib colors,\n or a custom look up table (an n x 4 array coded with RBGA values\n between 0 and 255), the default \"auto\" chooses a default divergent\n colormap, if \"center\" is given (currently \"icefire\"), otherwise a\n default sequential colormap (currently \"rocket\").\n alpha : float in [0, 1]\n alpha level to control opacity of the overlay.\n vertices : numpy array\n vertices for which the data is defined (needed if len(data) < nvtx)\n smoothing_steps : int or None\n number of smoothing steps (smoothing is used if len(data) < nvtx)\n The value 'nearest' can be used too.\n Default : 7\n time : numpy array\n time points in the data array (if data is 2D or 3D)\n %(time_label)s\n colorbar : bool\n whether to add a colorbar to the figure\n hemi : str | None\n If None, it is assumed to belong to the hemisphere being\n shown. If two hemispheres are being shown, an error will\n be thrown.\n remove_existing : bool\n Not supported yet.\n Remove surface added by previous \"add_data\" call. Useful for\n conserving memory when displaying different data in a loop.\n time_label_size : int\n Font size of the time label (default 14)\n initial_time : float | None\n Time initially shown in the plot. ``None`` to use the first time\n sample (default).\n scale_factor : float | None (default)\n Not supported yet.\n The scale factor to use when displaying glyphs for vector-valued\n data.\n vector_alpha : float | None\n Not supported yet.\n alpha level to control opacity of the arrows. Only used for\n vector-valued data. If None (default), ``alpha`` is used.\n %(verbose)s\n\n Notes\n -----\n If the data is defined for a subset of vertices (specified\n by the \"vertices\" parameter), a smoothing method is used to interpolate\n the data onto the high resolution surface. If the data is defined for\n subsampled version of the surface, smoothing_steps can be set to None,\n in which case only as many smoothing steps are applied until the whole\n surface is filled with non-zeros.\n\n Due to a Mayavi (or VTK) alpha rendering bug, ``vector_alpha`` is\n clamped to be strictly < 1.\n \"\"\"\n _validate_type(transparent, bool, 'transparent')\n _validate_type(vector_alpha, ('numeric', None), 'vector_alpha')\n _validate_type(scale_factor, ('numeric', None), 'scale_factor')\n\n # those parameters are not supported yet, only None is allowed\n _check_option('thresh', thresh, [None])\n _check_option('remove_existing', remove_existing, [None])\n _check_option('time_label_size', time_label_size, [None])\n\n hemi = self._check_hemi(hemi)\n array = np.asarray(array)\n vector_alpha = alpha if vector_alpha is None else vector_alpha\n self._data['vector_alpha'] = vector_alpha\n self._data['scale_factor'] = scale_factor\n\n # Create time array and add label if > 1D\n if array.ndim <= 1:\n time_idx = 0\n else:\n # check time array\n if time is None:\n time = np.arange(array.shape[-1])\n else:\n time = np.asarray(time)\n if time.shape != (array.shape[-1],):\n raise ValueError('time has shape %s, but need shape %s '\n '(array.shape[-1])' %\n (time.shape, (array.shape[-1],)))\n self._data[\"time\"] = time\n\n if self._n_times is None:\n self._times = time\n elif len(time) != self._n_times:\n raise ValueError(\"New n_times is different from previous \"\n \"n_times\")\n elif not np.array_equal(time, self._times):\n raise ValueError(\"Not all time values are consistent with \"\n \"previously set times.\")\n\n # initial time\n if initial_time is None:\n time_idx = 0\n else:\n time_idx = self._to_time_index(initial_time)\n\n # time label\n time_label, _ = _handle_time(time_label, 's', time)\n y_txt = 0.05 + 0.1 * bool(colorbar)\n\n if array.ndim == 3:\n if array.shape[1] != 3:\n raise ValueError('If array has 3 dimensions, array.shape[1] '\n 'must equal 3, got %s' % (array.shape[1],))\n fmin, fmid, fmax = _update_limits(\n fmin, fmid, fmax, center, array\n )\n\n if smoothing_steps is None:\n smoothing_steps = 7\n elif smoothing_steps == 'nearest':\n smoothing_steps = 0\n elif isinstance(smoothing_steps, int):\n if smoothing_steps < 0:\n raise ValueError('Expected value of `smoothing_steps` is'\n ' positive but {} was given.'.format(\n smoothing_steps))\n else:\n raise TypeError('Expected type of `smoothing_steps` is int or'\n ' NoneType but {} was given.'.format(\n type(smoothing_steps)))\n\n self._data['smoothing_steps'] = smoothing_steps\n self._data['clim'] = clim\n self._data['time'] = time\n self._data['initial_time'] = initial_time\n self._data['time_label'] = time_label\n self._data['time_idx'] = time_idx\n self._data['transparent'] = transparent\n # data specific for a hemi\n self._data[hemi] = dict()\n self._data[hemi]['actor'] = list()\n self._data[hemi]['mesh'] = list()\n self._data[hemi]['glyph_actor'] = None\n self._data[hemi]['glyph_mesh'] = None\n self._data[hemi]['array'] = array\n self._data[hemi]['vertices'] = vertices\n self._data['alpha'] = alpha\n self._data['colormap'] = colormap\n self._data['center'] = center\n self._data['fmin'] = fmin\n self._data['fmid'] = fmid\n self._data['fmax'] = fmax\n\n dt_max = fmax\n dt_min = fmin if center is None else -1 * fmax\n\n ctable = self.update_lut()\n self._data['ctable'] = ctable\n\n # 1) add the surfaces first\n for ri, v in enumerate(self._views):\n views_dict = lh_views_dict if hemi == 'lh' else rh_views_dict\n if self._hemi != 'split':\n ci = 0\n else:\n ci = 0 if hemi == 'lh' else 1\n self._renderer.subplot(ri, ci)\n\n mesh_data = self._renderer.mesh(\n x=self.geo[hemi].coords[:, 0],\n y=self.geo[hemi].coords[:, 1],\n z=self.geo[hemi].coords[:, 2],\n triangles=self.geo[hemi].faces,\n color=None,\n colormap=ctable,\n vmin=dt_min,\n vmax=dt_max,\n scalars=np.zeros(len(self.geo[hemi].coords)),\n )\n if isinstance(mesh_data, tuple):\n actor, mesh = mesh_data\n # add metadata to the mesh for picking\n mesh._hemi = hemi\n else:\n actor, mesh = mesh_data, None\n self._data[hemi]['actor'].append(actor)\n self._data[hemi]['mesh'].append(mesh)\n\n # 2) update time and smoothing properties\n # set_data_smoothing calls \"set_time_point\" for us, which will set\n # _current_time\n self.set_time_interpolation(self.time_interpolation)\n self.set_data_smoothing(smoothing_steps)\n\n # 3) add the other actors\n for ri, v in enumerate(self._views):\n views_dict = lh_views_dict if hemi == 'lh' else rh_views_dict\n if self._hemi != 'split':\n ci = 0\n else:\n ci = 0 if hemi == 'lh' else 1\n if not self._time_label_added and time_label is not None:\n time_actor = self._renderer.text2d(\n x_window=0.95, y_window=y_txt,\n size=time_label_size,\n text=time_label(self._current_time),\n justification='right'\n )\n self._data['time_actor'] = time_actor\n self._time_label_added = True\n if colorbar and not self._colorbar_added:\n self._renderer.scalarbar(source=actor, n_labels=8,\n bgcolor=(0.5, 0.5, 0.5))\n self._colorbar_added = True\n self._renderer.set_camera(azimuth=views_dict[v].azim,\n elevation=views_dict[v].elev)\n\n def add_label(self, label, color=None, alpha=1, scalar_thresh=None,\n borders=False, hemi=None, subdir=None):\n \"\"\"Add an ROI label to the image.\n\n Parameters\n ----------\n label : str | instance of Label\n label filepath or name. Can also be an instance of\n an object with attributes \"hemi\", \"vertices\", \"name\", and\n optionally \"color\" and \"values\" (if scalar_thresh is not None).\n color : matplotlib-style color | None\n anything matplotlib accepts: string, RGB, hex, etc. (default\n \"crimson\")\n alpha : float in [0, 1]\n alpha level to control opacity\n scalar_thresh : None or number\n threshold the label ids using this value in the label\n file's scalar field (i.e. label only vertices with\n scalar >= thresh)\n borders : bool | int\n Show only label borders. If int, specify the number of steps\n (away from the true border) along the cortical mesh to include\n as part of the border definition.\n hemi : str | None\n If None, it is assumed to belong to the hemipshere being\n shown.\n subdir : None | str\n If a label is specified as name, subdir can be used to indicate\n that the label file is in a sub-directory of the subject's\n label directory rather than in the label directory itself (e.g.\n for ``$SUBJECTS_DIR/$SUBJECT/label/aparc/lh.cuneus.label``\n ``brain.add_label('cuneus', subdir='aparc')``).\n\n Notes\n -----\n To remove previously added labels, run Brain.remove_labels().\n \"\"\"\n from matplotlib.colors import colorConverter\n if isinstance(label, str):\n if color is None:\n color = \"crimson\"\n\n if os.path.isfile(label):\n filepath = label\n label = read_label(filepath)\n hemi = label.hemi\n label_name = os.path.basename(filepath).split('.')[1]\n else:\n hemi = self._check_hemi(hemi)\n label_name = label\n label_fname = \".\".join([hemi, label_name, 'label'])\n if subdir is None:\n filepath = op.join(self._subjects_dir, self._subject_id,\n 'label', label_fname)\n else:\n filepath = op.join(self._subjects_dir, self._subject_id,\n 'label', subdir, label_fname)\n if not os.path.exists(filepath):\n raise ValueError('Label file %s does not exist'\n % filepath)\n label = read_label(filepath)\n ids = label.vertices\n scalars = label.values\n else:\n # try to extract parameters from label instance\n try:\n hemi = label.hemi\n ids = label.vertices\n if label.name is None:\n label_name = 'unnamed'\n else:\n label_name = str(label.name)\n\n if color is None:\n if hasattr(label, 'color') and label.color is not None:\n color = label.color\n else:\n color = \"crimson\"\n\n if scalar_thresh is not None:\n scalars = label.values\n except Exception:\n raise ValueError('Label was not a filename (str), and could '\n 'not be understood as a class. The class '\n 'must have attributes \"hemi\", \"vertices\", '\n '\"name\", and (if scalar_thresh is not None)'\n '\"values\"')\n hemi = self._check_hemi(hemi)\n\n if scalar_thresh is not None:\n ids = ids[scalars >= scalar_thresh]\n\n # XXX: add support for label_name\n self._label_name = label_name\n\n label = np.zeros(self.geo[hemi].coords.shape[0])\n label[ids] = 1\n color = colorConverter.to_rgba(color, alpha)\n cmap = np.array([(0, 0, 0, 0,), color])\n ctable = np.round(cmap * 255).astype(np.uint8)\n\n for ri, v in enumerate(self._views):\n if self._hemi != 'split':\n ci = 0\n else:\n ci = 0 if hemi == 'lh' else 1\n views_dict = lh_views_dict if hemi == 'lh' else rh_views_dict\n self._renderer.subplot(ri, ci)\n if borders:\n surface = {\n 'rr': self.geo[hemi].coords,\n 'tris': self.geo[hemi].faces,\n }\n self._renderer.contour(surface, label, [1.0], color=color,\n kind='tube')\n else:\n self._renderer.mesh(x=self.geo[hemi].coords[:, 0],\n y=self.geo[hemi].coords[:, 1],\n z=self.geo[hemi].coords[:, 2],\n triangles=self.geo[hemi].faces,\n scalars=label,\n color=None,\n colormap=ctable,\n backface_culling=False)\n self._renderer.set_camera(azimuth=views_dict[v].azim,\n elevation=views_dict[v].elev)\n\n def add_foci(self, coords, coords_as_verts=False, map_surface=None,\n scale_factor=1, color=\"white\", alpha=1, name=None,\n hemi=None):\n \"\"\"Add spherical foci, possibly mapping to displayed surf.\n\n The foci spheres can be displayed at the coordinates given, or\n mapped through a surface geometry. In other words, coordinates\n from a volume-based analysis in MNI space can be displayed on an\n inflated average surface by finding the closest vertex on the\n white surface and mapping to that vertex on the inflated mesh.\n\n Parameters\n ----------\n coords : numpy array\n x, y, z coordinates in stereotaxic space (default) or array of\n vertex ids (with ``coord_as_verts=True``)\n coords_as_verts : bool\n whether the coords parameter should be interpreted as vertex ids\n map_surface : Freesurfer surf or None\n surface to map coordinates through, or None to use raw coords\n scale_factor : float\n Controls the size of the foci spheres (relative to 1cm).\n color : matplotlib color code\n HTML name, RBG tuple, or hex code\n alpha : float in [0, 1]\n opacity of focus gylphs\n name : str\n internal name to use\n hemi : str | None\n If None, it is assumed to belong to the hemipshere being\n shown. If two hemispheres are being shown, an error will\n be thrown.\n \"\"\"\n from matplotlib.colors import colorConverter\n hemi = self._check_hemi(hemi)\n\n # those parameters are not supported yet, only None is allowed\n _check_option('map_surface', map_surface, [None])\n\n # Figure out how to interpret the first parameter\n if coords_as_verts:\n coords = self.geo[hemi].coords[coords]\n\n # Convert the color code\n if not isinstance(color, tuple):\n color = colorConverter.to_rgb(color)\n\n if self._units == 'm':\n scale_factor = scale_factor / 1000.\n for ri, v in enumerate(self._views):\n views_dict = lh_views_dict if hemi == 'lh' else rh_views_dict\n if self._hemi != 'split':\n ci = 0\n else:\n ci = 0 if hemi == 'lh' else 1\n self._renderer.subplot(ri, ci)\n self._renderer.sphere(center=coords, color=color,\n scale=(10. * scale_factor),\n opacity=alpha)\n self._renderer.set_camera(azimuth=views_dict[v].azim,\n elevation=views_dict[v].elev)\n\n def add_text(self, x, y, text, name=None, color=None, opacity=1.0,\n row=-1, col=-1, font_size=None, justification=None):\n \"\"\"Add a text to the visualization.\n\n Parameters\n ----------\n x : Float\n x coordinate\n y : Float\n y coordinate\n text : str\n Text to add\n name : str\n Name of the text (text label can be updated using update_text())\n color : Tuple\n Color of the text. Default is the foreground color set during\n initialization (default is black or white depending on the\n background color).\n opacity : Float\n Opacity of the text. Default: 1.0\n row : int\n Row index of which brain to use\n col : int\n Column index of which brain to use\n \"\"\"\n # XXX: support `name` should be added when update_text/remove_text\n # are implemented\n # _check_option('name', name, [None])\n\n self._renderer.text2d(x_window=x, y_window=y, text=text, color=color,\n size=font_size, justification=justification)\n\n def remove_labels(self, labels=None):\n \"\"\"Remove one or more previously added labels from the image.\n\n Parameters\n ----------\n labels : None | str | list of str\n Labels to remove. Can be a string naming a single label, or None to\n remove all labels. Possible names can be found in the Brain.labels\n attribute.\n \"\"\"\n pass\n\n def close(self):\n \"\"\"Close all figures and cleanup data structure.\"\"\"\n self._renderer.close()\n\n def show_view(self, view=None, roll=None, distance=None, row=0, col=0,\n hemi=None):\n \"\"\"Orient camera to display view.\"\"\"\n hemi = self._hemi if hemi is None else hemi\n views_dict = lh_views_dict if hemi == 'lh' else rh_views_dict\n if isinstance(view, str):\n view = views_dict.get(view)\n elif isinstance(view, dict):\n view = View(azim=view['azimuth'],\n elev=view['elevation'])\n self._renderer.subplot(row, col)\n self._renderer.set_camera(azimuth=view.azim,\n elevation=view.elev)\n self._renderer.reset_camera()\n\n def save_image(self, filename, mode='rgb'):\n \"\"\"Save view from all panels to disk.\n\n Parameters\n ----------\n filename: string\n path to new image file\n mode : string\n Either 'rgb' or 'rgba' for values to return.\n \"\"\"\n self._renderer.screenshot(mode=mode, filename=filename)\n\n def screenshot(self, mode='rgb'):\n \"\"\"Generate a screenshot of current view.\n\n Parameters\n ----------\n mode : string\n Either 'rgb' or 'rgba' for values to return.\n\n Returns\n -------\n screenshot : array\n Image pixel values.\n \"\"\"\n return self._renderer.screenshot(mode)\n\n def update_lut(self, fmin=None, fmid=None, fmax=None, alpha=None):\n \"\"\"Update color map.\n\n Parameters\n ----------\n fmin : float | None\n Minimum value in colormap.\n fmid : float | None\n Intermediate value in colormap (fmid between fmin and\n fmax).\n fmax : float | None\n Maximum value in colormap.\n \"\"\"\n alpha = alpha if alpha is not None else self._data['alpha']\n center = self._data['center']\n colormap = self._data['colormap']\n transparent = self._data['transparent']\n lims = dict(fmin=fmin, fmid=fmid, fmax=fmax)\n lims = {key: self._data[key] if val is None else val\n for key, val in lims.items()}\n assert all(val is not None for val in lims.values())\n if lims['fmin'] > lims['fmid']:\n lims['fmin'] = lims['fmid']\n if lims['fmax'] < lims['fmid']:\n lims['fmax'] = lims['fmid']\n self._data.update(lims)\n self._data['ctable'] = \\\n calculate_lut(colormap, alpha=alpha, center=center,\n transparent=transparent, **lims)\n return self._data['ctable']\n\n def set_data_smoothing(self, n_steps):\n \"\"\"Set the number of smoothing steps.\n\n Parameters\n ----------\n n_steps : int\n Number of smoothing steps\n \"\"\"\n for hemi in ['lh', 'rh']:\n hemi_data = self._data.get(hemi)\n if hemi_data is not None:\n if len(hemi_data['array']) >= self.geo[hemi].x.shape[0]:\n continue\n vertices = hemi_data['vertices']\n if vertices is None:\n raise ValueError(\n 'len(data) < nvtx (%s < %s): the vertices '\n 'parameter must not be None'\n % (len(hemi_data), self.geo[hemi].x.shape[0]))\n morph_n_steps = 'nearest' if n_steps == 0 else n_steps\n maps = sparse.eye(len(self.geo[hemi].coords), format='csr')\n smooth_mat = _hemi_morph(\n self.geo[hemi].faces,\n np.arange(len(self.geo[hemi].coords)),\n vertices, morph_n_steps, maps, warn=False)\n self._data[hemi]['smooth_mat'] = smooth_mat\n self.set_time_point(self._data['time_idx'])\n self._data['smoothing_steps'] = n_steps\n\n @property\n def _n_times(self):\n return len(self._times) if self._times is not None else None\n\n @property\n def time_interpolation(self):\n \"\"\"The interpolation mode.\"\"\"\n return self._time_interpolation\n\n @fill_doc\n def set_time_interpolation(self, interpolation):\n \"\"\"Set the interpolation mode.\n\n Parameters\n ----------\n %(brain_time_interpolation)s\n \"\"\"\n _check_option('interpolation', interpolation,\n ('linear', 'nearest', 'zero', 'slinear', 'quadratic',\n 'cubic'))\n self._time_interpolation = str(interpolation)\n del interpolation\n self._time_interp_funcs = dict()\n self._time_interp_inv = None\n if self._times is not None:\n idx = np.arange(self._n_times)\n for hemi in ['lh', 'rh']:\n hemi_data = self._data.get(hemi)\n if hemi_data is not None:\n array = hemi_data['array']\n self._time_interp_funcs[hemi] = _safe_interp1d(\n idx, array, self._time_interpolation, axis=-1,\n assume_sorted=True)\n self._time_interp_inv = _safe_interp1d(idx, self._times)\n\n def set_time_point(self, time_idx):\n \"\"\"Set the time point shown (can be a float to interpolate).\"\"\"\n from ..backends._pyvista import _set_mesh_scalars\n current_act_data = list()\n time_actor = self._data.get('time_actor', None)\n time_label = self._data.get('time_label', None)\n for hemi in ['lh', 'rh']:\n hemi_data = self._data.get(hemi)\n if hemi_data is not None:\n array = hemi_data['array']\n # interpolate in time\n if array.ndim == 1:\n act_data = array\n self._current_time = 0\n else:\n act_data = self._time_interp_funcs[hemi](time_idx)\n self._current_time = self._time_interp_inv(time_idx)\n if array.ndim == 3:\n vectors = act_data\n act_data = np.linalg.norm(act_data, axis=1)\n self._current_time = self._time_interp_inv(time_idx)\n current_act_data.append(act_data)\n if time_actor is not None and time_label is not None:\n time_actor.SetInput(time_label(self._current_time))\n\n # interpolate in space\n smooth_mat = hemi_data['smooth_mat']\n if smooth_mat is not None:\n act_data = smooth_mat.dot(act_data)\n\n # update the mesh scalar values\n for mesh in hemi_data['mesh']:\n if mesh is not None:\n _set_mesh_scalars(mesh, act_data, 'Data')\n\n # update the glyphs\n if array.ndim == 3:\n self.update_glyphs(hemi, vectors)\n self._current_act_data = np.concatenate(current_act_data)\n self._data['time_idx'] = time_idx\n\n def update_glyphs(self, hemi, vectors):\n from ..backends._pyvista import (_set_colormap_range,\n _add_polydata_actor)\n hemi_data = self._data.get(hemi)\n if hemi_data is not None:\n vertices = hemi_data['vertices']\n fmin = self._data['fmin']\n fmid = self._data['fmid']\n fmax = self._data['fmax']\n ctable = self.update_lut(fmin=fmin, fmid=fmid, fmax=fmax, alpha=1)\n ctable = (ctable * 255).astype(np.uint8)\n vector_alpha = self._data['vector_alpha']\n scale_factor = self._data['scale_factor']\n rng = [fmin, fmax]\n vertices = slice(None) if vertices is None else vertices\n x, y, z = np.array(self.geo[hemi].coords)[vertices].T\n\n polydata = self._renderer.quiver3d(\n x, y, z,\n vectors[:, 0], vectors[:, 1], vectors[:, 2],\n color=None,\n mode='2darrow',\n scale_mode='vector',\n scale=scale_factor,\n opacity=vector_alpha,\n name=str(hemi) + \"_glyph\"\n )\n if polydata is not None:\n if hemi_data['glyph_mesh'] is None:\n hemi_data['glyph_mesh'] = polydata\n glyph_actor = _add_polydata_actor(\n plotter=self._renderer.plotter,\n polydata=polydata,\n hide=True\n )\n hemi_data['glyph_actor'] = glyph_actor\n glyph_actor.GetProperty().SetLineWidth(2.)\n else:\n glyph_actor = hemi_data['glyph_actor']\n glyph_mesh = hemi_data['glyph_mesh']\n glyph_mesh.shallow_copy(polydata)\n _set_colormap_range(glyph_actor, ctable, None, rng)\n # the glyphs are now ready to be displayed\n glyph_actor.VisibilityOn()\n\n def update_fmax(self, fmax):\n \"\"\"Set the colorbar max point.\"\"\"\n from ..backends._pyvista import _set_colormap_range\n ctable = self.update_lut(fmax=fmax)\n ctable = (ctable * 255).astype(np.uint8)\n center = self._data['center']\n fmin = self._data['fmin']\n for hemi in ['lh', 'rh']:\n hemi_data = self._data.get(hemi)\n if hemi_data is not None:\n for actor in hemi_data['actor']:\n dt_max = fmax\n dt_min = fmin if center is None else -1 * fmax\n rng = [dt_min, dt_max]\n if self._colorbar_added:\n scalar_bar = self._renderer.plotter.scalar_bar\n else:\n scalar_bar = None\n _set_colormap_range(actor, ctable, scalar_bar, rng)\n self._data['fmax'] = fmax\n self._data['ctable'] = ctable\n\n def update_fmid(self, fmid):\n \"\"\"Set the colorbar mid point.\"\"\"\n from ..backends._pyvista import _set_colormap_range\n ctable = self.update_lut(fmid=fmid)\n ctable = (ctable * 255).astype(np.uint8)\n for hemi in ['lh', 'rh']:\n hemi_data = self._data.get(hemi)\n if hemi_data is not None:\n for actor in hemi_data['actor']:\n if self._colorbar_added:\n scalar_bar = self._renderer.plotter.scalar_bar\n else:\n scalar_bar = None\n _set_colormap_range(actor, ctable, scalar_bar)\n self._data['fmid'] = fmid\n self._data['ctable'] = ctable\n\n def update_fmin(self, fmin):\n \"\"\"Set the colorbar min point.\"\"\"\n from ..backends._pyvista import _set_colormap_range\n ctable = self.update_lut(fmin=fmin)\n ctable = (ctable * 255).astype(np.uint8)\n center = self._data['center']\n fmax = self._data['fmax']\n for hemi in ['lh', 'rh']:\n hemi_data = self._data.get(hemi)\n if hemi_data is not None:\n for actor in hemi_data['actor']:\n dt_max = fmax\n dt_min = fmin if center is None else -1 * fmax\n rng = [dt_min, dt_max]\n if self._colorbar_added:\n scalar_bar = self._renderer.plotter.scalar_bar\n else:\n scalar_bar = None\n _set_colormap_range(actor, ctable, scalar_bar, rng)\n self._data['fmin'] = fmin\n self._data['ctable'] = ctable\n\n def update_fscale(self, fscale):\n \"\"\"Scale the colorbar points.\"\"\"\n from ..backends._pyvista import _set_colormap_range\n center = self._data['center']\n fmin = self._data['fmin'] * fscale\n fmid = self._data['fmid'] * fscale\n fmax = self._data['fmax'] * fscale\n ctable = self.update_lut(fmin=fmin, fmid=fmid, fmax=fmax)\n ctable = (ctable * 255).astype(np.uint8)\n for hemi in ['lh', 'rh']:\n hemi_data = self._data.get(hemi)\n if hemi_data is not None:\n for actor in hemi_data['actor']:\n dt_max = fmax\n dt_min = fmin if center is None else -1 * fmax\n rng = [dt_min, dt_max]\n if self._colorbar_added:\n scalar_bar = self._renderer.plotter.scalar_bar\n else:\n scalar_bar = None\n _set_colormap_range(actor, ctable, scalar_bar, rng)\n self._data['ctable'] = ctable\n self._data['fmin'] = fmin\n self._data['fmid'] = fmid\n self._data['fmax'] = fmax\n\n def update_auto_scaling(self, restore=False):\n from ..backends._pyvista import _set_colormap_range\n user_clim = self._data['clim']\n if user_clim is not None and 'lims' in user_clim:\n allow_pos_lims = False\n else:\n allow_pos_lims = True\n if user_clim is not None and restore:\n clim = user_clim\n else:\n clim = 'auto'\n colormap = self._data['colormap']\n transparent = self._data['transparent']\n mapdata = _process_clim(\n clim, colormap, transparent, self._current_act_data,\n allow_pos_lims)\n diverging = 'pos_lims' in mapdata['clim']\n colormap = mapdata['colormap']\n scale_pts = mapdata['clim']['pos_lims' if diverging else 'lims']\n transparent = mapdata['transparent']\n del mapdata\n fmin, fmid, fmax = scale_pts\n center = 0. if diverging else None\n self._data['center'] = center\n self._data['colormap'] = colormap\n self._data['transparent'] = transparent\n ctable = self.update_lut(fmin=fmin, fmid=fmid, fmax=fmax)\n ctable = (ctable * 255).astype(np.uint8)\n for hemi in ['lh', 'rh']:\n hemi_data = self._data.get(hemi)\n if hemi_data is not None:\n for actor in hemi_data['actor']:\n dt_max = fmax\n dt_min = fmin if center is None else -1 * fmax\n rng = [dt_min, dt_max]\n if self._colorbar_added:\n scalar_bar = self._renderer.plotter.scalar_bar\n else:\n scalar_bar = None\n _set_colormap_range(actor, ctable, scalar_bar, rng)\n self._data['ctable'] = ctable\n\n def _to_time_index(self, value):\n \"\"\"Return the interpolated time index of the given time value.\"\"\"\n time = self._data['time']\n value = np.interp(value, time, np.arange(len(time)))\n return value\n\n @property\n def data(self):\n \"\"\"Data used by time viewer and color bar widgets.\"\"\"\n return self._data\n\n @property\n def views(self):\n return self._views\n\n @property\n def hemis(self):\n return self._hemis\n\n def _show(self):\n \"\"\"Request rendering of the window.\"\"\"\n try:\n return self._renderer.show()\n except RuntimeError:\n logger.info(\"No active/running renderer available.\")\n\n def _check_hemi(self, hemi):\n \"\"\"Check for safe single-hemi input, returns str.\"\"\"\n if hemi is None:\n if self._hemi not in ['lh', 'rh']:\n raise ValueError('hemi must not be None when both '\n 'hemispheres are displayed')\n else:\n hemi = self._hemi\n elif hemi not in ['lh', 'rh']:\n extra = ' or None' if self._hemi in ['lh', 'rh'] else ''\n raise ValueError('hemi must be either \"lh\" or \"rh\"' +\n extra + \", got \" + str(hemi))\n return hemi\n\n def scale_data_colormap(self, fmin, fmid, fmax, transparent,\n center=None, alpha=1.0, data=None, verbose=None):\n \"\"\"Scale the data colormap.\"\"\"\n lut_lst = self._data['ctable']\n n_col = len(lut_lst)\n\n # apply the lut on every surfaces\n for hemi in ['lh', 'rh']:\n hemi_data = self._data.get(hemi)\n if hemi_data is not None:\n for actor in hemi_data['actor']:\n vtk_lut = actor.GetMapper().GetLookupTable()\n vtk_lut.SetNumberOfColors(n_col)\n vtk_lut.SetRange([fmin, fmax])\n vtk_lut.Build()\n for i in range(0, n_col):\n lt = lut_lst[i]\n vtk_lut.SetTableValue(i, lt[0], lt[1], lt[2], alpha)\n self.update_fscale(1.0)\n\n def enable_depth_peeling(self):\n \"\"\"Enable depth peeling.\"\"\"\n self._renderer.enable_depth_peeling()\n\n\ndef _safe_interp1d(x, y, kind='linear', axis=-1, assume_sorted=False):\n \"\"\"Work around interp1d not liking singleton dimensions.\"\"\"\n from scipy.interpolate import interp1d\n if y.shape[axis] == 1:\n def func(x):\n return y.copy()\n return func\n else:\n return interp1d(x, y, kind, axis=axis, assume_sorted=assume_sorted)\n\n\ndef _update_limits(fmin, fmid, fmax, center, array):\n if center is None:\n if fmin is None:\n fmin = array.min() if array.size > 0 else 0\n if fmax is None:\n fmax = array.max() if array.size > 0 else 1\n else:\n if fmin is None:\n fmin = 0\n if fmax is None:\n fmax = np.abs(center - array).max() if array.size > 0 else 1\n if fmid is None:\n fmid = (fmin + fmax) / 2.\n\n if fmin >= fmid:\n raise RuntimeError('min must be < mid, got %0.4g >= %0.4g'\n % (fmin, fmid))\n if fmid >= fmax:\n raise RuntimeError('mid must be < max, got %0.4g >= %0.4g'\n % (fmid, fmax))\n\n return fmin, fmid, fmax\n" ]
[ [ "numpy.where", "scipy.signal.welch", "numpy.arange", "numpy.argmax", "scipy.interpolate.interp1d", "numpy.zeros", "numpy.isclose", "numpy.median", "scipy.spatial.distance.cdist", "numpy.log10", "numpy.testing.assert_allclose", "numpy.random.RandomState", "numpy.array", "numpy.sum", "numpy.abs", "numpy.isfinite", "numpy.linalg.norm", "numpy.setdiff1d", "numpy.ones", "numpy.testing.assert_array_less", "numpy.mod" ], [ "numpy.abs", "numpy.array_equal", "numpy.asarray", "numpy.arange", "numpy.linalg.norm", "matplotlib.colors.colorConverter.to_rgb", "numpy.concatenate", "numpy.round", "numpy.atleast_1d", "scipy.interpolate.interp1d", "matplotlib.colors.colorConverter.to_rgba", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "1.3", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] } ]
hieu-nguyen-tri/piro
[ "1abe8ff3bb318982dc8ffd6a09744a28ffbbb7b8" ]
[ "piro/route.py" ]
[ "import itertools\nimport scipy\nimport numpy as np\nimport plotly.express as px\nimport pandas as pd\nimport os\nimport json\nfrom copy import deepcopy\nfrom pymatgen import MPRester\nfrom pymatgen.analysis.phase_diagram import PhaseDiagram\nfrom pymatgen.util.string import latexify\nfrom piro.data import GASES, GAS_RELEASE, DEFAULT_GAS_PRESSURES\nfrom piro.utils import get_v, epitaxy, similarity, update_gases, through_cache\nfrom piro import RXN_FILES\nfrom tqdm.autonotebook import tqdm\nfrom scipy.special import comb\n\n\n# TODO: for elements and gases (references) - don't allow multiple entries\n# TODO: for E_d, test q = max(q_phases) - max of q, assuming that would be the limiting step\n\n\nclass SynthesisRoutes:\n def __init__(\n self,\n target_entry_id,\n confine_to_icsd=True,\n confine_to_stables=True,\n hull_distance=np.inf,\n simple_precursors=False,\n explicit_includes=None,\n allow_gas_release=False,\n add_element=None,\n temperature=298,\n pressure=1,\n use_cache=True,\n exclude_compositions=None,\n entries=None,\n epitaxies=None,\n similarities=None,\n sigma=None,\n transport_constant=None,\n custom_target_entry=None,\n flexible_competition=None,\n ):\n \"\"\"\n Synthesis reaction route recommendations, derived semi-empirically using the Classical Nucleation Theory\n and high-throughput DFT data.\n Precursor_library, epitaxial matches and similarities are precomputed upon instantiation.\n Args:\n target_entry_id (str): Materials Project entry id for target material\n confine_to_icsd (bool): Use ICSD-sourced entries to find precursors. Defaults to True.\n confine_to_stables: Use stable entries only to find. Defaults to True.\n hull_distance (float): Use entries within this distance to hull (eV/atom). Can significantly increase\n number of possible precursors and slow down the predictions. Ignored if confine_to_stables is True.\n simple_precursors (bool or int): If True, or integer >0, precursors with fewer components will\n be considered.\n explicit_includes (list): list of mp-ids to explicitly include. For example, confine_to_stables may exclude\n certain common precursors in some systems, if they are not on the convex-hull - this allows such\n potential precursors to be added to the library.\n exclude_compositions (list): list of compositions to avoid in precursor library.\n allow_gas_release (bool): Many reactions require the release of gases like CO2, O2, etc. depending on the\n precursors, which requires explicitly considering them in balancing the reactions. Defaults to False.\n add_element (str): Add an element to the chemical space of libraries that doesn't exist in the target\n material. Best example is 'C', which would allow carbonates to be added to the precursor library.\n temperature (float): Temperature (in Kelvin) to consider in free energy adjustments for gases.\n pressure (dict or float): Gas pressures (in atm). If float, all gases are assumed to have the same constant\n pressure. A dictionary in the form of {'O2': 0.21, 'CO2':, 0.05} can be provided to explicitly\n specify partial pressures. If given None, a default pressure dictionary will be used pertaining to\n open atmosphere conditions. Defaults to 1 atm.\n use_cache (bool): if True, caches the epitaxy and similarity information for future reuse.\n entries (list): List of Materials Project ComputedEntry objects, as can be obtained via the API. If provided\n these entries will be used while forming the precursor library. If not provided, MP database will be\n queried via the Rester API to get the most up-to-date entries. Defaults to None.\n epitaxies (list): List of minimum matching areas between the target and entries, normally as computed\n via the get_epitaxies method. Recommended use is to leave as None.\n similarities: List of similarity quantiles between the target and entries, normally as computed\n via the get_similarities method. Recommended use is to leave as None.\n sigma (float): surface energy constant (eV/Ang^2) to be used in predictions. Defaults to equivalent\n 2.0 J/m^2.\n transport_constant (float): diffusion barrier coefficient (max barrier). Defaults to 10.0.\n custom_target_entry (MP entry): custom computed entry object pymatgen\n flexible_competition (int): whether lower order targets are allowed in competing reactions. Defaults to 0\n which forces competing reactions to have products of the same order as target. If 1, one order smaller\n compounds and so on.\n \"\"\"\n\n self.target_entry_id = target_entry_id\n self.confine_to_icsd = confine_to_icsd\n self.confine_to_stables = confine_to_stables\n self.simple_precursors = simple_precursors\n self.explicit_includes = explicit_includes if explicit_includes else []\n self.allow_gas_release = allow_gas_release\n self.temperature = temperature\n self.pressure = pressure if pressure else DEFAULT_GAS_PRESSURES\n self.add_element = add_element if add_element else []\n self.entries = entries\n self.hull_distance = hull_distance\n self.use_cache = use_cache\n self.confine_competing_to_icsd = False\n self.exclude_compositions = exclude_compositions\n self.custom_target_entry = custom_target_entry\n self.flexible_competition = flexible_competition if flexible_competition else 0\n self._sigma = sigma if sigma else 2 * 6.242 * 0.01\n self._transport_constant = transport_constant if transport_constant else 10.0\n\n self.plot_data = None\n self.reactions = {}\n if not entries:\n if not custom_target_entry:\n with MPRester() as mpr:\n _e = mpr.get_entry_by_material_id(self.target_entry_id)\n else:\n _e = custom_target_entry\n self.elts = list(_e.composition.as_dict().keys())\n if add_element:\n self.elts.append(add_element)\n self.get_mp_entries()\n else:\n self.elts = list(self.target_entry.composition.as_dict().keys())\n\n self.get_precursor_library()\n self.epitaxies = epitaxies if epitaxies else self.get_epitaxies()\n self.similarities = similarities if similarities else self.get_similarities()\n print(\"Precursor library ready.\")\n\n def get_mp_entries(self):\n with MPRester() as mpr:\n self.entries = mpr.get_entries_in_chemsys(\n self.elts,\n inc_structure=\"final\",\n property_data=[\"icsd_ids\", \"formation_energy_per_atom\"],\n )\n for entry in self.entries:\n entry.structure.entry_id = entry.entry_id\n print(\"Total # of entries found in this chemistry: \", len(self.entries))\n\n @property\n def target_entry(self):\n if self.custom_target_entry:\n return self.custom_target_entry\n else:\n return [e for e in self.entries if e.entry_id == self.target_entry_id][0]\n\n def get_precursor_library(self):\n phased = PhaseDiagram(self.entries)\n if self.confine_to_stables:\n precursor_library = list(phased.stable_entries)\n elif self.hull_distance < np.inf:\n precursor_library = [\n e\n for e in self.entries\n if phased.get_e_above_hull(e) <= self.hull_distance\n ]\n else:\n precursor_library = [e for e in self.entries]\n if self.confine_to_icsd:\n precursor_library = [i for i in precursor_library if i.data[\"icsd_ids\"]]\n\n if self.simple_precursors:\n precursor_library = [\n i\n for i in precursor_library\n if len(i.composition.elements)\n < len(self.target_entry.composition.elements)\n - self.simple_precursors\n + 1\n ]\n\n if self.target_entry in precursor_library:\n precursor_library.pop(precursor_library.index(self.target_entry))\n\n if self.explicit_includes:\n print(\"explicitly including: \", self.explicit_includes)\n for entry_id in self.explicit_includes:\n try:\n entry = [e for e in self.entries if e.entry_id == entry_id][0]\n except IndexError:\n print(\"Could not find {} in entry list\".format(entry_id))\n continue\n if entry not in precursor_library:\n precursor_library.append(entry)\n\n if self.exclude_compositions:\n precursor_library = [\n i\n for i in precursor_library\n if i.composition.reduced_formula not in self.exclude_compositions\n ]\n\n self.precursor_library = precursor_library\n\n print(\n \"Total # of precusors materials obeying the provided filters: \",\n len(precursor_library),\n )\n return self.precursor_library\n\n def get_similarities(self):\n if self.use_cache:\n _similarities = through_cache(\n [s.structure for s in self.precursor_library],\n self.target_entry.structure,\n type=\"similarity\",\n )\n else:\n _similarities = similarity(\n [s.structure for s in self.precursor_library],\n self.target_entry.structure,\n )\n self.similarities = dict(\n zip([i.entry_id for i in self.precursor_library], _similarities)\n )\n print(\"Similarity matrix ready\")\n return self.similarities\n\n def get_epitaxies(self):\n if self.use_cache:\n _epitaxies = through_cache(\n [s.structure for s in self.precursor_library],\n self.target_entry.structure,\n type=\"epitaxy\",\n )\n else:\n _epitaxies = epitaxy(\n [s.structure for s in self.precursor_library],\n self.target_entry.structure,\n )\n self.epitaxies = dict(\n zip([i.entry_id for i in self.precursor_library], _epitaxies)\n )\n print(\"Epitaxies ready\")\n return self.epitaxies\n\n def get_reactions(self):\n\n target_c = get_v(\n self.target_entry.structure.composition.fractional_composition, self.elts\n )\n\n for precursors in tqdm(\n itertools.combinations(self.precursor_library, len(self.elts)),\n total=comb(len(self.precursor_library), len(self.elts)),\n ):\n\n precursors = list(precursors)\n\n c = [\n get_v(e.structure.composition.fractional_composition, self.elts)\n for e in precursors\n ]\n if np.any(np.sum(np.array(c), axis=0) == 0.0):\n continue\n\n try:\n coeffs = np.linalg.solve(np.vstack(c).T, target_c)\n effective_rank = scipy.linalg.lstsq(np.vstack(c).T, target_c)[2]\n except:\n # need better handling here.\n continue\n\n if np.any(np.abs(coeffs) > 100):\n continue\n\n precursor_formulas = np.array(\n [p.structure.composition.reduced_formula for p in precursors]\n )\n if len(set(precursor_formulas)) != len(precursor_formulas):\n continue\n\n if np.any(coeffs < 0.0):\n if not self.allow_gas_release:\n continue\n else:\n if not set(precursor_formulas[coeffs < 0.0]).issubset(GAS_RELEASE):\n continue\n\n for i in sorted(range(len(coeffs)), reverse=True):\n if np.abs(coeffs[i]) < 0.00001:\n precursors.pop(i)\n coeffs = np.delete(coeffs, i)\n # Update effective rank\n c_new = [\n get_v(e.structure.composition.fractional_composition, self.elts)\n for e in precursors\n ]\n effective_rank = scipy.linalg.lstsq(np.vstack(c_new).T, target_c)[2]\n if effective_rank < len(coeffs):\n # Removes under-determined reactions.\n # print(effective_rank, precursor_formulas, \\\n # [prec_.composition.reduced_formula for prec_ in precursors],coeffs)\n continue\n\n label = \"_\".join(sorted([e.entry_id for e in precursors]))\n if label in self.reactions:\n continue\n else:\n self.reactions[label] = {\n \"precursors\": deepcopy(precursors),\n \"coeffs\": coeffs,\n \"precursor_formulas\": np.array(\n [p.structure.composition.reduced_formula for p in precursors]\n ),\n \"precursor_ids\": [p.entry_id for p in precursors],\n }\n print(\"Total # of balanced reactions obtained: \", len(self.reactions))\n return self.reactions\n\n def get_reaction_energy(self, rxn_label, verbose=False):\n precursors = update_gases(\n self.reactions[rxn_label][\"precursors\"],\n T=self.temperature,\n P=self.pressure,\n copy=True,\n )\n # Free energy per atom\n energies = np.array([e.data[\"formation_energy_per_atom\"] for e in precursors])\n self.reactions[rxn_label][\"energy\"] = self.target_entry.data[\n \"formation_energy_per_atom\"\n ] - np.sum(self.reactions[rxn_label][\"coeffs\"] * energies)\n # Enthalpy energy per atom\n enthalpies = np.array(\n [\n e.data[\"enthalpy\"]\n if \"enthalpy\" in e.data\n else e.data[\"formation_energy_per_atom\"]\n for e in precursors\n ]\n )\n self.reactions[rxn_label][\"enthalpy\"] = self.target_entry.data[\n \"formation_energy_per_atom\"\n ] - np.sum(self.reactions[rxn_label][\"coeffs\"] * enthalpies)\n\n self.reactions[rxn_label][\"temperature\"] = self.temperature\n\n if verbose:\n print(\"target e: \", self.target_entry.data[\"formation_energy_per_atom\"])\n print(\"precursr: \", [e.composition.reduced_formula for e in precursors])\n print(\"energies: \", energies)\n print(\"coeffs: \", self.reactions[rxn_label][\"coeffs\"])\n\n return self.reactions[rxn_label][\"energy\"]\n\n @staticmethod\n def f(q):\n S = 1.0 - 2 * q\n if S < -1:\n S = -1\n elif S > 1:\n S = 1\n return (2 - 3 * S + S ** 3) / 4\n\n @property\n def sigma(self):\n return self._sigma\n\n @property\n def transport_constant(self):\n return self._transport_constant\n\n def get_nucleation_barrier(self, rxn_label):\n rx_e = self.reactions[rxn_label][\"energy\"]\n if rx_e > 0.0:\n self.reactions[rxn_label][\"barrier\"] = np.inf\n self.reactions[rxn_label][\"_params\"] = None\n return self.reactions[rxn_label][\"barrier\"]\n\n target_s = self.target_entry.structure\n delta_Gv = rx_e * target_s.num_sites / target_s.volume\n\n precursors = self.reactions[rxn_label][\"precursors\"]\n # precursor_formulas = self.reactions[rxn_label][\"precursor_formulas\"]\n\n q_epi = (\n min(\n [\n self.epitaxies[i.entry_id]\n for i in precursors\n if i.structure.composition.reduced_formula not in GASES\n ]\n )\n / 1000.0\n )\n q_epi = min(q_epi, 1.0)\n\n try:\n q_sim = min(\n [\n self.similarities[i.entry_id]\n for i in precursors\n if int(self.similarities[i.entry_id]) != -1\n and i.structure.composition.reduced_formula not in GASES\n ]\n )\n except:\n # better handling needed\n q_sim = 1.0\n\n f_t = self.f((q_epi + q_sim) / 2.0)\n G_star = 16 / 3 * np.pi * self.sigma ** 3 * f_t / delta_Gv ** 2\n E_d = self.transport_constant * q_sim\n\n self.reactions[rxn_label][\"barrier\"] = G_star + E_d\n self.reactions[rxn_label][\"_params\"] = {\n \"f_t\": f_t,\n \"G_star\": G_star,\n \"E_d\": E_d,\n \"q_sim\": q_sim,\n \"q_epi\": q_epi,\n }\n\n return self.reactions[rxn_label][\"barrier\"]\n\n def get_rxn_summary(self, rxn_label):\n coeffs = self.reactions[rxn_label][\"coeffs\"]\n num_sites = sum(\n self.target_entry.structure.composition.reduced_composition.as_dict().values()\n )\n _coeffs = []\n for i in range(len(coeffs)):\n p = self.reactions[rxn_label][\"precursors\"][i]\n _coeffs.append(\n coeffs[i]\n / sum(p.structure.composition.reduced_composition.as_dict().values())\n * num_sites\n )\n _coeffs = np.round(_coeffs, decimals=4)\n report = \" + \".join(\n [\n i + \" \" + j\n for i, j in list(\n zip(\n [str(c) for c in _coeffs],\n [\n p.structure.composition.reduced_formula\n + \"(\"\n + p.entry_id\n + \")\"\n for p in self.reactions[rxn_label][\"precursors\"]\n ],\n )\n )\n ]\n )\n self.reactions[rxn_label][\"summary\"] = report\n return report\n\n def get_competing_phases(self, rxn_label, confine_to_icsd=True):\n\n precursors = self.reactions[rxn_label][\"precursors\"]\n precursor_ids = [i.entry_id for i in precursors]\n _competing = []\n _competing_rxe = []\n\n for entry in self.entries:\n if confine_to_icsd:\n if not entry.data[\"icsd_ids\"]:\n continue\n if self.flexible_competition:\n s1 = set(entry.composition.as_dict().keys())\n s2 = set(self.target_entry.structure.composition.as_dict().keys())\n if not (\n s1.issubset(s2)\n and (len(s2) - self.flexible_competition <= len(s1) <= len(s2))\n ):\n continue\n else:\n if not set(self.target_entry.composition.as_dict().keys()).issubset(\n set(entry.structure.composition.as_dict().keys())\n ):\n continue\n if entry.entry_id in precursor_ids:\n continue\n if entry.entry_id == self.target_entry_id:\n continue\n competing_target_entry = entry\n\n elts_precs = set()\n for s in [\n set(p.structure.composition.as_dict().keys()) for p in precursors\n ]:\n elts_precs = elts_precs.union(s)\n if not set(entry.composition.as_dict().keys()).issubset(elts_precs):\n # print(entry.composition)\n continue\n\n elts_precs = sorted(list(elts_precs))\n\n target_c = get_v(\n competing_target_entry.structure.composition.fractional_composition,\n elts_precs,\n )\n c = [\n get_v(e.structure.composition.fractional_composition, elts_precs)\n for e in precursors\n ]\n\n precursor_formulas = np.array(\n [p.structure.composition.reduced_formula for p in precursors]\n )\n\n # trying to solve for compound fractions.\n try:\n coeffs = np.linalg.solve(np.vstack(c).T, target_c)\n except:\n try:\n x = scipy.sparse.linalg.lsqr(np.vstack(c).T, target_c)\n coeffs = x[0]\n if x[1] != 1:\n continue\n except:\n print(\n \" failed:\",\n competing_target_entry.composition.reduced_formula,\n precursor_formulas,\n )\n print(np.vstack(c).T, target_c)\n continue\n if np.any(coeffs < 0.0):\n if not self.allow_gas_release:\n continue\n else:\n if not set(precursor_formulas[coeffs < 0.0]).issubset(GAS_RELEASE):\n continue\n _precursors = update_gases(\n precursors, T=self.temperature, P=self.pressure, copy=True\n )\n\n for i in sorted(range(len(coeffs)), reverse=True):\n if np.abs(coeffs[i]) < 0.00001:\n _precursors.pop(i)\n coeffs = np.delete(coeffs, i)\n\n try:\n effective_rank = scipy.linalg.lstsq(np.vstack(c).T, target_c)[2]\n if effective_rank < len(coeffs):\n # print(precursor_formulas, coeffs)\n # Removes under-determined reactions.\n continue\n except:\n continue\n energies = np.array(\n [e.data[\"formation_energy_per_atom\"] for e in _precursors]\n )\n rx_e = competing_target_entry.data[\"formation_energy_per_atom\"] - np.sum(\n coeffs * energies\n )\n if rx_e < 0.0:\n _competing.append(competing_target_entry.entry_id)\n _competing_rxe.append((rx_e))\n self.reactions[rxn_label][\"competing\"] = _competing\n self.reactions[rxn_label][\"competing_rxe\"] = _competing_rxe\n self.reactions[rxn_label][\"n_competing\"] = len(_competing)\n return len(_competing)\n\n def recommend_routes(\n self,\n temperature=298,\n pressure=None,\n allow_gas_release=False,\n max_component_precursors=0,\n show_fraction_known_precursors=True,\n show_known_precursors_only=False,\n confine_competing_to_icsd=True,\n display_peroxides=True,\n display_superoxides=True,\n w=None,\n h=None,\n xrange=None,\n yrange=None,\n add_pareto=False,\n custom_text=\"\",\n ):\n if not pressure:\n pressure = self.pressure\n if not (\n self.temperature == temperature\n and self.pressure == pressure\n and self.allow_gas_release == allow_gas_release\n and self.confine_competing_to_icsd == confine_competing_to_icsd\n and self.reactions\n ):\n self.temperature = temperature\n self.pressure = pressure if pressure else self.pressure\n self.allow_gas_release = allow_gas_release\n self.confine_competing_to_icsd = confine_competing_to_icsd\n self.get_reactions()\n for rxn_label in self.reactions:\n self.get_reaction_energy(rxn_label)\n self.get_nucleation_barrier(rxn_label)\n self.get_rxn_summary(rxn_label)\n self.get_competing_phases(\n rxn_label, confine_to_icsd=confine_competing_to_icsd\n )\n self.check_if_known_precursors()\n\n self.plot_data = pd.DataFrame.from_dict(self.reactions, orient=\"index\")[\n [\n \"n_competing\",\n \"barrier\",\n \"summary\",\n \"energy\",\n \"enthalpy\",\n \"exp_precursors\",\n \"precursor_formulas\",\n ]\n ]\n if max_component_precursors:\n allowed_precursor_ids = [\n i.entry_id\n for i in self.precursor_library\n if len(set(i.composition.as_dict().keys()).difference(self.add_element))\n <= max_component_precursors\n or i.composition.reduced_formula in GAS_RELEASE\n ]\n display_reactions = []\n for r in self.plot_data.index.to_list():\n if set(r.split(\"_\")).issubset(set(allowed_precursor_ids)):\n display_reactions.append(r)\n self.plot_data = self.plot_data.loc[display_reactions]\n\n if not display_peroxides:\n peroxides = {\n \"Li2O2\",\n \"K2O2\",\n \"BaO2\",\n \"Rb2O2\",\n \"Cs2O2\",\n \"Na2O2\",\n \"SrO2\",\n \"CaO2\",\n \"MgO2\",\n \"ZnO2\",\n \"CdO2\",\n \"HgO2\",\n }\n allowed_rows = []\n for i in range(len(self.plot_data)):\n if not peroxides.intersection(\n set(self.plot_data[\"precursor_formulas\"][i].tolist())\n ):\n allowed_rows.append((i))\n self.plot_data = self.plot_data.iloc[allowed_rows]\n\n if not display_superoxides:\n superoxides = {\"LiO2\", \"NaO2\", \"KO2\", \"RbO2\", \"CsO2\"}\n allowed_rows = []\n for i in range(len(self.plot_data)):\n if not superoxides.intersection(\n set(self.plot_data[\"precursor_formulas\"][i].tolist())\n ):\n allowed_rows.append((i))\n self.plot_data = self.plot_data.iloc[allowed_rows]\n\n color = \"exp_precursors\" if show_fraction_known_precursors else None\n\n if show_known_precursors_only:\n self.plot_data = self.plot_data[\n self.plot_data[\"exp_precursors\"].astype(float) == 1.0\n ]\n fig = px.scatter(\n self.plot_data,\n x=\"n_competing\",\n y=\"barrier\",\n hover_data=[\"summary\"],\n color=color,\n width=w,\n height=h,\n template=\"simple_white\",\n )\n for i in fig.data:\n i.marker.size = 10\n fig.update_layout(\n yaxis={\n \"title\": \"Nucleation barrier (a.u.)\",\n \"ticks\": \"inside\",\n \"mirror\": True,\n \"showline\": True,\n },\n xaxis={\n \"title\": \"Number of competing phases\",\n \"ticks\": \"inside\",\n \"mirror\": True,\n \"showline\": True,\n },\n font={\"size\": 13},\n title=r\"Target: \"\n + self.target_entry.structure.composition.reduced_formula\n + custom_text,\n title_font_size=15,\n title_x=0.5,\n )\n fig.update_traces(\n marker=dict(\n size=12, line=dict(width=2, color=\"DarkSlateGrey\"), opacity=0.8\n ),\n selector=dict(mode=\"markers\"),\n )\n if xrange:\n fig.update_xaxes(range=xrange)\n if yrange:\n fig.update_yaxes(range=yrange)\n\n if add_pareto:\n import plotly.graph_objects as go\n\n _pareto_data = self.topsis().loc[self.get_pareto_front()]\n _x = _pareto_data[\"n_competing\"]\n _y = _pareto_data[\"barrier\"]\n fig.add_trace(\n go.Scatter(\n x=_x,\n y=_y,\n line=dict(color=\"firebrick\", width=2)\n # connectgaps=True\n )\n )\n fig.add_trace(\n go.Scatter(\n x=[_x[0], _x[0], None, _x[-1], self.topsis()[\"n_competing\"].max()],\n y=[_y[0], self.topsis()[\"barrier\"].max(), None, _y[-1], _y[-1]],\n line=dict(color=\"firebrick\", width=2, dash=\"dash\"),\n connectgaps=False,\n )\n )\n\n fig.update_layout(showlegend=False)\n return fig\n\n def get_precursor_formulas(self, include_ids=True):\n if include_ids:\n return [\n (p.entry_id, p.composition.reduced_formula)\n for p in self.precursor_library\n ]\n else:\n return [p.composition.reduced_formula for p in self.precursor_library]\n\n def get_rxn_containing(self, formulas):\n \"\"\"\n Find reactions that contain all formulas given.\n Args:\n formulas: list of formulas. string okay if one formula.\n Returns:\n reaction details\n \"\"\"\n if isinstance(formulas, str):\n formulas = list(formulas)\n return sorted(\n [\n (\n self.reactions[i][\"barrier\"],\n self.reactions[i][\"summary\"],\n self.reactions[i][\"n_competing\"],\n i,\n )\n for i in self.reactions\n if all(\n [formula in self.reactions[i][\"summary\"] for formula in formulas]\n )\n ]\n )\n\n def check_if_known_precursors(self):\n with open(\n os.path.join(RXN_FILES, \"experimental_precursors_KononovaSciData.json\"), \"r\"\n ) as f:\n exp_precursors = set(json.load(f))\n exp_precursors = exp_precursors.union(set(self.explicit_includes))\n\n for i in self.reactions:\n ids = [\n self.reactions[i][\"precursor_ids\"][j]\n for j in range(len(self.reactions[i][\"precursor_ids\"]))\n if self.reactions[i][\"precursor_formulas\"][j] not in GASES\n ]\n frac = len(set(ids).intersection(exp_precursors)) / len(ids)\n self.reactions[i][\"exp_precursors\"] = str(np.round(frac, decimals=4))\n\n def get_pareto_front(self):\n \"\"\"\n Returns: list of reaction labels on the pareto front\n \"\"\"\n x = self.plot_data[self.plot_data[\"barrier\"] < np.inf].sort_values(\n by=[\"n_competing\", \"barrier\"]\n )[[\"n_competing\", \"barrier\"]]\n y = x.groupby(by=[\"n_competing\"], as_index=False).min()\n rows = list(y.iterrows())\n front = []\n barrier_front = []\n for row in rows:\n n_competing = row[1][\"n_competing\"]\n barrier = row[1][\"barrier\"]\n if rows.index(row) == 0:\n front.append(\n x.index[\n (x[\"barrier\"] == barrier) & (x[\"n_competing\"] == n_competing)\n ][0]\n )\n barrier_front.append(barrier)\n continue\n if barrier < barrier_front[-1]:\n front.append(\n x.index[\n (x[\"barrier\"] == barrier) & (x[\"n_competing\"] == n_competing)\n ][0]\n )\n barrier_front.append(barrier)\n return front\n\n def topsis(self, latex=False):\n \"\"\"\n Returns a ranked list of reactions based on TOPSIS method for multiobjective optimization.\n Returns:\n \"\"\"\n x = self.plot_data[[\"n_competing\", \"barrier\"]]\n x = x[x[\"barrier\"] < np.inf]\n xsum = np.sqrt((x ** 2).sum())\n mu = x / xsum\n positive_ideal = mu.min()\n negative_ideal = mu.max()\n d_pos_ideal = np.sqrt(((mu - positive_ideal) ** 2).sum(axis=1))\n d_neg_ideal = np.sqrt(((mu - negative_ideal) ** 2).sum(axis=1))\n x[\"topsis_score\"] = d_neg_ideal / (d_pos_ideal + d_neg_ideal)\n x = x.sort_values(by=\"topsis_score\", ascending=False)\n result = self.plot_data.loc[x.index]\n result[\"topsis_score\"] = x[\"topsis_score\"]\n\n if latex:\n result[\"summary\"] = result[\"summary\"].apply(latexify)\n return result\n" ]
[ [ "numpy.abs", "numpy.round", "numpy.delete", "numpy.any", "pandas.DataFrame.from_dict", "numpy.array", "numpy.sum", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
vfonov/DARQ
[ "4845e416a3939b4e86e1441a4a44f4fea337caf5" ]
[ "python-tf/sample_counter.py" ]
[ "import tensorflow as tf\nimport sys\ntf.logging.set_verbosity('WARN')\ntf.compat.v1.enable_eager_execution()\n\nfiles=sys.argv\n\nfor f in sys.argv[1:]:\n print(f, sum(1 for i in tf.data.TFRecordDataset(f)))\n" ]
[ [ "tensorflow.data.TFRecordDataset", "tensorflow.compat.v1.enable_eager_execution", "tensorflow.logging.set_verbosity" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
dvntaka/hawaii_coronavirus_bot
[ "091d8f4a1f9a75250973234f0ad82807bbf2e2ae" ]
[ "src/first_bot_email.py" ]
[ "# Created follow a tutorial at: https://towardsdatascience.com/how-to-track-coronavirus-with-python-a5320b778c8e\n\nfrom datetime import date\nfrom urllib.request import Request, urlopen\nimport pandas as pd\nimport smtplib\n\n\ndef get_data():\n #req = Request('https://www.worldometers.info/coronavirus/#countries', headers={'User-Agent': 'Mozilla/5.0'})\n req = Request('https://www.worldometers.info/coronavirus/country/us/', headers={'User-Agent': 'Mozilla/5.0'})\n webpage = urlopen(req).read()\n\n df = pd.read_html(webpage)[0]\n\n\n # class Coronavirus():\n # def _init_(self):\n # self.driver = webdriver.Chrome()\n #\n # def get_data(self):\n # self.driver.get('https://www.worldometers.info/coronavirus/country/us/')\n\n #df = pd.read_html('https://www.worldometers.info/coronavirus/#countries')[0]\n\n hi = df.loc[df['USAState'].isin(['Hawaii'])] #df.loc[df['TotalCases'] == 'USA']# df[['TotalCases'] == 'USA']\n hi = hi.fillna(0)\n\n total_cases = int(hi.iloc[0]['TotalCases'])\n new_cases = int(hi.iloc[0]['NewCases'])\n total_deaths = int(hi.iloc[0]['TotalDeaths'])\n new_deaths = int(hi.iloc[0]['NewDeaths'])\n\n\n # categories = []\n # categories.append(total_cases)\n # categories.append(new_cases)\n # categories.append(total_deaths)\n # categories.append(new_deaths)\n #\n # for x in categories:\n # if math.isnan(x):\n # print('hi')\n # x = '0'\n # print(categories)\n\n print(new_cases)\n # /html/body/div[4]/div[1]/div/div[5]/div[1]/div/table#usa_table_countries_today\n # document.querySelector(\"#main_table_countries_today\")\n # #main_table_countries_today\n # /html/body/div[3]/div[3]/div/div[3]/div[1]/div/table\n send_mail(total_cases,new_cases,total_deaths, new_deaths)\n\n\ndef send_mail(total_cases, new_cases, total_deaths, new_deaths):\n\n body = 'Total cases: ' + str(total_cases) + '\\\n \\nNew cases: ' + str(new_cases) + '\\\n \\nTotal deaths: ' + str(total_deaths) + '\\\n \\nNew deaths: ' + str(new_deaths) + '\\\n \\nCheck the link: https://www.worldometers.info/coronavirus/country/us'\n\n\n FROM = '[email protected]'\n TO = '[email protected]'\n SUBJECT = 'HI Coronavirus Stats for ' + str(date.today())\n TEXT = body\n\n message = \"\"\"From: %s\\nTo: %s\\nSubject: %s\\n\\n%s\n \"\"\" % (FROM, TO, SUBJECT, TEXT)\n\n\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n server.login('[email protected]', 'aT@8J8f!')\n\n\n server.sendmail(\n FROM,\n TO,\n message\n )\n print('Hey Email has been sent!')\n server.close()\n\nif __name__==\"__main__\":\n get_data()\n #schedule.every().day.at(\"13:46\").do(get_data)\n #schedule.every(10).seconds.do(get_data)\n\n # while True:\n # schedule.run_pending()\n # time.sleep(60)" ]
[ [ "pandas.read_html" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
animeshtrivedi/surf-ml
[ "73102c69f303d5b289841e6116a607561e36595c", "73102c69f303d5b289841e6116a607561e36595c", "73102c69f303d5b289841e6116a607561e36595c", "73102c69f303d5b289841e6116a607561e36595c" ]
[ "benchmark/cifar10/cifar10_gpipe.py", "benchmark/cifar10/cifar10_pytorch.py", "pipedream-fork/runtime/communication.py", "benchmark/imagenet/gpipemodels/resnet/resnet.py" ]
[ "'''\nCifar10 example in pytorch\n'''\n\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport os\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\n\nfrom torchgpipe import GPipe\nfrom torchgpipe.balance import balance_by_time\n\nfrom typing import cast\nimport time\nfrom collections import OrderedDict\n\nfrom gpipemodels.resnet import *\nfrom gpipemodels.vgg import *\nfrom gpipemodels.mobilenetv2 import *\n\nmodel_names = {\n 'resnet18' : cifar10_resnet18(),\n 'resnet50' : cifar10_resnet50(),\n 'resnet152' : cifar10_resnet152(),\n 'vgg11' : cifar10_vgg11(),\n 'vgg16' : cifar10_vgg16(),\n 'mobilenetv2': cifar10_mobilenetv2(),\n}\n\ndatadir = os.environ['DATADIR']\nepochs = int(os.environ['EPOCHS'])\nmicrobatch_size = int(os.environ['BATCH_SIZE'])\nlog_inter = 1\ncores_gpu = int(os.environ['CORES_GPU'])\nmicrobatches = int(os.environ['MICROBATCHES'])\nbatch_size = microbatch_size * microbatches\n\ndef evaluate(test_loader, in_device, out_device, model):\n tick = time.time()\n steps = len(test_loader)\n data_tested = 0\n loss_sum = torch.zeros(1, device=out_device)\n accuracy_sum = torch.zeros(1, device=out_device)\n model.eval()\n\n with torch.no_grad():\n for i, (input, target) in enumerate(test_loader):\n current_batch = input.size(0)\n data_tested += current_batch\n input = input.to(device=in_device)\n target = target.to(device=out_device)\n\n output = model(input)\n\n loss = F.cross_entropy(output, target)\n loss_sum += loss * current_batch\n\n _, predicted = torch.max(output, 1)\n correct = (predicted == target).sum()\n accuracy_sum += correct\n\n if i % log_inter == 0:\n percent = i / steps * 100\n throughput = data_tested / (time.time() - tick)\n print('valid | %d%% | %.3f samples/sec (estimated)'\n '' % (percent, throughput))\n\n loss = loss_sum / data_tested\n accuracy = accuracy_sum / data_tested\n\n return loss.item(), accuracy.item()\n\n\ndef run_epoch(args, model, in_device, out_device, train_loader, test_loader, epoch, optimizer):\n torch.cuda.synchronize(in_device)\n tick = time.time()\n\n steps = len(train_loader)\n data_trained = 0\n loss_sum = torch.zeros(1, device=out_device)\n model.train()\n for i, (input, target) in enumerate(train_loader):\n data_trained += batch_size\n input = input.to(device=in_device, non_blocking=True)\n target = target.to(device=out_device, non_blocking=True)\n\n output = model(input)\n loss = F.cross_entropy(output, target)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n loss_sum += loss.detach() * batch_size\n\n if i % log_inter == 0:\n percent = i / steps * 100\n throughput = data_trained / (time.time()-tick)\n \n dev = torch.cuda.current_device()\n stats = torch.cuda.memory_stats(device=dev)\n max_mem = torch.cuda.get_device_properties(dev).total_memory\n print('train | %d/%d epoch (%d%%) | %.3f samples/sec (estimated) | mem (GB): %.3f (%.3f) / %.3f'\n '' % (epoch+1, epochs, percent, throughput, \n stats[\"allocated_bytes.all.peak\"] / 10**9,\n stats[\"reserved_bytes.all.peak\"] / 10**9,\n float(max_mem) / 10**9))\n\n torch.cuda.synchronize(in_device)\n tock = time.time()\n\n train_loss = loss_sum.item() / data_trained\n valid_loss, valid_accuracy = evaluate(test_loader, in_device, out_device, model)\n torch.cuda.synchronize(in_device)\n\n elapsed_time = tock - tick\n throughput = data_trained / elapsed_time\n print('%d/%d epoch | train loss:%.3f %.3f samples/sec | '\n 'valid loss:%.3f accuracy:%.3f'\n '' % (epoch+1, epochs, train_loss, throughput,\n valid_loss, valid_accuracy))\n\n return throughput, elapsed_time\n\n\nif __name__ == '__main__':\n # Training settings\n parser = argparse.ArgumentParser(description='D-DNN cifar10 benchmark')\n parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet50',\n choices=model_names,\n help='model architecture: ' +\n ' | '.join(model_names) +\n ' (default: resnet50)')\n parser.add_argument('--lr', type=float, default=0.001, metavar='LR',\n help='learning rate (default: 0.001)')\n parser.add_argument('--momentum', type=float, default=0.9, metavar='M',\n help='SGD momentum (default: 0.9)')\n # Value of args.synthetic_data may seem confusing, but those values \n # come from bash and there 0=true and all else =false\n parser.add_argument('-s', '--synthetic_data', type=int, default=0,\n help=\"Use synthetic data\")\n args = parser.parse_args()\n\n device = torch.device(\"cuda\")\n dataloader_kwargs = {'pin_memory': True}\n\n torch.manual_seed(1)\n torch.cuda.manual_seed(1)\n\n if args.synthetic_data:\n # Load normal data\n train_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10(datadir, train=True, download=False, \n transform=transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])),\n batch_size=batch_size, shuffle=True, num_workers=cores_gpu,\n **dataloader_kwargs)\n\n test_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10(datadir, train=False, download=False, \n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])),\n batch_size=batch_size, shuffle=True, num_workers=cores_gpu,\n **dataloader_kwargs)\n else:\n # Load synthetic data\n traindir = datadir + '/CIFAR10/train'\n valdir = datadir + '/CIFAR10/val'\n\n train_loader = torch.utils.data.DataLoader(\n datasets.ImageFolder(\n traindir,\n transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ]),\n ),\n batch_size=batch_size, shuffle=True,\n num_workers=cores_gpu, pin_memory=True)\n\n test_loader = torch.utils.data.DataLoader(\n datasets.ImageFolder(\n valdir, \n transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ]),\n ),\n batch_size=batch_size, shuffle=True,\n num_workers=cores_gpu, pin_memory=True)\n\n #---------------------------------------------------------------------------------\n # Move model to GPU.\n print(\"=> creating model '{}'\".format(args.arch))\n model = model_names[args.arch].cuda()\n\n partitions = torch.cuda.device_count()\n sample = torch.empty(batch_size, 3, 32, 32)\n balance = balance_by_time(partitions, model, sample)\n\n model = GPipe(model, balance, chunks=microbatches)\n \n #---------------------------------------------------------------------------------\n devices = list(model.devices)\n in_device = devices[0]\n out_device = devices[-1]\n torch.cuda.set_device(in_device)\n\n throughputs = []\n elapsed_times = []\n optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)\n for epoch in range(epochs):\n throughput, elapsed_time = run_epoch(args, model, in_device, out_device, train_loader, test_loader, epoch, optimizer)\n\n throughputs.append(throughput)\n elapsed_times.append(elapsed_time)\n\n _, valid_accuracy = evaluate(test_loader, in_device, out_device, model)\n\n n = len(throughputs)\n throughput = sum(throughputs) / n if n > 0 else 0.0\n elapsed_time = sum(elapsed_times) / n if n > 0 else 0.0\n print('valid accuracy: %.4f | %.3f samples/sec, %.3f sec/epoch (average)'\n '' % (valid_accuracy, throughput, elapsed_time))\n", "'''\nCifar10 example in pytorch\nhttps://github.com/pytorch/tutorials/blob/master/beginner_source/blitz/cifar10_tutorial.py\n'''\n\nfrom __future__ import print_function\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport os\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nimport time\nfrom pytorchcifargitmodels import *\n\nmodel_names = {\n 'resnet18' : cifar10_resnet18(),\n 'resnet34' : cifar10_resnet34(),\n 'resnet50' : cifar10_resnet50(),\n 'resnet101' : cifar10_resnet101(),\n 'resnet152' : cifar10_resnet152(),\n 'vgg11' : cifar10_vgg11(),\n 'vgg13' : cifar10_vgg13(),\n 'vgg16' : cifar10_vgg16(),\n 'vgg19' : cifar10_vgg19(),\n 'mobilenetv2': cifar10_mobilenetv2(),\n}\n\ndatadir = os.environ['DATADIR']\nepochs = int(os.environ['EPOCHS'])\nbatch_size = int(os.environ['BATCH_SIZE'])\nlog_inter = int(os.environ['LOGINTER'])\ncores_gpu = int(os.environ['CORES_GPU'])\n\ndef train(args, model, device, train_loader, test_loader):\n optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=0.9, weight_decay=5e-4)\n\n throughputs = []\n elapsed_times = []\n for epoch in range(0, epochs):\n throughput, elapsed_time = train_epoch(epoch, args, model, device, train_loader, optimizer, test_loader)\n\n throughputs.append(throughput)\n elapsed_times.append(elapsed_time)\n \n return throughputs, elapsed_times\n\n\ndef train_epoch(epoch, args, model, device, train_loader, optimizer, test_loader):\n #torch.cuda.synchronize(device)\n tick = time.time()\n steps = len(train_loader)\n data_trained = 0\n loss_sum = torch.zeros(1, device=device)\n model.train()\n\n for i, (data, target) in enumerate(train_loader):\n data_trained += batch_size\n\n output = model(data.to(device))\n loss = F.cross_entropy(output, target.to(device))\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n loss_sum += loss.detach() * batch_size\n\n if i % log_inter == 0:\n percent = i / steps * 100\n throughput = data_trained / (time.time()-tick)\n \n dev = torch.cuda.current_device()\n# stats = torch.cuda.memory_stats(device=dev)\n# max_mem = torch.cuda.get_device_properties(dev).total_memory\n# print('train | %d/%d epoch (%d%%) | %.3f samples/sec (estimated) | mem (GB): %.3f (%.3f) / %.3f'\n# '' % (epoch+1, epochs, percent, throughput, \n# stats[\"allocated_bytes.all.peak\"] / 10**9,\n# stats[\"reserved_bytes.all.peak\"] / 10**9,\n# float(max_mem) / 10**9))\n print(\"working...\")\n \n# torch.cuda.synchronize(device)\n tock = time.time()\n\n train_loss = loss_sum.item() / data_trained\n valid_loss, valid_accuracy = test_epoch(model, device, test_loader)\n# torch.cuda.synchronize(device)\n\n elapsed_time = tock - tick\n throughput = data_trained / elapsed_time\n print('%d/%d epoch | train loss:%.3f %.3f samples/sec | '\n 'valid loss:%.3f accuracy:%.3f'\n '' % (epoch+1, epochs, train_loss, throughput,\n valid_loss, valid_accuracy))\n\n return throughput, elapsed_time\n\n\ndef test_epoch(model, device, test_loader):\n tick = time.time()\n steps = len(test_loader)\n data_tested = 0\n loss_sum = torch.zeros(1, device=device)\n accuracy_sum = torch.zeros(1, device=device)\n model.eval()\n\n with torch.no_grad():\n for i, (data, target) in enumerate(test_loader):\n current_batch = data.size(0)\n data_tested += current_batch\n\n target = target.to(device)\n output = model(data.to(device))\n loss = F.cross_entropy(output, target)\n loss_sum += loss * current_batch\n\n _, predicted = torch.max(output, 1)\n correct = (predicted == target).sum()\n accuracy_sum += correct\n\n if i % log_inter == 0:\n percent = i / steps * 100\n throughput = data_tested / (time.time() - tick)\n print('valid | %d%% | %.3f samples/sec (estimated)'\n '' % (percent, throughput))\n\n loss = loss_sum / data_tested\n accuracy = accuracy_sum / data_tested\n\n return loss.item(), accuracy.item()\n\n\ndef main():\n # Training settings\n parser = argparse.ArgumentParser(description='D-DNN cifar10 benchmark')\n parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet50',\n choices=model_names,\n help='model architecture: ' +\n ' | '.join(model_names) +\n ' (default: resnet50)')\n parser.add_argument('--lr', type=float, default=0.1, metavar='LR',\n help='learning rate (default: 0.1)')\n # Value of args.synthetic_data may seem confusing, but those values \n # come from bash and there 0=true and all else =false\n parser.add_argument('-s', '--synthetic_data', type=int, default=0,\n help=\"Use synthetic data\")\n args = parser.parse_args()\n\n device = torch.device(\"cpu\")\n dataloader_kwargs = {'pin_memory': True}\n\n torch.manual_seed(1)\n torch.cuda.manual_seed(1)\n\n print(\"=> creating model '{}'\".format(args.arch))\n model = model_names[args.arch].to(device)\n\n if args.synthetic_data:\n # Load normal data\n train_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10(datadir, train=True, download=False, \n transform=transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])),\n batch_size=batch_size, shuffle=True, num_workers=cores_gpu,\n **dataloader_kwargs)\n\n test_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10(datadir, train=False, download=False, \n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])),\n batch_size=batch_size, shuffle=True, num_workers=cores_gpu,\n **dataloader_kwargs)\n else:\n # Load synthetic data\n traindir = datadir + '/CIFAR10/train'\n valdir = datadir + '/CIFAR10/val'\n\n train_loader = torch.utils.data.DataLoader(\n datasets.ImageFolder(\n traindir,\n transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ]),\n ),\n batch_size=batch_size, shuffle=True,\n num_workers=cores_gpu, pin_memory=True)\n\n test_loader = torch.utils.data.DataLoader(\n datasets.ImageFolder(\n valdir, \n transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ]),\n ),\n batch_size=batch_size, shuffle=True,\n num_workers=cores_gpu, pin_memory=True)\n\n # Run the model\n throughputs, elapsed_times = train(args, model, device, train_loader, test_loader)\n _, valid_accuracy = test_epoch(model, device, test_loader)\n\n n = len(throughputs)\n throughput = sum(throughputs) / n if n > 0 else 0.0\n elapsed_time = sum(elapsed_times) / n if n > 0 else 0.0\n print('valid accuracy: %.4f | %.3f samples/sec, %.3f sec/epoch (average)'\n '' % (valid_accuracy, throughput, elapsed_time))\n\n\nif __name__ == '__main__':\n main()\n", "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nimport os\nimport threading\nimport torch\nimport torch.distributed as dist\nimport sys\n\nimport threadsafe_counter\nimport threadsafe_queue\n\nfrom datetime import timedelta #added to source\n\nNCCL='nccl'\nGLOO='gloo'\n\n\nclass CommunicationHandler(object):\n \"\"\" Handles communication between stages.\n\n For stages on different machines, use send/recv.\n For stages on same machine, use broadcast.\n \"\"\"\n def __init__(self, master_addr, master_port, rank,\n local_rank, num_ranks_in_server,\n world_size, fp16, backend):\n \"\"\" Set up process groups.\n\n Note: To turn off broadcasting, set num_ranks_in_server = 1.\n \"\"\"\n self.rank = rank\n self.local_rank = local_rank\n self.backend = backend\n self.num_ranks_in_server = num_ranks_in_server\n self.world_size = world_size\n self.fp16 = fp16\n assert num_ranks_in_server > 0\n\n # Initialize the distributed environment.\n os.environ['MASTER_ADDR'] = master_addr\n os.environ['MASTER_PORT'] = str(master_port)\n dist.init_process_group(backend, rank=rank, world_size=world_size, timeout=timedelta(minutes=120)) # changed source, added longer timeout\n assert dist.get_world_size() == self.world_size\n print(\"Finished initializing process group; backend: %s, rank: %d, \"\n \"world_size: %d\" % (backend, rank, world_size))\n\n # Stores list of ranks of GPUs on the same server.\n self.ranks_in_server = []\n\n if num_ranks_in_server == 1:\n return\n\n # Stores information about tensors sent directly GPU-to-GPU.\n self.connection_list = []\n\n # Stores process groups (for broadcast() connections).\n self.process_groups = {}\n\n # Populate ranks_in_server.\n rank_of_first_gpu_in_server = rank - rank % num_ranks_in_server\n for connected_rank in range(\n rank_of_first_gpu_in_server,\n rank_of_first_gpu_in_server + num_ranks_in_server):\n if connected_rank == rank:\n continue\n self.ranks_in_server.append(connected_rank)\n assert len(self.ranks_in_server) == num_ranks_in_server - 1, \\\n self.ranks_in_server\n\n def is_gpu_to_gpu_comm(self, connected_rank):\n if connected_rank in self.ranks_in_server:\n return True\n return False\n\n def register_tensor(self, connected_rank, tag):\n \"\"\"\n Builds connections list of tensors that are communicated GPU to GPU.\n\n For tensors that are sent GPU-to-GPU (intra-server for GLOO backend),\n make a list of destination/source ranks and the corresponding tag.\n This information is then used to crate process groups.\n \"\"\"\n if not self.is_gpu_to_gpu_comm(connected_rank=connected_rank):\n return\n connection_info = [tag, connected_rank]\n self.connection_list.append(connection_info)\n\n def initialize(self, receive_ranks, send_ranks,\n tensor_tags, target_tensor_names,\n training_tensor_dtypes,\n rank_in_stage,\n num_ranks_in_stage,\n ranks_in_previous_stage,\n ranks_in_next_stage):\n \"\"\"\n Initialize state needed for CommunicationHandler.\n \"\"\"\n self.receive_ranks = receive_ranks\n self.send_ranks = send_ranks\n self.tensor_tags = tensor_tags\n self.target_tensor_names = target_tensor_names\n self.training_tensor_dtypes = training_tensor_dtypes\n self.rank_in_stage = rank_in_stage\n self.num_ranks_in_stage = num_ranks_in_stage\n self.ranks_in_previous_stage = ranks_in_previous_stage\n self.num_ranks_in_previous_stage = len(ranks_in_previous_stage)\n self.ranks_in_next_stage = ranks_in_next_stage\n self.num_ranks_in_next_stage = len(ranks_in_next_stage)\n\n self.setup_queues()\n self.setup_messaging_schedule()\n self.create_process_groups()\n\n def setup_queues(self):\n \"\"\"\n Setup queues for communication between main compute thread\n and helper communication threads. One queue per tensor\n in forward / backward direction.\n \"\"\"\n self.forward_receive_queues = {}\n self.backward_receive_queues = {}\n self.forward_send_queues = {}\n self.backward_send_queues = {}\n self.num_forward_threads = 0\n self.num_backward_threads = 0\n\n self.target_receive_rank_counts = {}\n self.target_send_rank_counts = {}\n # Setup queues for each tensor to be received and sent.\n for input_name in self.receive_ranks:\n self.forward_receive_queues[input_name] = []\n self.backward_send_queues[input_name] = []\n for i in range(len(self.receive_ranks[input_name])):\n self.forward_receive_queues[input_name].append(\n threadsafe_queue.Queue())\n self.backward_send_queues[input_name].append(\n threadsafe_queue.Queue())\n target_receive_rank = self.receive_ranks[input_name][i]\n self.register_tensor(\n connected_rank=target_receive_rank,\n tag=self.tensor_tags[input_name])\n if target_receive_rank not in self.target_receive_rank_counts:\n self.target_receive_rank_counts[target_receive_rank] = 0\n self.target_receive_rank_counts[target_receive_rank] += 1\n self.num_forward_threads += 1\n self.num_backward_threads += 1\n for output_name in self.send_ranks:\n self.backward_receive_queues[output_name] = []\n self.forward_send_queues[output_name] = []\n for i in range(len(self.send_ranks[output_name])):\n self.backward_receive_queues[output_name].append(\n threadsafe_queue.Queue())\n self.forward_send_queues[output_name].append(\n threadsafe_queue.Queue())\n target_send_rank = self.send_ranks[output_name][i]\n self.register_tensor(\n connected_rank=target_send_rank,\n tag=self.tensor_tags[output_name])\n if target_send_rank not in self.target_send_rank_counts:\n self.target_send_rank_counts[target_send_rank] = 0\n self.target_send_rank_counts[target_send_rank] += 1\n self.num_forward_threads += 1\n self.num_backward_threads += 1\n\n for target_tensor_name in self.target_tensor_names:\n # Queues for target in forward pass.\n self.forward_receive_queues[target_tensor_name] = []\n self.forward_send_queues[target_tensor_name] = []\n\n if self.num_ranks_in_previous_stage > 0:\n self.receive_ranks[target_tensor_name] = self.ranks_in_previous_stage\n for i in range(len(self.receive_ranks[target_tensor_name])):\n self.register_tensor(\n connected_rank=self.receive_ranks[target_tensor_name][i],\n tag=self.tensor_tags[target_tensor_name])\n self.forward_receive_queues[target_tensor_name].append(\n threadsafe_queue.Queue())\n self.num_forward_threads += 1\n\n if self.num_ranks_in_next_stage > 0:\n self.send_ranks[target_tensor_name] = self.ranks_in_next_stage\n for i in range(len(self.send_ranks[target_tensor_name])):\n self.register_tensor(\n connected_rank=self.send_ranks[target_tensor_name][i],\n tag=self.tensor_tags[target_tensor_name])\n self.forward_send_queues[target_tensor_name].append(\n threadsafe_queue.Queue())\n self.num_forward_threads += 1\n\n print (\"Send ranks: \", self.send_ranks)\n print (\"Receive ranks: \", self.receive_ranks)\n\n # Queues for ack for forward pass-only runs as a clocking mechanism.\n self.num_ack_threads = 0\n if \"ack\" in self.tensor_tags:\n self.backward_receive_queues[\"ack\"] = []\n self.backward_send_queues[\"ack\"] = []\n for i in range(self.num_ranks_in_previous_stage):\n self.register_tensor(\n connected_rank=self.ranks_in_previous_stage[i],\n tag=self.tensor_tags[\"ack\"])\n self.backward_send_queues[\"ack\"].append(\n threadsafe_queue.Queue())\n self.num_ack_threads += 1\n for i in range(self.num_ranks_in_next_stage):\n self.register_tensor(\n connected_rank=self.ranks_in_next_stage[i],\n tag=self.tensor_tags[\"ack\"])\n self.backward_receive_queues[\"ack\"].append(\n threadsafe_queue.Queue())\n self.num_ack_threads += 1\n\n def set_tensor_shapes(self, tensor_shapes):\n self.tensor_shapes = tensor_shapes\n\n def set_counter(self, counter):\n self.counter = threadsafe_counter.Counter(counter)\n\n def wait(self):\n self.counter.wait()\n\n def num_iterations_for_helper_threads(self, num_iterations):\n \"\"\" Scales the number of iterations a helper thread is run for.\n Since we start a helper thread for each worker in previous/next stage,\n the number of iterations for each thread should be scaled by\n the number of workers in previous/next stage.\n TODO: don't current support uneven configurations.\n \"\"\"\n forward_num_iterations = num_iterations\n backward_num_iterations = num_iterations\n\n if self.num_ranks_in_next_stage > 0:\n assert forward_num_iterations % self.num_ranks_in_next_stage == 0\n forward_num_iterations = forward_num_iterations // \\\n self.num_ranks_in_next_stage\n else:\n forward_num_iterations = 0\n\n if self.num_ranks_in_previous_stage > 0:\n assert backward_num_iterations % self.num_ranks_in_previous_stage == 0\n backward_num_iterations = backward_num_iterations // \\\n self.num_ranks_in_previous_stage\n else:\n backward_num_iterations = 0\n\n return forward_num_iterations, backward_num_iterations\n\n def start_helper_threads(self, num_iterations, forward_only):\n \"\"\"\n Start helper communication threads, one for each queue.\n \"\"\"\n if forward_only:\n self.set_counter(self.num_forward_threads +\n self.num_ack_threads)\n # For validation, receive acks in backward pass from next stage, send\n # acks in backward pass to next stage.\n self.receive_ranks[\"ack\"] = self.ranks_in_previous_stage\n self.send_ranks[\"ack\"] = self.ranks_in_next_stage\n else:\n self.set_counter(self.num_forward_threads +\n self.num_backward_threads)\n if \"ack\" in self.receive_ranks:\n del self.receive_ranks[\"ack\"]\n if \"ack\" in self.send_ranks:\n del self.send_ranks[\"ack\"]\n\n (num_iterations_for_forward_threads,\n num_iterations_for_backward_threads) = \\\n self.num_iterations_for_helper_threads(\n num_iterations=num_iterations)\n dtype = torch.float16 if self.fp16 else torch.float32\n\n # Setup queues for each tensor to be received and sent.\n for input_name in self.receive_ranks:\n if input_name in self.target_tensor_names or input_name == \"ack\":\n continue\n\n for i in range(len(self.receive_ranks[input_name])):\n if not forward_only:\n self.start_helper_thread(\n self.send_helper_thread_args,\n send_helper_thread,\n [input_name, i, True],\n num_iterations_for_backward_threads)\n self.start_helper_thread(\n self.recv_helper_thread_args,\n recv_helper_thread,\n [input_name,\n i,\n self.training_tensor_dtypes[input_name],\n False],\n num_iterations_for_backward_threads)\n for output_name in self.send_ranks:\n if output_name in self.target_tensor_names or output_name == \"ack\":\n continue\n\n for i in range(len(self.send_ranks[output_name])):\n if not forward_only:\n self.start_helper_thread(\n self.recv_helper_thread_args,\n recv_helper_thread,\n [output_name, i,\n self.training_tensor_dtypes[output_name],\n True],\n num_iterations_for_forward_threads)\n self.start_helper_thread(\n self.send_helper_thread_args,\n send_helper_thread,\n [output_name, i, False],\n num_iterations_for_forward_threads)\n\n for target_tensor_name in self.target_tensor_names:\n if self.num_ranks_in_previous_stage > 0:\n for i in range(len(self.receive_ranks[target_tensor_name])):\n self.start_helper_thread(\n self.recv_helper_thread_args,\n recv_helper_thread,\n [target_tensor_name, i, torch.int64,\n False],\n num_iterations_for_backward_threads)\n\n if self.num_ranks_in_next_stage > 0:\n for i in range(len(self.send_ranks[target_tensor_name])):\n self.start_helper_thread(\n self.send_helper_thread_args,\n send_helper_thread,\n [target_tensor_name, i, False],\n num_iterations_for_forward_threads)\n\n # Start helper threads for ack for forward pass-only run as a clocking\n # mechanism.\n if forward_only:\n if \"ack\" in self.receive_ranks:\n for i in range(len(self.receive_ranks[\"ack\"])):\n self.start_helper_thread(self.send_helper_thread_args,\n send_helper_thread,\n [\"ack\", i, True],\n num_iterations_for_backward_threads)\n if \"ack\" in self.send_ranks:\n for i in range(len(self.send_ranks[\"ack\"])):\n self.start_helper_thread(self.recv_helper_thread_args,\n recv_helper_thread,\n [\"ack\", i, torch.int64, True],\n num_iterations_for_forward_threads)\n\n def start_helper_thread(self, args_func, func, args_func_args, num_iterations):\n \"\"\"\n Start passed-in func on a helper thread.\n \"\"\"\n args_func_args += [num_iterations]\n args = args_func(*args_func_args)\n helper_thread = threading.Thread(target=func,\n args=args)\n helper_thread.start()\n\n def create_process_groups(self):\n \"\"\" Create process groups in the same order across all ranks.\n\n To create process groups in the same order, each worker collects\n the connection_list of all other workers. To do this, every worker\n gathers the largest size of all other worker's connection_lists (L).\n Then every worker creates a tensor of size Lx2, where each row\n represents a connection, and fills up this tensor depending on how\n large its own connection list is. The worker(s) w/ the largest\n connection list will fill up the entire tensor.\n\n After constructing this list, an all_gather is performed, after which\n each worker has an identical NxLx2 output, where N is the number of\n workers (world_size), and each index of output represents a worker's\n connection list. For i=self.rank, the output will be identical to the\n workers local connection list.\n\n Each worker then iterates in the same order over the connections list,\n checking if each connection has been created yet (every connection will\n appear twice in the output), and creating a new process group if one\n doesn't exist for that connection, for both the forward and backward\n direction. Since ranks within process groups must always be identical,\n the smaller rank always goes first, followed by the larger rank.\n \"\"\"\n if self.num_ranks_in_server == 1:\n return\n\n print(\"Setting up process groups for broadcasts...\")\n\n # Figure out the size of the largest connection list that any worker\n # has (L).\n connection_list_size = torch.tensor(\n len(self.connection_list), dtype=torch.int)\n if self.backend == NCCL:\n connection_list_size = connection_list_size.cuda()\n gathered_connection_list_sizes = [\n torch.ones_like(connection_list_size)\n for _ in range(self.world_size)]\n dist.all_gather(gathered_connection_list_sizes,\n connection_list_size)\n max_connection_list_size = max(\n gathered_connection_list_sizes)\n\n if max_connection_list_size == 0:\n return \n\n # Build tensor to send local connection list to all other workers.\n connection_list_tensor = torch.ones([max_connection_list_size, 2],\n dtype=torch.int) * -1\n if self.backend == NCCL:\n connection_list_tensor = connection_list_tensor.cuda()\n if len(self.connection_list) > 0:\n connection_list_tensor[0:len(self.connection_list)] = \\\n torch.IntTensor(self.connection_list)\n\n # Gather connection lists of all workers.\n aggregated_connection_list = [\n torch.ones_like(connection_list_tensor)\n for _ in range(self.world_size)]\n dist.all_gather(aggregated_connection_list,\n connection_list_tensor)\n\n # Construct identical process groups on each worker.\n local_rank_connections = 0\n for src_rank in range(len(aggregated_connection_list)):\n for connection in aggregated_connection_list[src_rank]:\n tag = int(connection[0])\n dst_rank = int(connection[1])\n\n if tag == -1:\n assert dst_rank == -1\n continue\n\n min_rank = min(src_rank, dst_rank)\n max_rank = max(src_rank, dst_rank)\n assert min_rank != max_rank\n\n if min_rank not in self.process_groups:\n self.process_groups[min_rank] = {}\n\n if max_rank not in self.process_groups[min_rank]:\n self.process_groups[min_rank][max_rank] = {}\n\n if tag not in self.process_groups[min_rank][max_rank]:\n sub_process_group_fwd = dist.new_group(\n ranks=[min_rank, max_rank])\n sub_process_group_bwd = dist.new_group(\n ranks=[min_rank, max_rank])\n\n self.process_groups[min_rank][max_rank][tag] = {\n 'forward': sub_process_group_fwd,\n 'backward': sub_process_group_bwd\n }\n\n if min_rank == self.rank or max_rank == self.rank:\n local_rank_connections += 1\n assert local_rank_connections == len(self.connection_list)\n\n def setup_messaging_schedule(self):\n \"\"\" Order in which to receive forward and send backwards.\n\n Separate indexes of ranks in previous stage based on their\n corresponding offset in this stage. Then each worker will go\n in increasing order within a subset, and process subsets in\n a decreasing order.\n\n This is done so that messages are processed in the order\n that they are sent. Backwards send is done so that that it\n matches up with forward receive.\n \"\"\"\n self.messaging_schedule = []\n for i in range(self.num_ranks_in_stage):\n idx = i\n message_schedule = []\n while idx < self.num_ranks_in_previous_stage:\n message_schedule.append(idx)\n idx += self.num_ranks_in_stage\n if len(message_schedule) > 0:\n self.messaging_schedule.append(message_schedule)\n\n self.fwd_messaging_scheduling_row = self.rank_in_stage\n self.fwd_messaging_scheduling_col = 0\n self.bwd_messaging_scheduling_row = self.rank_in_stage\n self.bwd_messaging_scheduling_col = 0\n\n # For cases where previous stage has less workers than current stage.\n # SOURCE EDIT: > to >= otherwise program deadlocks for configs described above\n while self.fwd_messaging_scheduling_row >= \\\n len(self.messaging_schedule):\n self.fwd_messaging_scheduling_row -= 1\n self.bwd_messaging_scheduling_row -= 1\n\n def get_messaging_index(self, sending):\n if sending:\n connection_rank = self.messaging_schedule[\n self.bwd_messaging_scheduling_row][\n self.bwd_messaging_scheduling_col]\n else:\n connection_rank = self.messaging_schedule[\n self.fwd_messaging_scheduling_row][\n self.fwd_messaging_scheduling_col]\n\n return connection_rank\n\n def increment_messaging_index(self, sending):\n if sending:\n self.bwd_messaging_scheduling_col += 1\n if self.bwd_messaging_scheduling_col == len(\n self.messaging_schedule[\n self.bwd_messaging_scheduling_row]):\n self.bwd_messaging_scheduling_col = 0\n self.bwd_messaging_scheduling_row -= 1\n if self.bwd_messaging_scheduling_row == -1:\n self.bwd_messaging_scheduling_row = \\\n len(self.messaging_schedule) - 1\n else:\n self.fwd_messaging_scheduling_col += 1\n if self.fwd_messaging_scheduling_col == len(\n self.messaging_schedule[\n self.fwd_messaging_scheduling_row]):\n self.fwd_messaging_scheduling_col = 0\n self.fwd_messaging_scheduling_row -= 1\n if self.fwd_messaging_scheduling_row == -1:\n self.fwd_messaging_scheduling_row = \\\n len(self.messaging_schedule) - 1\n\n def recv_helper_thread_args(self, tensor_name, index, dtype,\n backward, num_iterations):\n if backward:\n src_rank = self.send_ranks[tensor_name][index]\n else:\n src_rank = self.receive_ranks[tensor_name][index]\n\n sub_process_group = None\n tag = self.tensor_tags[tensor_name]\n if self.is_gpu_to_gpu_comm(connected_rank=src_rank) and tensor_name != \"ack\":\n min_rank = min(self.rank, src_rank)\n max_rank = max(self.rank, src_rank)\n if src_rank > self.rank:\n sub_process_group = \\\n self.process_groups[min_rank][max_rank][tag]['backward']\n else:\n sub_process_group = \\\n self.process_groups[min_rank][max_rank][tag]['forward']\n assert sub_process_group\n\n if backward:\n queue = self.backward_receive_queues[tensor_name][index]\n else:\n queue = self.forward_receive_queues[tensor_name][index]\n tensor_shape = self.tensor_shapes[tensor_name]\n\n return (queue, self.counter, self.local_rank, tensor_name,\n src_rank, tag, tensor_shape, dtype, sub_process_group,\n num_iterations)\n\n def send_helper_thread_args(self, tensor_name, index,\n backward, num_iterations):\n if backward:\n dst_rank = self.receive_ranks[tensor_name][index]\n num_ranks_in_connected_stage = self.num_ranks_in_previous_stage\n else:\n dst_rank = self.send_ranks[tensor_name][index]\n num_ranks_in_connected_stage = self.num_ranks_in_next_stage\n\n sub_process_group = None\n tag = self.tensor_tags[tensor_name]\n if self.is_gpu_to_gpu_comm(connected_rank=dst_rank) and tensor_name != \"ack\":\n min_rank = min(self.rank, dst_rank)\n max_rank = max(self.rank, dst_rank)\n if dst_rank > self.rank:\n sub_process_group = \\\n self.process_groups[min_rank][max_rank][tag]['forward']\n else:\n sub_process_group = \\\n self.process_groups[min_rank][max_rank][tag]['backward']\n assert sub_process_group\n\n if backward:\n queue = self.backward_send_queues[tensor_name][index]\n else:\n queue = self.forward_send_queues[tensor_name][index]\n\n return (queue, self.counter, self.local_rank, tensor_name, self.rank,\n dst_rank, tag, sub_process_group, num_iterations)\n\n def recv(self, tensor_name, forward_minibatch_id,\n backward_minibatch_id, backward=False):\n if backward:\n index = (backward_minibatch_id + self.rank_in_stage) % \\\n len(self.backward_receive_queues[tensor_name])\n tensor = self.backward_receive_queues[tensor_name][\n index].remove()\n return tensor\n else:\n index = self.get_messaging_index(sending=False)\n tensor = self.forward_receive_queues[tensor_name][\n index].remove()\n if tensor.dtype == torch.float32:\n tensor = tensor.requires_grad_()\n return tensor\n\n def send(self, tensor_name, tensor, forward_minibatch_id,\n backward_minibatch_id, backward=False):\n if backward:\n index = self.get_messaging_index(sending=True)\n dst_rank = self.receive_ranks[tensor_name][index]\n self.backward_send_queues[tensor_name][index].add(tensor)\n else:\n index = (forward_minibatch_id + self.rank_in_stage) % \\\n len(self.send_ranks[tensor_name])\n self.forward_send_queues[tensor_name][index].add(tensor)\n\ndef recv_helper_thread(queue, counter, local_rank, tensor_name,\n src_rank, tag, tensor_shape, dtype,\n sub_process_group, num_iterations):\n torch.cuda.set_device(local_rank)\n # This method is to be executed from a helper daemon thread.\n for i in range(num_iterations):\n tensor = _recv(\n tensor_name, src_rank, tensor_shape=tensor_shape,\n dtype=dtype, tag=tag,\n sub_process_group=sub_process_group)\n queue.add(tensor)\n counter.decrement()\n\ndef send_helper_thread(queue, counter, local_rank, tensor_name,\n src_rank, dst_rank, tag,\n sub_process_group, num_iterations):\n torch.cuda.set_device(local_rank)\n # This method is to be executed from a helper daemon thread.\n for i in range(num_iterations):\n tensor = queue.remove()\n _send(tensor, tensor_name, src_rank, dst_rank,\n tag=tag,\n sub_process_group=sub_process_group)\n counter.decrement()\n\ndef _recv(tensor_name, src_rank, tensor_shape=None, dtype=torch.float32,\n tensor=None, tag=None, sub_process_group=None):\n \"\"\"\n Receives tensor by calling PyTorch's recv() call.\n\n Tensor will be copied to GPU prior to return.\n \"\"\"\n assert tag is not None\n if tensor is None:\n assert tensor_shape is not None\n assert dtype is not None\n assert dtype != torch.float16\n\n if sub_process_group is not None:\n # Receive tensor shape.\n received_tensor_shape = torch.zeros(len(tensor_shape),\n dtype=torch.int)\n dist.broadcast(tensor=received_tensor_shape,\n src=src_rank,\n group=sub_process_group)\n received_tensor_shape = list(map(lambda x: int(x),\n received_tensor_shape))\n\n # Receive tensor.\n tensor = torch.zeros(received_tensor_shape, dtype=dtype).cuda()\n dist.broadcast(tensor=tensor,\n src=src_rank,\n group=sub_process_group)\n else:\n # Receive tensor shape.\n received_tensor_shape = torch.zeros(len(tensor_shape),\n dtype=torch.int)\n dist.recv(tensor=received_tensor_shape,\n src=src_rank,\n tag=tag)\n received_tensor_shape = list(map(lambda x: int(x),\n received_tensor_shape))\n\n # Receive tensor.\n tensor = torch.zeros(received_tensor_shape, dtype=dtype)\n dist.recv(tensor=tensor,\n src=src_rank,\n tag=tag)\n tensor = tensor.cuda()\n\n assert tensor.is_cuda\n return tensor\n\ndef _send(tensor, tensor_name, src_rank, dst_rank, tag, sub_process_group=None):\n \"\"\"\n Sends tensor by calling PyTorch's send() call.\n\n If tensor is being sent not via broadcast(), it will\n be first copied to the CPU.\n \"\"\"\n if sub_process_group is not None:\n assert tensor.is_cuda\n\n # Send tensor shape.\n tensor_shape = torch.tensor(tensor.shape, dtype=torch.int)\n dist.broadcast(tensor=tensor_shape, src=src_rank,\n group=sub_process_group)\n\n # Send tensor.\n contiguous_tensor = tensor.detach().clone()\n dist.broadcast(tensor=contiguous_tensor.contiguous(),\n src=src_rank,\n group=sub_process_group)\n else:\n assert tensor.is_cuda\n tensor = tensor.cpu()\n\n # Send tensor shape.\n tensor_shape = torch.tensor(tensor.shape, dtype=torch.int)\n dist.send(tensor=tensor_shape, dst=dst_rank, tag=tag)\n\n # Send tensor.\n dist.send(tensor=tensor, dst=dst_rank, tag=tag)\n", "\"\"\"A ResNet implementation but using :class:`nn.Sequential`. :func:`resnet101`\nreturns a :class:`nn.Sequential` instead of ``ResNet``.\n\nThis code is transformed :mod:`torchvision.models.resnet`.\n\n\"\"\"\nfrom collections import OrderedDict\nfrom typing import Any, List\n\nfrom torch import nn\n\nfrom .block import bottleneck, basicblock\nfrom .flatten_sequential import flatten_sequential\n\n__all__ = ['inet_resnet18', 'inet_resnet34', 'inet_resnet50', 'inet_resnet101', 'inet_resnet152']\n\ndef build_resnet(layers, block, num_classes=1000, inplace=False):\n \"\"\"Builds a ResNet as a simple sequential model.\n\n Note:\n The implementation is copied from :mod:`torchvision.models.resnet`.\n\n \"\"\"\n inplanes = 64\n if block.__name__ == 'basicblock':\n expansion = 1\n elif block.__name__ == 'bottleneck':\n expansion = 4\n else:\n raise Exception('Invalid block')\n\n def make_layer(block, planes, blocks, stride=1, inplace=False):\n nonlocal inplanes\n nonlocal expansion\n\n downsample = None\n if stride != 1 or inplanes != planes * expansion:\n downsample = nn.Sequential(\n nn.Conv2d(inplanes, planes * expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * expansion),\n )\n\n layers = []\n layers.append(block(inplanes, planes, stride, downsample, inplace))\n inplanes = planes * expansion\n for _ in range(1, blocks):\n layers.append(block(inplanes, planes, inplace=inplace))\n\n return nn.Sequential(*layers)\n\n # Build ResNet as a sequential model.\n model = nn.Sequential(OrderedDict([\n ('conv1', nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)),\n ('bn1', nn.BatchNorm2d(64)),\n ('relu', nn.ReLU()),\n ('maxpool', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),\n\n ('layer1', make_layer(block, 64, layers[0], inplace=inplace)),\n ('layer2', make_layer(block, 128, layers[1], stride=2, inplace=inplace)),\n ('layer3', make_layer(block, 256, layers[2], stride=2, inplace=inplace)),\n ('layer4', make_layer(block, 512, layers[3], stride=2, inplace=inplace)),\n\n ('avgpool', nn.AdaptiveAvgPool2d((1, 1))),\n ('flat', nn.Flatten()),\n ('fc', nn.Linear(512 * expansion, num_classes)),\n ]))\n\n # Flatten nested sequentials.\n model = flatten_sequential(model)\n\n # Initialize weights for Conv2d and BatchNorm2d layers.\n # Stolen from torchvision-0.4.0.\n def init_weight(m: nn.Module) -> None:\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n return\n\n if isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n return\n\n model.apply(init_weight)\n\n return model\n\n\ndef inet_resnet18(**kwargs: Any) -> nn.Sequential:\n \"\"\"Constructs a ResNet-101 model.\"\"\"\n return build_resnet([2, 2, 2, 2], basicblock, **kwargs)\n\ndef inet_resnet34(**kwargs: Any) -> nn.Sequential:\n \"\"\"Constructs a ResNet-101 model.\"\"\"\n return build_resnet([3, 4, 6, 3], basicblock, **kwargs)\n\ndef inet_resnet50(**kwargs: Any) -> nn.Sequential:\n \"\"\"Constructs a ResNet-101 model.\"\"\"\n return build_resnet([3, 4, 6, 3], bottleneck, **kwargs)\n\ndef inet_resnet101(**kwargs: Any) -> nn.Sequential:\n \"\"\"Constructs a ResNet-101 model.\"\"\"\n return build_resnet([3, 4, 23, 3], bottleneck, **kwargs)\n\ndef inet_resnet152(**kwargs: Any) -> nn.Sequential:\n \"\"\"Constructs a ResNet-101 model.\"\"\"\n return build_resnet([3, 8, 36, 3], bottleneck, **kwargs)\n" ]
[ [ "torch.cuda.get_device_properties", "torch.cuda.synchronize", "torch.empty", "torch.cuda.manual_seed", "torch.zeros", "torch.cuda.set_device", "torch.manual_seed", "torch.max", "torch.nn.functional.cross_entropy", "torch.cuda.current_device", "torch.cuda.memory_stats", "torch.no_grad", "torch.device", "torch.cuda.device_count" ], [ "torch.max", "torch.cuda.manual_seed", "torch.zeros", "torch.cuda.current_device", "torch.manual_seed", "torch.nn.functional.cross_entropy", "torch.no_grad", "torch.device" ], [ "torch.distributed.broadcast", "torch.ones", "torch.distributed.send", "torch.cuda.set_device", "torch.zeros", "torch.distributed.all_gather", "torch.distributed.recv", "torch.tensor", "torch.distributed.new_group", "torch.IntTensor", "torch.distributed.get_world_size", "torch.ones_like" ], [ "torch.nn.Sequential", "torch.nn.init.constant_", "torch.nn.Conv2d", "torch.nn.Flatten", "torch.nn.MaxPool2d", "torch.nn.Linear", "torch.nn.AdaptiveAvgPool2d", "torch.nn.BatchNorm2d", "torch.nn.ReLU", "torch.nn.init.kaiming_normal_" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
bartubozkurt/data_analysis
[ "536d2bc9f75b9d8ff28cc2859a52498dd2f65627" ]
[ "Data_Analysis-main/Pandas/work_with_series.py" ]
[ "import pandas as pd\r\nimport numpy as np\r\n\r\ndata = np.array([\"Bartu\",\"Bozkurt\",\"Osman\"])\r\n# s = pd.Series(data)\r\ns = pd.Series(data ,index = [1,2,3])\r\nprint(s)\r\n\"\"\" \r\n 0 Bartu\r\n 1 Bozkurt\r\n 2 Osman\r\n dtype: object\r\n\"\"\"\r\n\"\"\" \r\n 1 Bartu\r\n 2 Bozkurt\r\n 3 Osman\r\n dtype: object \r\n\"\"\"\r\nprint('-----------------------------------')\r\n\r\ndata2 = {\"Matematik\" : 10, \"Fizik\": 20,\"Beden Eğitimi\": 100}\r\n#s2 = pd.Series(data2)\r\ns2 = pd.Series(data2, index = [\"Fizik\",\"Matematik\",\"Beden Eğitimi\"])\r\nprint(s2)\r\n\"\"\" \r\n Matematik 10\r\n Fizik 20\r\n Beden Eğitimi 100\r\n dtype: int64 \r\n\"\"\"\r\n\"\"\" \r\n Fizik 20\r\n Matematik 10\r\n Beden Eğitimi 100\r\n dtype: int64 \r\n\"\"\"\r\n\r\nprint('-----------------------------------')\r\n\r\ns3 = pd.Series(5, index = [1,2,3])\r\nprint(s3)\r\n\"\"\"\r\n 1 5\r\n 2 5\r\n 3 5\r\n dtype: int64\r\n \"\"\"\r\n\r\n" ]
[ [ "numpy.array", "pandas.Series" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
blockboard/spiralpp
[ "b45cb108e0791ddcf3cbd567151f67a0245a13cd" ]
[ "tests/contiguous_arrays_test.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\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\"\"\"Test that non-contiguous arrays are handled properly.\"\"\"\n\nimport subprocess\nimport threading\nimport unittest\n\nimport numpy as np\n\nimport torch\n\nimport libtorchbeast\n\n\nclass ContiguousArraysTest(unittest.TestCase):\n def setUp(self):\n self.server_proc = subprocess.Popen(\n [\"python\", \"tests/contiguous_arrays_env.py\"]\n )\n\n server_address = [\"unix:/tmp/contiguous_arrays_test\"]\n self.learner_queue = libtorchbeast.BatchingQueue(\n batch_dim=1, minimum_batch_size=1, maximum_batch_size=10, check_inputs=True\n )\n self.replay_queue = libtorchbeast.BatchingQueue(\n batch_dim=1, minimum_batch_size=1, maximum_batch_size=1, check_inputs=True\n )\n self.inference_batcher = libtorchbeast.DynamicBatcher(\n batch_dim=1,\n minimum_batch_size=1,\n maximum_batch_size=10,\n timeout_ms=100,\n check_outputs=True,\n )\n actor = libtorchbeast.ActorPool(\n unroll_length=1,\n learner_queue=self.learner_queue,\n replay_queue=self.replay_queue,\n inference_batcher=self.inference_batcher,\n env_server_addresses=server_address,\n initial_agent_state=(),\n )\n\n def run():\n actor.run()\n\n self.actor_thread = threading.Thread(target=run)\n self.actor_thread.start()\n\n self.target = np.arange(3 * 4 * 5)\n self.target = self.target.reshape(3, 4, 5)\n self.target = self.target.transpose(2, 1, 0)\n\n def check_inference_inputs(self):\n batch = next(self.inference_batcher)\n batched_env_outputs, _ = batch.get_inputs()\n frame, *_ = batched_env_outputs\n self.assertTrue(np.array_equal(frame.shape, (1, 1, 5, 4, 3)))\n frame = frame.reshape(5, 4, 3)\n self.assertTrue(np.array_equal(frame, self.target))\n # Set an arbitrary output.\n batch.set_outputs(((torch.ones(1, 1),), ()))\n\n def test_contiguous_arrays(self):\n self.check_inference_inputs()\n # Stop actor thread.\n self.inference_batcher.close()\n self.learner_queue.close()\n self.actor_thread.join()\n\n def tearDown(self):\n self.server_proc.terminate()\n" ]
[ [ "numpy.arange", "torch.ones", "numpy.array_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Bukkster/fiftyone
[ "c061216de5094131c8ce8718d8a6ac58056b003e" ]
[ "tests/unittests/utils_tests.py" ]
[ "\"\"\"\nFiftyOne utilities unit tests.\n\n| Copyright 2017-2022, Voxel51, Inc.\n| `voxel51.com <https://voxel51.com/>`_\n|\n\"\"\"\nimport time\nimport unittest\n\nfrom mongoengine.errors import ValidationError\nimport numpy as np\n\nimport fiftyone as fo\nimport fiftyone.constants as foc\nimport fiftyone.core.media as fom\nimport fiftyone.core.uid as fou\nfrom fiftyone.migrations.runner import MigrationRunner\n\nfrom decorators import drop_datasets\n\n\nclass LabelsTests(unittest.TestCase):\n @drop_datasets\n def test_create(self):\n labels = fo.Classification(label=\"cow\", confidence=0.98)\n self.assertIsInstance(labels, fo.Classification)\n\n with self.assertRaises(ValidationError):\n fo.Classification(label=100)\n\n @drop_datasets\n def test_copy(self):\n dataset = fo.Dataset()\n\n dataset.add_sample(\n fo.Sample(\n filepath=\"filepath1.jpg\",\n test_dets=fo.Detections(\n detections=[\n fo.Detection(\n label=\"friend\",\n confidence=0.9,\n bounding_box=[0, 0, 0.5, 0.5],\n )\n ]\n ),\n )\n )\n\n sample = dataset.first()\n sample2 = sample.copy()\n\n self.assertIsNot(sample2, sample)\n self.assertNotEqual(sample2.id, sample.id)\n self.assertIsNot(sample2.test_dets, sample.test_dets)\n det = sample.test_dets.detections[0]\n det2 = sample2.test_dets.detections[0]\n self.assertIsNot(det2, det)\n self.assertNotEqual(det2.id, det.id)\n\n\nclass SerializationTests(unittest.TestCase):\n def test_embedded_document(self):\n label1 = fo.Classification(label=\"cat\", logits=np.arange(4))\n\n label2 = fo.Classification(label=\"cat\", logits=np.arange(4))\n\n d1 = label1.to_dict()\n d2 = label2.to_dict()\n d1.pop(\"_id\")\n d2.pop(\"_id\")\n self.assertDictEqual(d1, d2)\n\n d = label1.to_dict()\n self.assertEqual(fo.Classification.from_dict(d), label1)\n\n s = label1.to_json(pretty_print=False)\n self.assertEqual(fo.Classification.from_json(s), label1)\n\n s = label1.to_json(pretty_print=True)\n self.assertEqual(fo.Classification.from_json(s), label1)\n\n def test_sample_no_dataset(self):\n \"\"\"This test only works if the samples do not have Classification or\n Detection fields because of the autogenerated ObjectIDs.\n \"\"\"\n sample1 = fo.Sample(\n filepath=\"~/Desktop/test.png\",\n tags=[\"test\"],\n vector=np.arange(5),\n array=np.ones((2, 3)),\n float=5.1,\n bool=True,\n int=51,\n )\n\n sample2 = fo.Sample(\n filepath=\"~/Desktop/test.png\",\n tags=[\"test\"],\n vector=np.arange(5),\n array=np.ones((2, 3)),\n float=5.1,\n bool=True,\n int=51,\n )\n self.assertDictEqual(sample1.to_dict(), sample2.to_dict())\n\n self.assertEqual(\n fo.Sample.from_dict(sample1.to_dict()).to_dict(), sample1.to_dict()\n )\n\n @drop_datasets\n def test_sample_in_dataset(self):\n \"\"\"This test only works if the samples do not have Classification or\n Detection fields because of the autogenerated ObjectIDs.\n \"\"\"\n dataset1 = fo.Dataset()\n dataset2 = fo.Dataset()\n\n sample1 = fo.Sample(\n filepath=\"~/Desktop/test.png\",\n tags=[\"test\"],\n vector=np.arange(5),\n array=np.ones((2, 3)),\n float=5.1,\n bool=True,\n int=51,\n )\n\n sample2 = fo.Sample(\n filepath=\"~/Desktop/test.png\",\n tags=[\"test\"],\n vector=np.arange(5),\n array=np.ones((2, 3)),\n float=5.1,\n bool=True,\n int=51,\n )\n\n self.assertDictEqual(sample1.to_dict(), sample2.to_dict())\n\n dataset1.add_sample(sample1)\n dataset2.add_sample(sample2)\n\n self.assertNotEqual(sample1, sample2)\n\n s1 = fo.Sample.from_dict(sample1.to_dict())\n s2 = fo.Sample.from_dict(sample2.to_dict())\n\n self.assertFalse(s1.in_dataset)\n self.assertNotEqual(s1, sample1)\n\n self.assertDictEqual(s1.to_dict(), s2.to_dict())\n\n\nclass MediaTypeTests(unittest.TestCase):\n @drop_datasets\n def setUp(self):\n self.img_sample = fo.Sample(filepath=\"image.png\")\n self.img_dataset = fo.Dataset()\n self.img_dataset.add_sample(self.img_sample)\n\n self.vid_sample = fo.Sample(filepath=\"video.mp4\")\n self.vid_dataset = fo.Dataset()\n self.vid_dataset.add_sample(self.vid_sample)\n\n def test_img_types(self):\n self.assertEqual(self.img_sample.media_type, fom.IMAGE)\n self.assertEqual(self.img_dataset.media_type, fom.IMAGE)\n\n def test_vid_types(self):\n self.assertEqual(self.vid_sample.media_type, fom.VIDEO)\n self.assertEqual(self.vid_dataset.media_type, fom.VIDEO)\n\n def test_img_change_attempts(self):\n with self.assertRaises(fom.MediaTypeError):\n self.img_sample.filepath = \"video.mp4\"\n\n def test_vid_change_attempts(self):\n with self.assertRaises(fom.MediaTypeError):\n self.vid_sample.filepath = \"image.png\"\n\n\nclass MigrationTests(unittest.TestCase):\n def test_runner(self):\n def revs(versions):\n return [(v, v + \".py\") for v in versions]\n\n runner = MigrationRunner(\n head=\"0.0.1\",\n destination=\"0.3\",\n _revisions=revs([\"0.1\", \"0.2\", \"0.3\"]),\n )\n self.assertEqual(runner.revisions, [\"0.1\", \"0.2\", \"0.3\"])\n\n runner = MigrationRunner(\n head=\"0.1\",\n destination=\"0.3\",\n _revisions=revs([\"0.1\", \"0.2\", \"0.3\"]),\n )\n self.assertEqual(runner.revisions, [\"0.2\", \"0.3\"])\n\n runner = MigrationRunner(\n head=\"0.3\",\n destination=\"0.1\",\n _revisions=revs([\"0.1\", \"0.2\", \"0.3\"]),\n )\n self.assertEqual(runner.revisions, [\"0.3\", \"0.2\"])\n\n runner = MigrationRunner(\n head=\"0.3\",\n destination=\"0.0.1\",\n _revisions=revs([\"0.1\", \"0.2\", \"0.3\"]),\n )\n self.assertEqual(runner.revisions, [\"0.3\", \"0.2\", \"0.1\"])\n\n def test_future(self):\n pkg_ver = foc.VERSION\n future_ver = str(int(pkg_ver[0]) + 1) + pkg_ver[1:]\n\n # Uprading to a future version is not allowed\n\n with self.assertRaises(EnvironmentError):\n MigrationRunner(destination=future_ver)\n\n with self.assertRaises(EnvironmentError):\n MigrationRunner(head=\"0.1\", destination=future_ver)\n\n # Downgrading from a future version is not allowed\n\n with self.assertRaises(EnvironmentError):\n MigrationRunner(head=future_ver)\n\n with self.assertRaises(EnvironmentError):\n MigrationRunner(head=future_ver, destination=\"0.1\")\n\n\nclass UIDTests(unittest.TestCase):\n def test_log_import(self):\n fo.config.do_not_track = False\n foc.UA_ID = foc.UA_DEV\n\n fou.log_import_if_allowed(test=True)\n time.sleep(2)\n self.assertTrue(fou._import_logged)\n\n\nif __name__ == \"__main__\":\n fo.config.show_progress_bars = False\n unittest.main(verbosity=2)\n" ]
[ [ "numpy.arange", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
LeiWang1999/buddy-mlir
[ "05996fdbe1a2643299c2cb5441c0e6bad2f9848f" ]
[ "examples/ConvOpt/comparison/onnxruntime-conv2d.py" ]
[ "import numpy as np\nimport cv2\nimport onnxruntime\nimport time\n\ndef test_conv2d(img, filter_size):\n start = time.time()\n # Load the model\n model_path = f'conv_{filter_size}x{filter_size}.onnx'\n ort_session = onnxruntime.InferenceSession(model_path)\n # Run inference\n ort_inputs = {ort_session.get_inputs()[0].name: img}\n ort_outs = ort_session.run(None, ort_inputs)\n edge_detect = ort_outs[0]\n edge_detect = edge_detect.squeeze()\n end = time.time()\n print(f'conv {filter_size}x{filter_size} : {end - start}')\n return edge_detect\n\ndef main():\n img = cv2.imread('../images/YuTu2048.png',cv2.IMREAD_GRAYSCALE)\n # Convert the image to numpy array.\n img = np.array(img, dtype='float32')\n img = img.reshape((1, 1, img.shape[0], img.shape[1]))\n '''\n Perform the edget detection.\n '''\n for i in range(3, 10, 2):\n edge_detect = test_conv2d(img, i)\n cv2.imwrite(f'./onnxruntime-conv2d_{i}.png', edge_detect)\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Ho-Jun-Moon/rosnet
[ "8976dd9660ed6d96d9a4fb260e73dbea8687a94e" ]
[ "rosnet/metrics/_classes.py" ]
[ "import numpy as np\nfrom ..decorator import check_vector\n\nclass MAE:\n def predict(self, y_predict, y):\n result = np.mean(np.abs(y_predict - y))\n return result\n \n def __str__(self):\n return 'mae'\n\nclass MSE:\n @check_vector\n def predict(self, y_predict, y):\n result = np.square(y_predict - y)\n result = np.mean(result)\n return result\n\n @check_vector\n def d(self, y_predict, y):\n diff = y_predict - y\n shape = diff.shape\n result = 1\n result = result * np.ones(shape)/np.prod(shape)\n result = result * 2 * diff\n\n return result\n\n def __str__(self):\n return 'mse'\n\nclass BINARY_CROSS_ENTROPY:\n @check_vector\n def predict(self, y_predict, y):\n H = self.get_H(y_predict, y)\n result = np.mean(H)\n\n return result\n\n def relu(self, X):\n return np.maximum(X,0)\n\n def transform(self, X):\n # input : 변환하고자하는 값\n # output[1] : 변환된 값\n # 시그모이드 값 대입하는 함수\n return np.exp(-self.relu(-X))/(1.0 + np.exp(-np.abs(X)))\n\n def derv_H_sigmoid(self, logit, z): # z는 참 레이블\n return -z + self.transform(logit)\n\n def get_H(self, X, z):\n return self.relu(X) - X * z + np.log(1 + np.exp(-np.abs(X)))\n \n @check_vector\n def d(self, y_predict, y):\n result = 1.0 / np.prod(y_predict.shape)\n result = result * self.derv_H_sigmoid(y_predict, y) \n\n return result\n\n def __str__(self):\n return 'BINARY_CROSS_ENTROPY'\n\nclass ACCURACY:\n @check_vector\n def predict(self, y_predict, y):\n est_yes = np.greater(y_predict, 0.5)\n ans_yes = np.greater(y, 0.5)\n est_no = np.logical_not(est_yes)\n ans_no = np.logical_not(ans_yes)\n\n tp = np.sum(np.logical_and(est_yes, ans_yes))\n fp = np.sum(np.logical_and(est_yes, ans_no))\n fn = np.sum(np.logical_and(est_no, ans_yes))\n tn = np.sum(np.logical_and(est_no, ans_no))\n\n result = self.safe_div(tp+tn, tp+tn+fp+fn)\n return result\n\n def safe_div(self, p, q):\n p, q = float(p), float(q)\n if np.abs(q) < 1.0e-20: return np.sign(p)\n return p / q\n\n def __str__(self):\n return 'ACCURACY'\n\n\nclass PRECISION:\n @check_vector\n def predict(self, y_predict, y):\n est_yes = np.greater(y_predict, 0)\n ans_yes = np.greater(y, 0.5)\n est_no = np.logical_not(est_yes)\n ans_no = np.logical_not(ans_yes)\n\n tp = np.sum(np.logical_and(est_yes, ans_yes))\n fp = np.sum(np.logical_and(est_yes, ans_no))\n fn = np.sum(np.logical_and(est_no, ans_yes))\n tn = np.sum(np.logical_and(est_no, ans_no))\n\n result = self.safe_div(tp, tp+fp)\n return result\n\n def safe_div(self, p, q):\n p, q = float(p), float(q)\n if np.abs(q) < 1.0e-20: return np.sign(p)\n return p / q\n\n def __str__(self):\n return 'PRECISION'\n\nclass RECALL:\n @check_vector\n def predict(self, y_predict, y):\n est_yes = np.greater(y_predict, 0)\n ans_yes = np.greater(y, 0.5)\n est_no = np.logical_not(est_yes)\n ans_no = np.logical_not(ans_yes)\n\n tp = np.sum(np.logical_and(est_yes, ans_yes))\n fp = np.sum(np.logical_and(est_yes, ans_no))\n fn = np.sum(np.logical_and(est_no, ans_yes))\n tn = np.sum(np.logical_and(est_no, ans_no))\n\n result = self.safe_div(tp, tp+fn)\n return result\n\n def safe_div(self, p, q):\n p, q = float(p), float(q)\n if np.abs(q) < 1.0e-20: return np.sign(p)\n return p / q\n\n def __str__(self):\n return 'RECALL'\n\nclass F1:\n @check_vector\n def predict(self, y_predict, y):\n est_yes = np.greater(y_predict, 0)\n ans_yes = np.greater(y, 0.5)\n est_no = np.logical_not(est_yes)\n ans_no = np.logical_not(ans_yes)\n\n tp = np.sum(np.logical_and(est_yes, ans_yes))\n fp = np.sum(np.logical_and(est_yes, ans_no))\n fn = np.sum(np.logical_and(est_no, ans_yes))\n tn = np.sum(np.logical_and(est_no, ans_no))\n\n recall = self.safe_div(tp, tp+fn)\n precision = self.safe_div(tp, tp+fp)\n result = 2 * self.safe_div(recall*precision, recall+precision)\n return result\n\n def safe_div(self, p, q):\n p, q = float(p), float(q)\n if np.abs(q) < 1.0e-20: return np.sign(p)\n return p / q\n\n def __str__(self):\n return 'F1'\n\nclass BINARY_CROSS_ENTROPY_WEIGHT:\n def __init__(self):\n self.weight = None\n \n @check_vector\n def predict(self, y_predict, y):\n if self.weight is None:\n self.weight = np.ones(y.shape) / len(y)\n\n H = self.get_H(y_predict, y)\n result = np.sum(H * self.weight)\n\n return result\n\n def set_weight(self, w):\n if len(w.shape) == 1:\n w = w.reshape(-1,1)\n \n self.weight = w\n\n def relu(self, X):\n return np.maximum(X,0)\n\n def transform(self, X):\n # input : 변환하고자하는 값\n # output[1] : 변환된 값\n # 시그모이드 값 대입하는 함수\n return np.exp(-self.relu(X))/(1.0 + np.exp(-np.abs(X)))\n\n def derv_H_sigmoid(self, logit, z): # z는 참 레이블\n return -z + self.transform(logit)\n\n def get_H(self, X, z):\n return self.relu(X) - X * z + np.log(1 + np.exp(-np.abs(X)))\n \n @check_vector\n def d(self, y_predict, y):\n result = self.weight\n result = result * self.derv_H_sigmoid(y_predict, y) \n\n return result\n\n def __str__(self):\n return 'BINARY_CROSS_ENTROPY_WEIGHT'\n\n" ]
[ [ "numpy.square", "numpy.logical_not", "numpy.maximum", "numpy.greater", "numpy.abs", "numpy.ones", "numpy.sign", "numpy.mean", "numpy.prod", "numpy.logical_and", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
johnamcleod/agents
[ "5ab7026e47503f14ef02918acfae340f4128dcd4", "756f7bdf493986c25eb585438134f1dbb8045b1b", "5ab7026e47503f14ef02918acfae340f4128dcd4", "5ab7026e47503f14ef02918acfae340f4128dcd4" ]
[ "tf_agents/environments/examples/tic_tac_toe_environment.py", "tf_agents/bandits/environments/bandit_py_environment.py", "tf_agents/agents/dqn/dqn_agent_test.py", "tf_agents/agents/ppo/ppo_policy.py" ]
[ "# coding=utf-8\n# Copyright 2020 The TF-Agents 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# 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# Lint as: python3\n\"\"\"A state-settable environment for Tic-Tac-Toe game.\"\"\"\n\nimport copy\nimport numpy as np\n\nfrom tf_agents.environments import py_environment\nfrom tf_agents.specs import BoundedArraySpec\nfrom tf_agents.trajectories.time_step import StepType\nfrom tf_agents.trajectories.time_step import TimeStep\n\n\nclass TicTacToeEnvironment(py_environment.PyEnvironment):\n \"\"\"A state-settable environment for Tic-Tac-Toe game.\n\n For MCTS/AlphaZero, we need to keep states of the environment in a node and\n later restore them once MCTS selects which node to visit. This requires\n calling into get_state() and set_state() functions.\n\n The states are a 3 x 3 array where 0 = empty, 1 = player, 2 = opponent.\n The action is a 2-d vector to indicate the position for the player's move.\n \"\"\"\n REWARD_WIN = np.asarray(1., dtype=np.float32)\n REWARD_LOSS = np.asarray(-1., dtype=np.float32)\n REWARD_DRAW_OR_NOT_FINAL = np.asarray(0., dtype=np.float32)\n # A very small number such that it does not affect the value calculation.\n REWARD_ILLEGAL_MOVE = np.asarray(-.001, dtype=np.float32)\n\n REWARD_WIN.setflags(write=False)\n REWARD_LOSS.setflags(write=False)\n REWARD_DRAW_OR_NOT_FINAL.setflags(write=False)\n\n def __init__(self, rng: np.random.RandomState = None, discount=1.0):\n \"\"\"Initializes TicTacToeEnvironment.\n\n Args:\n rng: If a random generator is provided, the opponent will choose a random\n empty space. If None is provided, the opponent will choose the first\n empty space.\n discount: Discount for reward.\n \"\"\"\n super(TicTacToeEnvironment, self).__init__()\n self._rng = rng\n self._discount = np.asarray(discount, dtype=np.float32)\n\n self._states = None\n\n def action_spec(self):\n return BoundedArraySpec((2,), np.int32, minimum=0, maximum=2)\n\n def observation_spec(self):\n return BoundedArraySpec((3, 3), np.int32, minimum=0, maximum=2)\n\n def _reset(self):\n self._states = np.zeros((3, 3), np.int32)\n return TimeStep(StepType.FIRST, np.asarray(0.0, dtype=np.float32),\n self._discount, self._states)\n\n def _legal_actions(self, states: np.ndarray):\n return list(zip(*np.where(states == 0)))\n\n def _opponent_play(self, states: np.ndarray):\n actions = self._legal_actions(np.array(states))\n if not actions:\n raise RuntimeError('There is no empty space for opponent to play at.')\n\n if self._rng:\n i = self._rng.randint(len(actions))\n else:\n i = 0\n return actions[i]\n\n def get_state(self) -> TimeStep:\n # Returning an unmodifiable copy of the state.\n return copy.deepcopy(self._current_time_step)\n\n def set_state(self, time_step: TimeStep):\n self._current_time_step = time_step\n self._states = time_step.observation\n\n def _step(self, action: np.ndarray):\n if self._current_time_step.is_last():\n return self._reset()\n\n action = tuple(action)\n if self._states[action] != 0:\n return TimeStep(StepType.LAST, TicTacToeEnvironment.REWARD_ILLEGAL_MOVE,\n self._discount, self._states)\n\n self._states[action] = 1\n\n is_final, reward = self._check_states(self._states)\n if is_final:\n return TimeStep(StepType.LAST, reward, self._discount,\n self._states)\n\n # TODO(b/152638947): handle multiple agents properly.\n # Opponent places '2' on the board.\n opponent_action = self._opponent_play(self._states)\n self._states[opponent_action] = 2\n\n is_final, reward = self._check_states(self._states)\n\n step_type = StepType.MID\n if np.all(self._states == 0):\n step_type = StepType.FIRST\n elif is_final:\n step_type = StepType.LAST\n\n return TimeStep(step_type, reward, self._discount, self._states)\n\n def _check_states(self, states: np.ndarray):\n \"\"\"Check if the given states are final and calculate reward.\n\n Args:\n states: states of the board.\n\n Returns:\n A tuple of (is_final, reward) where is_final means whether the states\n are final are not, and reward is the reward for stepping into the states\n The meaning of reward: 0 = not decided or draw, 1 = win, -1 = loss\n \"\"\"\n seqs = np.array([\n # each row\n states[0, :], states[1, :], states[2, :],\n # each column\n states[:, 0], states[:, 1], states[:, 2],\n # diagonal\n states[(0, 1, 2), (0, 1, 2)],\n states[(2, 1, 0), (0, 1, 2)],\n ])\n seqs = seqs.tolist()\n if [1, 1, 1] in seqs:\n return True, TicTacToeEnvironment.REWARD_WIN # win\n if [2, 2, 2] in seqs:\n return True, TicTacToeEnvironment.REWARD_LOSS # loss\n if 0 in states:\n # Not final\n return False, TicTacToeEnvironment.REWARD_DRAW_OR_NOT_FINAL\n return True, TicTacToeEnvironment.REWARD_DRAW_OR_NOT_FINAL # draw\n", "# coding=utf-8\n# Copyright 2020 The TF-Agents 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# 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\"\"\"Base class for Bandit Python environments.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\n# Using Type Annotations.\nfrom __future__ import print_function\n\nimport abc\nfrom typing import Optional, Text\nimport numpy as np\n\nimport tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import\n\nfrom tf_agents.environments import py_environment\nfrom tf_agents.trajectories import time_step as ts\nfrom tf_agents.typing import types\n\n\nclass BanditPyEnvironment(py_environment.PyEnvironment):\n \"\"\"Base class for Bandit Python environments.\n\n Every bandit Python environment should derive from this class.\n Subclasses need to implement functions _observe() and _apply_action().\n\n Usage:\n\n To receive the first observation, the environment's reset() function should be\n called. To take an action, use the step(action) function. The time step\n returned by step(action) will contain the reward and the next observation.\n \"\"\"\n\n def __init__(self,\n observation_spec: types.NestedArray,\n action_spec: types.NestedArray,\n reward_spec: Optional[types.NestedArray] = None,\n name: Optional[Text] = None):\n self._observation_spec = observation_spec\n self._action_spec = action_spec\n self._reward_spec = reward_spec\n self._name = name\n super(BanditPyEnvironment, self).__init__()\n\n def _reset(self) -> ts.TimeStep:\n \"\"\"Returns a time step containing an observation.\n\n It should not be overridden by Bandit environment implementations.\n\n Returns:\n A time step of type FIRST containing an observation.\n \"\"\"\n return ts.restart(self._observe(), batch_size=self.batch_size,\n reward_spec=self.reward_spec())\n\n def _step(self, action: types.NestedArray) -> ts.TimeStep:\n \"\"\"Returns a time step containing the reward for the action taken.\n\n The returning time step also contains the next observation.\n It should not be overridden by bandit environment implementations.\n\n Args:\n action: The action taken by the Bandit policy.\n\n Returns:\n A time step of type LAST containing the reward for the action taken and\n the next observation.\n \"\"\"\n # This step will take an action and return a reward.\n reward = self._apply_action(action)\n return ts.termination(self._observe(), reward)\n\n def action_spec(self) -> types.NestedArraySpec:\n return self._action_spec\n\n def observation_spec(self) -> types.NestedArraySpec:\n return self._observation_spec\n\n def reward_spec(self) -> types.NestedArraySpec:\n return self._reward_spec\n\n def _empty_observation(self):\n return tf.nest.map_structure(lambda x: np.zeros(x.shape, x.dtype),\n self.observation_spec())\n\n @abc.abstractmethod\n def _apply_action(self, action: types.NestedArray) -> types.Float:\n \"\"\"Applies `action` to the Environment and returns the corresponding reward.\n\n Args:\n action: A value conforming action_spec that will be taken as action in the\n environment.\n\n Returns:\n A float value that is the reward received by the environment.\n \"\"\"\n\n @abc.abstractmethod\n def _observe(self) -> types.NestedArray:\n \"\"\"Returns an observation.\"\"\"\n\n @property\n def name(self) -> Text:\n return self._name\n", "# coding=utf-8\n# Copyright 2020 The TF-Agents 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# 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\"\"\"Tests for agents.dqn.dqn_agent.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import\n\nfrom tf_agents.agents.dqn import dqn_agent\nfrom tf_agents.networks import network\nfrom tf_agents.networks import q_network\nfrom tf_agents.networks import sequential\nfrom tf_agents.networks import test_utils as networks_test_utils\nfrom tf_agents.specs import tensor_spec\nfrom tf_agents.trajectories import policy_step\nfrom tf_agents.trajectories import test_utils as trajectories_test_utils\nfrom tf_agents.trajectories import time_step as ts\nfrom tf_agents.trajectories import trajectory\nfrom tf_agents.utils import common\nfrom tf_agents.utils import test_utils\n\n\nclass DummyNet(network.Network):\n\n def __init__(self,\n observation_spec,\n action_spec,\n l2_regularization_weight=0.0,\n name=None):\n super(DummyNet, self).__init__(\n observation_spec, state_spec=(), name=name)\n num_actions = action_spec.maximum - action_spec.minimum + 1\n\n # Store custom layers that can be serialized through the Checkpointable API.\n self._dummy_layers = [\n tf.keras.layers.Dense(\n num_actions,\n kernel_regularizer=tf.keras.regularizers.l2(\n l2_regularization_weight),\n kernel_initializer=tf.constant_initializer([[num_actions, 1],\n [1, 1]]),\n bias_initializer=tf.constant_initializer([[1], [1]]))\n ]\n\n def call(self, inputs, step_type=None, network_state=()):\n del step_type\n inputs = tf.cast(inputs, tf.float32)\n for layer in self._dummy_layers:\n inputs = layer(inputs)\n return inputs, network_state\n\n\nclass ComputeTDTargetsTest(test_utils.TestCase):\n\n def testComputeTDTargets(self):\n next_q_values = tf.constant([10, 20], dtype=tf.float32)\n rewards = tf.constant([10, 20], dtype=tf.float32)\n discounts = tf.constant([0.9, 0.9], dtype=tf.float32)\n\n expected_td_targets = [19., 38.]\n td_targets = dqn_agent.compute_td_targets(next_q_values, rewards, discounts)\n self.assertAllClose(self.evaluate(td_targets), expected_td_targets)\n\n\[email protected]_parameters(\n ('DqnAgent', dqn_agent.DqnAgent),\n ('DdqnAgent', dqn_agent.DdqnAgent))\nclass DqnAgentTest(test_utils.TestCase):\n\n def setUp(self):\n super(DqnAgentTest, self).setUp()\n self._observation_spec = tensor_spec.TensorSpec([2], tf.float32)\n self._time_step_spec = ts.time_step_spec(self._observation_spec)\n self._action_spec = tensor_spec.BoundedTensorSpec((), tf.int32, 0, 1)\n\n def testCreateAgent(self, agent_class):\n q_net = DummyNet(self._observation_spec, self._action_spec)\n agent = agent_class(\n self._time_step_spec,\n self._action_spec,\n q_network=q_net,\n optimizer=None)\n self.assertIsNotNone(agent.policy)\n\n def testCreateAgentWithPrebuiltPreprocessingLayers(self, agent_class):\n dense_layer = tf.keras.layers.Dense(2)\n q_net = networks_test_utils.KerasLayersNet(self._observation_spec,\n self._action_spec,\n dense_layer)\n with self.assertRaisesRegexp(\n ValueError, 'shares weights with the original network'):\n agent_class(\n self._time_step_spec,\n self._action_spec,\n q_network=q_net,\n optimizer=None)\n\n # Explicitly share weights between q and target networks.\n # This would be an unusual setup so we check that an error is thrown.\n q_target_net = networks_test_utils.KerasLayersNet(self._observation_spec,\n self._action_spec,\n dense_layer)\n with self.assertRaisesRegexp(\n ValueError, 'shares weights with the original network'):\n agent_class(\n self._time_step_spec,\n self._action_spec,\n q_network=q_net,\n optimizer=None,\n target_q_network=q_target_net)\n\n def testInitializeAgent(self, agent_class):\n q_net = DummyNet(self._observation_spec, self._action_spec)\n agent = agent_class(\n self._time_step_spec,\n self._action_spec,\n q_network=q_net,\n optimizer=None)\n init_op = agent.initialize()\n if not tf.executing_eagerly():\n with self.cached_session() as sess:\n common.initialize_uninitialized_variables(sess)\n self.assertIsNone(sess.run(init_op))\n\n def testCreateAgentDimChecks(self, agent_class):\n action_spec = tensor_spec.BoundedTensorSpec([1, 2], tf.int32, 0, 1)\n q_net = DummyNet(self._observation_spec, action_spec)\n with self.assertRaisesRegex(ValueError, 'Only scalar actions'):\n agent_class(\n self._time_step_spec, action_spec, q_network=q_net, optimizer=None)\n\n def testInvalidNetworkOutputSize(self, agent_class):\n wrong_action_spec = tensor_spec.BoundedTensorSpec((), tf.int32, 0, 2)\n q_net = q_network.QNetwork(\n self._time_step_spec.observation,\n wrong_action_spec)\n with self.assertRaisesRegex(ValueError, r'with inner dims \\(2,\\)'):\n agent_class(\n self._time_step_spec, self._action_spec,\n q_network=q_net, optimizer=None)\n\n # TODO(b/127383724): Add a test where the target network has different values.\n def testLoss(self, agent_class):\n q_net = DummyNet(self._observation_spec, self._action_spec)\n agent = agent_class(\n self._time_step_spec,\n self._action_spec,\n q_network=q_net,\n optimizer=None)\n\n observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)\n time_steps = ts.restart(observations, batch_size=2)\n\n actions = tf.constant([0, 1], dtype=tf.int32)\n action_steps = policy_step.PolicyStep(actions)\n\n rewards = tf.constant([10, 20], dtype=tf.float32)\n discounts = tf.constant([0.9, 0.9], dtype=tf.float32)\n next_observations = tf.constant([[5, 6], [7, 8]], dtype=tf.float32)\n next_time_steps = ts.transition(next_observations, rewards, discounts)\n\n experience = trajectories_test_utils.stacked_trajectory_from_transition(\n time_steps, action_steps, next_time_steps)\n\n # Using the kernel initializer [[2, 1], [1, 1]] and bias initializer\n # [[1], [1]] from DummyNet above, we can calculate the following values:\n # Q-value for first observation/action pair: 2 * 1 + 1 * 2 + 1 = 5\n # Q-value for second observation/action pair: 1 * 3 + 1 * 4 + 1 = 8\n # (Here we use the second row of the kernel initializer above, since the\n # chosen action is now 1 instead of 0.)\n #\n # For target Q-values, action 0 produces a greater Q-value with a kernel of\n # [2, 1] instead of [1, 1] for action 1.\n # Target Q-value for first next_observation: 2 * 5 + 1 * 6 + 1 = 17\n # Target Q-value for second next_observation: 2 * 7 + 1 * 8 + 1 = 23\n # TD targets: 10 + 0.9 * 17 = 25.3 and 20 + 0.9 * 23 = 40.7\n # TD errors: 25.3 - 5 = 20.3 and 40.7 - 8 = 32.7\n # TD loss: 19.8 and 32.2 (Huber loss subtracts 0.5)\n # Overall loss: (19.8 + 32.2) / 2 = 26\n expected_loss = 26.0\n loss, _ = agent._loss(experience)\n\n self.evaluate(tf.compat.v1.global_variables_initializer())\n self.assertAllClose(self.evaluate(loss), expected_loss)\n\n def testLossWithChangedOptimalActions(self, agent_class):\n q_net = DummyNet(self._observation_spec, self._action_spec)\n agent = agent_class(\n self._time_step_spec,\n self._action_spec,\n q_network=q_net,\n optimizer=None)\n\n observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)\n time_steps = ts.restart(observations, batch_size=2)\n\n actions = tf.constant([0, 1], dtype=tf.int32)\n action_steps = policy_step.PolicyStep(actions)\n\n rewards = tf.constant([10, 20], dtype=tf.float32)\n discounts = tf.constant([0.9, 0.9], dtype=tf.float32)\n\n # Note that instead of [[5, 6], [7, 8]] as before, we now have -5 and -7.\n next_observations = tf.constant([[-5, 6], [-7, 8]], dtype=tf.float32)\n next_time_steps = ts.transition(next_observations, rewards, discounts)\n\n experience = trajectories_test_utils.stacked_trajectory_from_transition(\n time_steps, action_steps, next_time_steps)\n\n # Using the kernel initializer [[2, 1], [1, 1]] and bias initializer\n # [[1], [1]] from DummyNet above, we can calculate the following values:\n # Q-value for first observation/action pair: 2 * 1 + 1 * 2 + 1 = 5\n # Q-value for second observation/action pair: 1 * 3 + 1 * 4 + 1 = 8\n # (Here we use the second row of the kernel initializer above, since the\n # chosen action is now 1 instead of 0.)\n #\n # For the target Q-values here, note that since we've replaced 5 and 7 with\n # -5 and -7, it is better to use action 1 with a kernel of [1, 1] instead of\n # action 0 with a kernel of [2, 1].\n # Target Q-value for first next_observation: 1 * -5 + 1 * 6 + 1 = 2\n # Target Q-value for second next_observation: 1 * -7 + 1 * 8 + 1 = 2\n # TD targets: 10 + 0.9 * 2 = 11.8 and 20 + 0.9 * 2 = 21.8\n # TD errors: 11.8 - 5 = 6.8 and 21.8 - 8 = 13.8\n # TD loss: 6.3 and 13.3 (Huber loss subtracts 0.5)\n # Overall loss: (6.3 + 13.3) / 2 = 9.8\n expected_loss = 9.8\n loss, _ = agent._loss(experience)\n\n self.evaluate(tf.compat.v1.global_variables_initializer())\n self.assertAllClose(self.evaluate(loss), expected_loss)\n\n def testLossWithL2Regularization(self, agent_class):\n q_net = DummyNet(self._observation_spec, self._action_spec,\n l2_regularization_weight=1.0)\n agent = agent_class(\n self._time_step_spec,\n self._action_spec,\n q_network=q_net,\n optimizer=None)\n\n observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)\n time_steps = ts.restart(observations, batch_size=2)\n\n actions = tf.constant([0, 1], dtype=tf.int32)\n action_steps = policy_step.PolicyStep(actions)\n\n rewards = tf.constant([10, 20], dtype=tf.float32)\n discounts = tf.constant([0.9, 0.9], dtype=tf.float32)\n next_observations = tf.constant([[5, 6], [7, 8]], dtype=tf.float32)\n next_time_steps = ts.transition(next_observations, rewards, discounts)\n\n experience = trajectories_test_utils.stacked_trajectory_from_transition(\n time_steps, action_steps, next_time_steps)\n\n # See the loss explanation in testLoss above.\n # L2_regularization_loss: 2^2 + 1^2 + 1^2 + 1^2 = 7.0\n # Overall loss: 26.0 (from testLoss) + 7.0 = 33.0\n expected_loss = 33.0\n loss, _ = agent._loss(experience)\n\n self.evaluate(tf.compat.v1.initialize_all_variables())\n self.assertAllClose(self.evaluate(loss), expected_loss)\n\n def testLossNStep(self, agent_class):\n q_net = DummyNet(self._observation_spec, self._action_spec)\n agent = agent_class(\n self._time_step_spec,\n self._action_spec,\n q_network=q_net,\n optimizer=None,\n n_step_update=2)\n\n observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)\n time_steps = ts.restart(observations, batch_size=2)\n\n actions = tf.constant([0, 1], dtype=tf.int32)\n action_steps = policy_step.PolicyStep(actions)\n\n rewards = tf.constant([10, 20], dtype=tf.float32)\n discounts = tf.constant([0.9, 0.9], dtype=tf.float32)\n next_observations = tf.constant([[5, 6], [7, 8]], dtype=tf.float32)\n next_time_steps = ts.transition(next_observations, rewards, discounts)\n\n third_observations = tf.constant([[9, 10], [11, 12]], dtype=tf.float32)\n third_time_steps = ts.transition(third_observations, rewards, discounts)\n\n experience1 = trajectory.from_transition(\n time_steps, action_steps, next_time_steps)\n experience2 = trajectory.from_transition(\n next_time_steps, action_steps, third_time_steps)\n experience3 = trajectory.from_transition(\n third_time_steps, action_steps, third_time_steps)\n\n experience = tf.nest.map_structure(\n lambda x, y, z: tf.stack([x, y, z], axis=1),\n experience1, experience2, experience3)\n\n # We can extend the analysis from testLoss above as follows:\n # Original Q-values are still 5 and 8 for the same reasons.\n # Q-value for first third_observation: 2 * 9 + 1 * 10 + 1 = 29\n # Q-value for second third_observation: 2 * 11 + 1 * 12 + 1 = 35\n # TD targets: 10 + 0.9 * (10 + 0.9 * 29) = 42.49\n # 20 + 0.9 * (20 + 0.9 * 35) = 66.35\n # TD errors: 42.49 - 5 = 37.49 and 66.35 - 8 = 58.35\n # TD loss: 36.99 and 57.85 (Huber loss subtracts 0.5)\n # Overall loss: (36.99 + 57.85) / 2 = 47.42\n expected_loss = 47.42\n loss, _ = agent._loss(experience)\n\n self.evaluate(tf.compat.v1.global_variables_initializer())\n self.assertAllClose(self.evaluate(loss), expected_loss)\n\n def testLossRNNSmokeTest(self, agent_class):\n q_net = sequential.Sequential([\n tf.keras.layers.LSTM(\n 2, return_state=True, return_sequences=True,\n kernel_initializer=tf.constant_initializer(0.5),\n recurrent_initializer=tf.constant_initializer(0.5)),\n ])\n\n agent = agent_class(\n self._time_step_spec,\n self._action_spec,\n q_network=q_net,\n gamma=0.95,\n optimizer=None)\n\n observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)\n time_steps = ts.restart(observations, batch_size=2)\n\n rewards = tf.constant([10, 20], dtype=tf.float32)\n discounts = tf.constant([0.7, 0.8], dtype=tf.float32)\n\n next_observations = tf.constant([[5, 6], [7, 8]], dtype=tf.float32)\n next_time_steps = ts.transition(next_observations, rewards, discounts)\n third_observations = tf.constant([[9, 10], [11, 12]], dtype=tf.float32)\n third_time_steps = ts.transition(third_observations, rewards, discounts)\n\n actions = tf.constant([0, 1], dtype=tf.int32)\n action_steps = policy_step.PolicyStep(actions)\n\n experience1 = trajectory.from_transition(\n time_steps, action_steps, next_time_steps)\n experience2 = trajectory.from_transition(\n next_time_steps, action_steps, third_time_steps)\n experience3 = trajectory.from_transition(\n third_time_steps, action_steps, third_time_steps)\n\n experience = tf.nest.map_structure(\n lambda x, y, z: tf.stack([x, y, z], axis=1),\n experience1, experience2, experience3)\n\n loss, _ = agent._loss(experience)\n\n self.evaluate(tf.compat.v1.global_variables_initializer())\n\n # Smoke test, here to make sure the calculation does not change as we\n # modify preprocessing or other internals.\n expected_loss = 28.722265\n self.assertAllClose(self.evaluate(loss), expected_loss)\n\n def testLossNStepMidMidLastFirst(self, agent_class):\n \"\"\"Tests that n-step loss handles LAST time steps properly.\"\"\"\n q_net = DummyNet(self._observation_spec, self._action_spec)\n agent = agent_class(\n self._time_step_spec,\n self._action_spec,\n q_network=q_net,\n optimizer=None,\n n_step_update=3)\n\n observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)\n rewards = tf.constant([10, 20], dtype=tf.float32)\n discounts = tf.constant([0.9, 0.9], dtype=tf.float32)\n # MID: use ts.transition\n time_steps = ts.transition(observations, rewards, discounts)\n\n actions = tf.constant([0, 1], dtype=tf.int32)\n action_steps = policy_step.PolicyStep(actions)\n\n second_observations = tf.constant([[5, 6], [7, 8]], dtype=tf.float32)\n # MID: use ts.transition\n second_time_steps = ts.transition(second_observations, rewards, discounts)\n\n third_observations = tf.constant([[9, 10], [11, 12]], dtype=tf.float32)\n # LAST: use ts.termination\n third_time_steps = ts.termination(third_observations, rewards)\n\n fourth_observations = tf.constant([[13, 14], [15, 16]], dtype=tf.float32)\n # FIRST: use ts.restart\n fourth_time_steps = ts.restart(fourth_observations, batch_size=2)\n\n experience1 = trajectory.from_transition(\n time_steps, action_steps, second_time_steps)\n experience2 = trajectory.from_transition(\n second_time_steps, action_steps, third_time_steps)\n experience3 = trajectory.from_transition(\n third_time_steps, action_steps, fourth_time_steps)\n experience4 = trajectory.from_transition(\n fourth_time_steps, action_steps, fourth_time_steps)\n\n experience = tf.nest.map_structure(\n lambda w, x, y, z: tf.stack([w, x, y, z], axis=1),\n experience1, experience2, experience3, experience4)\n\n # Once again we can extend the analysis from testLoss above as follows:\n # Original Q-values are still 5 and 8 for the same reasons.\n # However next Q-values are now zeroed out due to the LAST time step in\n # between. Thus the TD targets become the discounted reward sums, or:\n # 10 + 0.9 * 10 = 19 and 20 + 0.9 * 20 = 38\n # TD errors: 19 - 5 = 14 and 38 - 8 = 30\n # TD loss: 13.5 and 29.5 (Huber loss subtracts 0.5)\n # Overall loss: (13.5 + 29.5) / 2 = 21.5\n expected_loss = 21.5\n loss, _ = agent._loss(experience)\n\n self.evaluate(tf.compat.v1.global_variables_initializer())\n self.assertAllClose(self.evaluate(loss), expected_loss)\n\n def testLossWithMaskedActions(self, agent_class):\n # Observations are now a tuple of the usual observation and an action mask.\n observation_spec_with_mask = (\n self._observation_spec,\n tensor_spec.BoundedTensorSpec([2], tf.int32, 0, 1))\n time_step_spec = ts.time_step_spec(observation_spec_with_mask)\n q_net = DummyNet(self._observation_spec, self._action_spec)\n agent = agent_class(\n time_step_spec,\n self._action_spec,\n q_network=q_net,\n optimizer=None,\n observation_and_action_constraint_splitter=lambda x: (x[0], x[1]))\n\n # For `observations`, the masks are set up so that all actions are valid.\n observations = (tf.constant([[1, 2], [3, 4]], dtype=tf.float32),\n tf.constant([[1, 1], [1, 1]], dtype=tf.int32))\n time_steps = ts.restart(observations, batch_size=2)\n\n actions = tf.constant([0, 1], dtype=tf.int32)\n action_steps = policy_step.PolicyStep(actions)\n\n rewards = tf.constant([10, 20], dtype=tf.float32)\n discounts = tf.constant([0.9, 0.9], dtype=tf.float32)\n\n # For `next_observations`, the masks are set up so that only one action is\n # valid for each element in the batch.\n next_observations = (tf.constant([[5, 6], [7, 8]], dtype=tf.float32),\n tf.constant([[0, 1], [1, 0]], dtype=tf.int32))\n next_time_steps = ts.transition(next_observations, rewards, discounts)\n\n experience = trajectories_test_utils.stacked_trajectory_from_transition(\n time_steps, action_steps, next_time_steps)\n\n # Using the kernel initializer [[2, 1], [1, 1]] and bias initializer\n # [[1], [1]] from DummyNet above, we can calculate the following values:\n # Q-value for first observation/action pair: 2 * 1 + 1 * 2 + 1 = 5\n # Q-value for second observation/action pair: 1 * 3 + 1 * 4 + 1 = 8\n # (Here we use the second row of the kernel initializer above, since the\n # chosen action is now 1 instead of 0.)\n #\n # For target Q-values, because of the masks we only have one valid choice of\n # action for each next_observation:\n # Target Q-value for first next_observation (only action 1 is valid):\n # 1 * 5 + 1 * 6 + 1 = 12\n # Target Q-value for second next_observation (only action 0 is valid):\n # 2 * 7 + 1 * 8 + 1 = 23\n # TD targets: 10 + 0.9 * 12 = 20.8 and 20 + 0.9 * 23 = 40.7\n # TD errors: 20.8 - 5 = 15.8 and 40.7 - 8 = 32.7\n # TD loss: 15.3 and 32.2 (Huber loss subtracts 0.5)\n # Overall loss: (15.3 + 32.2) / 2 = 23.75\n expected_loss = 23.75\n loss, _ = agent._loss(experience)\n\n self.evaluate(tf.compat.v1.global_variables_initializer())\n self.assertAllClose(self.evaluate(loss), expected_loss)\n\n def testPolicy(self, agent_class):\n q_net = DummyNet(self._observation_spec, self._action_spec)\n agent = agent_class(\n self._time_step_spec,\n self._action_spec,\n q_network=q_net,\n optimizer=None)\n observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)\n time_steps = ts.restart(observations, batch_size=2)\n policy = agent.policy\n action_step = policy.action(time_steps)\n # Batch size 2.\n self.assertAllEqual(action_step.action.shape,\n [2] + self._action_spec.shape.as_list())\n self.evaluate(tf.compat.v1.global_variables_initializer())\n actions_ = self.evaluate(action_step.action)\n self.assertTrue(all(actions_ <= self._action_spec.maximum))\n self.assertTrue(all(actions_ >= self._action_spec.minimum))\n\n def testInitializeRestoreAgent(self, agent_class):\n q_net = DummyNet(self._observation_spec, self._action_spec)\n agent = agent_class(\n self._time_step_spec,\n self._action_spec,\n q_network=q_net,\n optimizer=None)\n observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)\n time_steps = ts.restart(observations, batch_size=2)\n policy = agent.policy\n action_step = policy.action(time_steps)\n self.evaluate(tf.compat.v1.global_variables_initializer())\n\n checkpoint = tf.train.Checkpoint(agent=agent)\n\n latest_checkpoint = tf.train.latest_checkpoint(self.get_temp_dir())\n checkpoint_load_status = checkpoint.restore(latest_checkpoint)\n\n if tf.executing_eagerly():\n self.evaluate(checkpoint_load_status.initialize_or_restore())\n self.assertAllEqual(self.evaluate(action_step.action), [0, 0])\n else:\n with self.cached_session() as sess:\n checkpoint_load_status.initialize_or_restore(sess)\n self.assertAllEqual(sess.run(action_step.action), [0, 0])\n\n def testTrainWithSparseTensorAndDenseFeaturesLayer(self, agent_class):\n obs_spec = {\n 'dense': tensor_spec.BoundedTensorSpec(\n dtype=tf.float32, shape=[3], minimum=-10.0, maximum=10.0),\n 'sparse_terms': tf.SparseTensorSpec(dtype=tf.string, shape=[4]),\n 'sparse_frequencies': tf.SparseTensorSpec(dtype=tf.float32, shape=[4]),\n }\n cat_column = (\n tf.compat.v2.feature_column.categorical_column_with_hash_bucket(\n 'sparse_terms', hash_bucket_size=5))\n weighted_cat_column = (\n tf.compat.v2.feature_column.weighted_categorical_column(\n cat_column, weight_feature_key='sparse_frequencies'))\n feature_columns = [\n tf.compat.v2.feature_column.numeric_column('dense', [3]),\n tf.compat.v2.feature_column.embedding_column(weighted_cat_column, 3),\n ]\n dense_features_layer = tf.compat.v2.keras.layers.DenseFeatures(\n feature_columns)\n time_step_spec = ts.time_step_spec(obs_spec)\n q_net = q_network.QNetwork(\n time_step_spec.observation,\n self._action_spec,\n preprocessing_combiner=dense_features_layer)\n agent = agent_class(\n time_step_spec,\n self._action_spec,\n q_network=q_net,\n optimizer=tf.compat.v1.train.AdamOptimizer())\n\n observations = tensor_spec.sample_spec_nest(obs_spec, outer_dims=[5, 2])\n # sparse_terms and sparse_frequencies must be defined on matching indices.\n observations['sparse_terms'] = tf.SparseTensor(\n indices=observations['sparse_frequencies'].indices,\n values=tf.as_string(\n tf.math.round(observations['sparse_frequencies'].values)),\n dense_shape=observations['sparse_frequencies'].dense_shape)\n if not tf.executing_eagerly():\n # Mimic unknown inner dims on the SparseTensor\n def _unknown_inner_shape(t):\n if not isinstance(t, tf.SparseTensor):\n return t\n return tf.SparseTensor(\n indices=t.indices, values=t.values,\n dense_shape=tf.compat.v1.placeholder_with_default(\n t.dense_shape, shape=t.dense_shape.shape))\n observations = tf.nest.map_structure(_unknown_inner_shape, observations)\n self.assertIsNone(tf.get_static_value(\n observations['sparse_terms'].dense_shape))\n\n time_step = ts.restart(observations, batch_size=[5, 2])\n action_step = tensor_spec.sample_spec_nest(\n self._action_spec, outer_dims=[5, 2])\n p_step = policy_step.PolicyStep(action=action_step, state=(), info=())\n traj = trajectory.from_transition(time_step, p_step, time_step)\n loss_info = agent.train(traj)\n self.evaluate(tf.compat.v1.global_variables_initializer())\n loss_info = self.evaluate(loss_info)\n self.assertGreater(loss_info.loss, 0)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# coding=utf-8\n# Copyright 2020 The TF-Agents 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# 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\"\"\"An ActorPolicy that also returns policy_info needed for PPO training.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n# Using Type Annotations.\nfrom __future__ import print_function\n\nfrom typing import Optional\n\nimport gin\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\nfrom tf_agents.agents.ppo import ppo_utils\nfrom tf_agents.distributions import utils as distribution_utils\nfrom tf_agents.networks import network\nfrom tf_agents.policies import actor_policy\nfrom tf_agents.specs import tensor_spec\nfrom tf_agents.trajectories import policy_step\nfrom tf_agents.trajectories import time_step as ts\nfrom tf_agents.typing import types\nfrom tf_agents.utils import nest_utils\nfrom tf_agents.utils import tensor_normalizer\n\n\ntfd = tfp.distributions\n\n\[email protected](module='tf_agents')\nclass PPOPolicy(actor_policy.ActorPolicy):\n \"\"\"An ActorPolicy that also returns policy_info needed for PPO training.\n\n This policy requires two networks: the usual `actor_network` and the\n additional `value_network`. The value network can be executed with the\n `apply_value_network()` method.\n\n When the networks have state (RNNs, LSTMs) you must be careful to pass the\n state for the actor network to `action()` and the state of the value network\n to `apply_value_network()`. Use `get_initial_value_state()` to access\n the state of the value network.\n \"\"\"\n\n def __init__(self,\n time_step_spec: ts.TimeStep,\n action_spec: types.NestedTensorSpec,\n actor_network: network.Network,\n value_network: network.Network,\n observation_normalizer: Optional[\n tensor_normalizer.TensorNormalizer] = None,\n clip: bool = True,\n collect: bool = True,\n compute_value_and_advantage_in_train: bool = False):\n \"\"\"Builds a PPO Policy given network Templates or functions.\n\n Args:\n time_step_spec: A `TimeStep` spec of the expected time_steps.\n action_spec: A nest of BoundedTensorSpec representing the actions.\n actor_network: An instance of a tf_agents.networks.network.Network, with\n call(observation, step_type, network_state). Network should\n return one of the following: 1. a nested tuple of tfp.distributions\n objects matching action_spec, or 2. a nested tuple of tf.Tensors\n representing actions.\n value_network: An instance of a tf_agents.networks.network.Network, with\n call(observation, step_type, network_state). Network should return\n value predictions for the input state.\n observation_normalizer: An object to use for obervation normalization.\n clip: Whether to clip actions to spec before returning them. Default\n True. Most policy-based algorithms (PCL, PPO, REINFORCE) use unclipped\n continuous actions for training.\n collect: If True, creates ops for actions_log_prob, value_preds, and\n action_distribution_params. (default True)\n compute_value_and_advantage_in_train: A bool to indicate where value\n prediction and advantage calculation happen. If True, both happen in\n agent.train(), therefore no need to save the value prediction inside of\n policy info. If False, value prediction is computed during data\n collection. This argument must be set to `False` if mini batch learning\n is enabled.\n\n Raises:\n TypeError: if `actor_network` or `value_network` is not of type\n `tf_agents.networks.Network`.\n ValueError: if `actor_network` or `value_network` do not emit\n valid outputs. For example, `actor_network` must either be\n a (legacy style) `DistributionNetwork`, or explicitly emit\n a nest of `tfp.distribution.Distribution` objects.\n \"\"\"\n if not isinstance(actor_network, network.Network):\n raise TypeError('actor_network is not of type network.Network')\n if not isinstance(value_network, network.Network):\n raise TypeError('value_network is not of type network.Network')\n\n actor_output_spec = actor_network.create_variables(\n time_step_spec.observation)\n\n value_output_spec = value_network.create_variables(\n time_step_spec.observation)\n\n nest_utils.assert_value_spec(\n value_output_spec, 'value_network')\n\n distribution_utils.assert_specs_are_compatible(\n actor_output_spec, action_spec,\n 'actor_network output spec does not match action spec')\n\n self._compute_value_and_advantage_in_train = (\n compute_value_and_advantage_in_train)\n\n if collect:\n if isinstance(actor_network, network.DistributionNetwork):\n # Legacy DistributionNetwork case. New code can just provide a regular\n # Network that emits a Distribution object; and we use a different\n # code path using DistributionSpecV2 for that.\n network_output_spec = actor_network.output_spec\n info_spec = {\n 'dist_params':\n tf.nest.map_structure(lambda spec: spec.input_params_spec,\n network_output_spec)\n }\n else:\n # We have a Network that emits a nest of distributions.\n def nested_dist_params(spec):\n if not isinstance(spec, distribution_utils.DistributionSpecV2):\n raise ValueError(\n 'Unexpected output from `actor_network`. Expected '\n '`Distribution` objects, but saw output spec: {}'\n .format(actor_output_spec))\n return distribution_utils.parameters_to_dict(\n spec.parameters, tensors_only=True)\n\n info_spec = {\n 'dist_params':\n tf.nest.map_structure(nested_dist_params,\n actor_output_spec)\n }\n\n if not self._compute_value_and_advantage_in_train:\n info_spec['value_prediction'] = tensor_spec.TensorSpec(\n shape=[], dtype=tf.float32)\n else:\n info_spec = ()\n\n policy_state_spec = {}\n if actor_network.state_spec:\n policy_state_spec['actor_network_state'] = actor_network.state_spec\n if (collect and value_network.state_spec and\n not self._compute_value_and_advantage_in_train):\n policy_state_spec['value_network_state'] = value_network.state_spec\n if not policy_state_spec:\n policy_state_spec = ()\n\n super(PPOPolicy, self).__init__(\n time_step_spec=time_step_spec,\n action_spec=action_spec,\n policy_state_spec=policy_state_spec,\n info_spec=info_spec,\n actor_network=actor_network,\n observation_normalizer=observation_normalizer,\n clip=clip)\n\n self._collect = collect\n self._value_network = value_network\n\n def get_initial_value_state(self,\n batch_size: types.Int) -> types.NestedTensor:\n \"\"\"Returns the initial state of the value network.\n\n Args:\n batch_size: A constant or Tensor holding the batch size. Can be None, in\n which case the state will not have a batch dimension added.\n\n Returns:\n A nest of zero tensors matching the spec of the value network state.\n \"\"\"\n return tensor_spec.zero_spec_nest(\n self._value_network.state_spec,\n outer_dims=None if batch_size is None else [batch_size])\n\n def apply_value_network(self,\n observations: types.NestedTensor,\n step_types: types.Tensor,\n value_state: Optional[types.NestedTensor] = None,\n training: bool = False) -> types.NestedTensor:\n \"\"\"Apply value network to time_step, potentially a sequence.\n\n If observation_normalizer is not None, applies observation normalization.\n\n Args:\n observations: A (possibly nested) observation tensor with outer_dims\n either (batch_size,) or (batch_size, time_index). If observations is a\n time series and network is RNN, will run RNN steps over time series.\n step_types: A (possibly nested) step_types tensor with same outer_dims as\n observations.\n value_state: Optional. Initial state for the value_network. If not\n provided the behavior depends on the value network itself.\n training: Whether the output value is going to be used for training.\n\n Returns:\n The output of value_net, which is a tuple of:\n - value_preds with same outer_dims as time_step\n - value_state at the end of the time series\n \"\"\"\n if self._observation_normalizer:\n observations = self._observation_normalizer.normalize(observations)\n return self._value_network(observations, step_types, value_state,\n training=training)\n\n def _apply_actor_network(self, time_step, policy_state, training=False):\n observation = time_step.observation\n if self._observation_normalizer:\n observation = self._observation_normalizer.normalize(observation)\n\n return self._actor_network(\n observation,\n time_step.step_type,\n network_state=policy_state,\n training=training)\n\n def _variables(self):\n var_list = self._actor_network.variables[:]\n var_list += self._value_network.variables[:]\n if self._observation_normalizer:\n var_list += self._observation_normalizer.variables\n return var_list\n\n def _distribution(self, time_step, policy_state, training=False):\n if not policy_state:\n policy_state = {'actor_network_state': (), 'value_network_state': ()}\n else:\n policy_state = policy_state.copy()\n\n if 'actor_network_state' not in policy_state:\n policy_state['actor_network_state'] = ()\n if 'value_network_state' not in policy_state:\n policy_state['value_network_state'] = ()\n\n new_policy_state = {'actor_network_state': (), 'value_network_state': ()}\n\n (distributions, new_policy_state['actor_network_state']) = (\n self._apply_actor_network(\n time_step, policy_state['actor_network_state'], training=training))\n\n if self._collect:\n policy_info = {\n 'dist_params': ppo_utils.get_distribution_params(\n distributions,\n legacy_distribution_network=isinstance(\n self._actor_network,\n network.DistributionNetwork))\n }\n\n if not self._compute_value_and_advantage_in_train:\n # If value_prediction is not computed in agent.train it needs to be\n # computed and saved here.\n (policy_info['value_prediction'],\n new_policy_state['value_network_state']) = self.apply_value_network(\n time_step.observation,\n time_step.step_type,\n value_state=policy_state['value_network_state'],\n training=False)\n else:\n policy_info = ()\n\n if (not new_policy_state['actor_network_state'] and\n not new_policy_state['value_network_state']):\n new_policy_state = ()\n elif not new_policy_state['value_network_state']:\n del new_policy_state['value_network_state']\n elif not new_policy_state['actor_network_state']:\n del new_policy_state['actor_network_state']\n\n return policy_step.PolicyStep(distributions, new_policy_state, policy_info)\n" ]
[ [ "numpy.asarray", "numpy.all", "numpy.array", "numpy.zeros", "numpy.where" ], [ "numpy.zeros" ], [ "tensorflow.stack", "tensorflow.cast", "tensorflow.compat.v1.initialize_all_variables", "tensorflow.compat.v1.placeholder_with_default", "tensorflow.SparseTensorSpec", "tensorflow.compat.v1.train.AdamOptimizer", "tensorflow.keras.regularizers.l2", "tensorflow.test.main", "tensorflow.compat.v2.feature_column.categorical_column_with_hash_bucket", "tensorflow.compat.v2.feature_column.weighted_categorical_column", "tensorflow.executing_eagerly", "tensorflow.compat.v2.keras.layers.DenseFeatures", "tensorflow.train.Checkpoint", "tensorflow.keras.layers.Dense", "tensorflow.compat.v2.feature_column.numeric_column", "tensorflow.get_static_value", "tensorflow.math.round", "tensorflow.constant", "tensorflow.compat.v1.global_variables_initializer", "tensorflow.constant_initializer", "tensorflow.compat.v2.feature_column.embedding_column", "tensorflow.nest.map_structure" ], [ "tensorflow.nest.map_structure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Michaeljurado24/nengo
[ "dc0419fbe571374d0a55a7f67309dfcb254a2e88", "dc0419fbe571374d0a55a7f67309dfcb254a2e88", "dc0419fbe571374d0a55a7f67309dfcb254a2e88" ]
[ "nengo/_vendor/scipy/sparse/linalg_interface.py", "nengo/utils/tests/test_least_squares_solvers.py", "nengo/utils/tests/test_nco.py" ]
[ "\"\"\"\nThese are borrowed from SciPy and used under their license:\n\nCopyright (c) 2001, 2002 Enthought, Inc.\nAll rights reserved.\n\nCopyright (c) 2003-2012 SciPy Developers.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n a. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n b. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n c. Neither the name of Enthought nor the names of the SciPy Developers\n may be used to endorse or promote products derived from this software\n without specific prior written permission.\n\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS\nBE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\nOR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\nTHE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n# From scipy/sparse/linalg/interface.py v0.18.0\n\nfrom __future__ import absolute_import, division\n\nimport numpy as np\n\nfrom .sputils import isintlike, isshape\n\n\nclass LinearOperator(object):\n \"\"\"Common interface for performing matrix vector products\n\n Many iterative methods (e.g. cg, gmres) do not need to know the\n individual entries of a matrix to solve a linear system A*x=b.\n Such solvers only require the computation of matrix vector\n products, A*v where v is a dense vector. This class serves as\n an abstract interface between iterative solvers and matrix-like\n objects.\n\n To construct a concrete LinearOperator, either pass appropriate\n callables to the constructor of this class, or subclass it.\n\n A subclass must implement either one of the methods ``_matvec``\n and ``_matmat``, and the attributes/properties ``shape`` (pair of\n integers) and ``dtype`` (may be None). It may call the ``__init__``\n on this class to have these attributes validated. Implementing\n ``_matvec`` automatically implements ``_matmat`` (using a naive\n algorithm) and vice-versa.\n\n Optionally, a subclass may implement ``_rmatvec`` or ``_adjoint``\n to implement the Hermitian adjoint (conjugate transpose). As with\n ``_matvec`` and ``_matmat``, implementing either ``_rmatvec`` or\n ``_adjoint`` implements the other automatically. Implementing\n ``_adjoint`` is preferable; ``_rmatvec`` is mostly there for\n backwards compatibility.\n\n Parameters\n ----------\n shape : tuple\n Matrix dimensions (M,N).\n matvec : callable f(v)\n Returns returns A * v.\n rmatvec : callable f(v)\n Returns A^H * v, where A^H is the conjugate transpose of A.\n matmat : callable f(V)\n Returns A * V, where V is a dense matrix with dimensions (N,K).\n dtype : dtype\n Data type of the matrix.\n\n Attributes\n ----------\n args : tuple\n For linear operators describing products etc. of other linear\n operators, the operands of the binary operation.\n\n See Also\n --------\n aslinearoperator : Construct LinearOperators\n\n Notes\n -----\n The user-defined matvec() function must properly handle the case\n where v has shape (N,) as well as the (N,1) case. The shape of\n the return type is handled internally by LinearOperator.\n\n LinearOperator instances can also be multiplied, added with each\n other and exponentiated, all lazily: the result of these operations\n is always a new, composite LinearOperator, that defers linear\n operations to the original operators and combines the results.\n\n Examples\n --------\n >>> import numpy as np\n >>> from scipy.sparse.linalg import LinearOperator\n >>> def mv(v):\n ... return np.array([2*v[0], 3*v[1]])\n ...\n >>> A = LinearOperator((2,2), matvec=mv)\n >>> A\n <2x2 _CustomLinearOperator with dtype=float64>\n >>> A.matvec(np.ones(2))\n array([ 2., 3.])\n >>> A * np.ones(2)\n array([ 2., 3.])\n\n \"\"\"\n def __new__(cls, *args, **kwargs):\n if cls is LinearOperator:\n # Operate as _CustomLinearOperator factory.\n return _CustomLinearOperator(*args, **kwargs)\n else:\n obj = super(LinearOperator, cls).__new__(cls)\n\n if (type(obj)._matvec == LinearOperator._matvec\n and type(obj)._matmat == LinearOperator._matmat):\n raise TypeError(\"LinearOperator subclass should implement\"\n \" at least one of _matvec and _matmat.\")\n\n return obj\n\n def __init__(self, dtype, shape):\n \"\"\"Initialize this LinearOperator.\n\n To be called by subclasses. ``dtype`` may be None; ``shape`` should\n be convertible to a length-2 tuple.\n \"\"\"\n if dtype is not None:\n dtype = np.dtype(dtype)\n\n shape = tuple(shape)\n if not isshape(shape):\n raise ValueError(\"invalid shape %r (must be 2-d)\" % shape)\n\n self.dtype = dtype\n self.shape = shape\n\n def _init_dtype(self):\n \"\"\"Called from subclasses at the end of the __init__ routine.\n \"\"\"\n if self.dtype is None:\n v = np.zeros(self.shape[-1])\n self.dtype = np.asarray(self.matvec(v)).dtype\n\n def _matmat(self, X):\n \"\"\"Default matrix-matrix multiplication handler.\n\n Falls back on the user-defined _matvec method, so defining that will\n define matrix multiplication (though in a very suboptimal way).\n \"\"\"\n return np.hstack([self.matvec(col.reshape(-1, 1)) for col in X.T])\n\n def _matvec(self, x):\n \"\"\"Default matrix-vector multiplication handler.\n\n If self is a linear operator of shape (M, N), then this method will\n be called on a shape (N,) or (N, 1) ndarray, and should return a\n shape (M,) or (M, 1) ndarray.\n\n This default implementation falls back on _matmat, so defining that\n will define matrix-vector multiplication as well.\n \"\"\"\n return self.matmat(x.reshape(-1, 1))\n\n def matvec(self, x):\n \"\"\"Matrix-vector multiplication.\n\n Performs the operation y=A*x where A is an MxN linear\n operator and x is a column vector or 1-d array.\n\n Parameters\n ----------\n x : {matrix, ndarray}\n An array with shape (N,) or (N,1).\n\n Returns\n -------\n y : {matrix, ndarray}\n A matrix or ndarray with shape (M,) or (M,1) depending\n on the type and shape of the x argument.\n\n Notes\n -----\n This matvec wraps the user-specified matvec routine or overridden\n _matvec method to ensure that y has the correct shape and type.\n\n \"\"\"\n\n x = np.asanyarray(x)\n\n M, N = self.shape\n\n if x.shape != (N,) and x.shape != (N, 1):\n raise ValueError('dimension mismatch')\n\n y = self._matvec(x)\n\n if isinstance(x, np.matrix):\n y = np.asmatrix(y)\n else:\n y = np.asarray(y)\n\n if x.ndim == 1:\n y = y.reshape(M)\n elif x.ndim == 2:\n y = y.reshape(M, 1)\n else:\n raise ValueError('invalid shape returned by user-defined matvec()')\n\n return y\n\n def rmatvec(self, x):\n \"\"\"Adjoint matrix-vector multiplication.\n\n Performs the operation y = A^H * x where A is an MxN linear\n operator and x is a column vector or 1-d array.\n\n Parameters\n ----------\n x : {matrix, ndarray}\n An array with shape (M,) or (M,1).\n\n Returns\n -------\n y : {matrix, ndarray}\n A matrix or ndarray with shape (N,) or (N,1) depending\n on the type and shape of the x argument.\n\n Notes\n -----\n This rmatvec wraps the user-specified rmatvec routine or overridden\n _rmatvec method to ensure that y has the correct shape and type.\n\n \"\"\"\n\n x = np.asanyarray(x)\n\n M, N = self.shape\n\n if x.shape != (M,) and x.shape != (M, 1):\n raise ValueError('dimension mismatch')\n\n y = self._rmatvec(x)\n\n if isinstance(x, np.matrix):\n y = np.asmatrix(y)\n else:\n y = np.asarray(y)\n\n if x.ndim == 1:\n y = y.reshape(N)\n elif x.ndim == 2:\n y = y.reshape(N, 1)\n else:\n raise ValueError('invalid shape returned by user-defined rmatvec()')\n\n return y\n\n def _rmatvec(self, x):\n \"\"\"Default implementation of _rmatvec; defers to adjoint.\"\"\"\n if type(self)._adjoint == LinearOperator._adjoint:\n # _adjoint not overridden, prevent infinite recursion\n raise NotImplementedError\n else:\n return self.H.matvec(x)\n\n def matmat(self, X):\n \"\"\"Matrix-matrix multiplication.\n\n Performs the operation y=A*X where A is an MxN linear\n operator and X dense N*K matrix or ndarray.\n\n Parameters\n ----------\n X : {matrix, ndarray}\n An array with shape (N,K).\n\n Returns\n -------\n Y : {matrix, ndarray}\n A matrix or ndarray with shape (M,K) depending on\n the type of the X argument.\n\n Notes\n -----\n This matmat wraps any user-specified matmat routine or overridden\n _matmat method to ensure that y has the correct type.\n\n \"\"\"\n\n X = np.asanyarray(X)\n\n if X.ndim != 2:\n raise ValueError('expected 2-d ndarray or matrix, not %d-d'\n % X.ndim)\n\n M, N = self.shape\n\n if X.shape[0] != N:\n raise ValueError('dimension mismatch: %r, %r'\n % (self.shape, X.shape))\n\n Y = self._matmat(X)\n\n if isinstance(Y, np.matrix):\n Y = np.asmatrix(Y)\n\n return Y\n\n def __call__(self, x):\n return self*x\n\n def __mul__(self, x):\n return self.dot(x)\n\n def dot(self, x):\n \"\"\"Matrix-matrix or matrix-vector multiplication.\n\n Parameters\n ----------\n x : array_like\n 1-d or 2-d array, representing a vector or matrix.\n\n Returns\n -------\n Ax : array\n 1-d or 2-d array (depending on the shape of x) that represents\n the result of applying this linear operator on x.\n\n \"\"\"\n if isinstance(x, LinearOperator):\n return _ProductLinearOperator(self, x)\n elif np.isscalar(x):\n return _ScaledLinearOperator(self, x)\n else:\n x = np.asarray(x)\n\n if x.ndim == 1 or x.ndim == 2 and x.shape[1] == 1:\n return self.matvec(x)\n elif x.ndim == 2:\n return self.matmat(x)\n else:\n raise ValueError('expected 1-d or 2-d array or matrix, got %r'\n % x)\n\n def __matmul__(self, other):\n if np.isscalar(other):\n raise ValueError(\"Scalar operands are not allowed, \"\n \"use '*' instead\")\n return self.__mul__(other)\n\n def __rmatmul__(self, other):\n if np.isscalar(other):\n raise ValueError(\"Scalar operands are not allowed, \"\n \"use '*' instead\")\n return self.__rmul__(other)\n\n def __rmul__(self, x):\n if np.isscalar(x):\n return _ScaledLinearOperator(self, x)\n else:\n return NotImplemented\n\n def __pow__(self, p):\n if np.isscalar(p):\n return _PowerLinearOperator(self, p)\n else:\n return NotImplemented\n\n def __add__(self, x):\n if isinstance(x, LinearOperator):\n return _SumLinearOperator(self, x)\n else:\n return NotImplemented\n\n def __neg__(self):\n return _ScaledLinearOperator(self, -1)\n\n def __sub__(self, x):\n return self.__add__(-x)\n\n def __repr__(self):\n M, N = self.shape\n if self.dtype is None:\n dt = 'unspecified dtype'\n else:\n dt = 'dtype=' + str(self.dtype)\n\n return '<%dx%d %s with %s>' % (M, N, self.__class__.__name__, dt)\n\n def adjoint(self):\n \"\"\"Hermitian adjoint.\n\n Returns the Hermitian adjoint of self, aka the Hermitian\n conjugate or Hermitian transpose. For a complex matrix, the\n Hermitian adjoint is equal to the conjugate transpose.\n\n Can be abbreviated self.H instead of self.adjoint().\n\n Returns\n -------\n A_H : LinearOperator\n Hermitian adjoint of self.\n \"\"\"\n return self._adjoint()\n\n H = property(adjoint)\n\n def transpose(self):\n \"\"\"Transpose this linear operator.\n\n Returns a LinearOperator that represents the transpose of this one.\n Can be abbreviated self.T instead of self.transpose().\n \"\"\"\n return self._transpose()\n\n T = property(transpose)\n\n def _adjoint(self):\n \"\"\"Default implementation of _adjoint; defers to rmatvec.\"\"\"\n shape = (self.shape[1], self.shape[0])\n return _CustomLinearOperator(shape, matvec=self.rmatvec,\n rmatvec=self.matvec,\n dtype=self.dtype)\n\n\nclass _CustomLinearOperator(LinearOperator):\n \"\"\"Linear operator defined in terms of user-specified operations.\"\"\"\n\n def __init__(self, shape, matvec, rmatvec=None, matmat=None, dtype=None):\n super(_CustomLinearOperator, self).__init__(dtype, shape)\n\n self.args = ()\n\n self.__matvec_impl = matvec\n self.__rmatvec_impl = rmatvec\n self.__matmat_impl = matmat\n\n self._init_dtype()\n\n def _matmat(self, X):\n if self.__matmat_impl is not None:\n return self.__matmat_impl(X)\n else:\n return super(_CustomLinearOperator, self)._matmat(X)\n\n def _matvec(self, x):\n return self.__matvec_impl(x)\n\n def _rmatvec(self, x):\n func = self.__rmatvec_impl\n if func is None:\n raise NotImplemented(\"rmatvec is not defined\")\n return self.__rmatvec_impl(x)\n\n def _adjoint(self):\n return _CustomLinearOperator(shape=(self.shape[1], self.shape[0]),\n matvec=self.__rmatvec_impl,\n rmatvec=self.__matvec_impl,\n dtype=self.dtype)\n\n\ndef _get_dtype(operators, dtypes=None):\n if dtypes is None:\n dtypes = []\n for obj in operators:\n if obj is not None and hasattr(obj, 'dtype'):\n dtypes.append(obj.dtype)\n return np.find_common_type(dtypes, [])\n\n\nclass _SumLinearOperator(LinearOperator):\n def __init__(self, A, B):\n if not isinstance(A, LinearOperator) or \\\n not isinstance(B, LinearOperator):\n raise ValueError('both operands have to be a LinearOperator')\n if A.shape != B.shape:\n raise ValueError('cannot add %r and %r: shape mismatch'\n % (A, B))\n self.args = (A, B)\n super(_SumLinearOperator, self).__init__(_get_dtype([A, B]), A.shape)\n\n def _matvec(self, x):\n return self.args[0].matvec(x) + self.args[1].matvec(x)\n\n def _rmatvec(self, x):\n return self.args[0].rmatvec(x) + self.args[1].rmatvec(x)\n\n def _matmat(self, x):\n return self.args[0].matmat(x) + self.args[1].matmat(x)\n\n def _adjoint(self):\n A, B = self.args\n return A.H + B.H\n\n\nclass _ProductLinearOperator(LinearOperator):\n def __init__(self, A, B):\n if not isinstance(A, LinearOperator) or \\\n not isinstance(B, LinearOperator):\n raise ValueError('both operands have to be a LinearOperator')\n if A.shape[1] != B.shape[0]:\n raise ValueError('cannot multiply %r and %r: shape mismatch'\n % (A, B))\n super(_ProductLinearOperator, self).__init__(_get_dtype([A, B]),\n (A.shape[0], B.shape[1]))\n self.args = (A, B)\n\n def _matvec(self, x):\n return self.args[0].matvec(self.args[1].matvec(x))\n\n def _rmatvec(self, x):\n return self.args[1].rmatvec(self.args[0].rmatvec(x))\n\n def _matmat(self, x):\n return self.args[0].matmat(self.args[1].matmat(x))\n\n def _adjoint(self):\n A, B = self.args\n return B.H * A.H\n\n\nclass _ScaledLinearOperator(LinearOperator):\n def __init__(self, A, alpha):\n if not isinstance(A, LinearOperator):\n raise ValueError('LinearOperator expected as A')\n if not np.isscalar(alpha):\n raise ValueError('scalar expected as alpha')\n dtype = _get_dtype([A], [type(alpha)])\n super(_ScaledLinearOperator, self).__init__(dtype, A.shape)\n self.args = (A, alpha)\n\n def _matvec(self, x):\n return self.args[1] * self.args[0].matvec(x)\n\n def _rmatvec(self, x):\n return np.conj(self.args[1]) * self.args[0].rmatvec(x)\n\n def _matmat(self, x):\n return self.args[1] * self.args[0].matmat(x)\n\n def _adjoint(self):\n A, alpha = self.args\n return A.H * alpha\n\n\nclass _PowerLinearOperator(LinearOperator):\n def __init__(self, A, p):\n if not isinstance(A, LinearOperator):\n raise ValueError('LinearOperator expected as A')\n if A.shape[0] != A.shape[1]:\n raise ValueError('square LinearOperator expected, got %r' % A)\n if not isintlike(p):\n raise ValueError('integer expected as p')\n\n super(_PowerLinearOperator, self).__init__(_get_dtype([A]), A.shape)\n self.args = (A, p)\n\n def _power(self, fun, x):\n res = np.array(x, copy=True)\n for i in range(self.args[1]):\n res = fun(res)\n return res\n\n def _matvec(self, x):\n return self._power(self.args[0].matvec, x)\n\n def _rmatvec(self, x):\n return self._power(self.args[0].rmatvec, x)\n\n def _matmat(self, x):\n return self._power(self.args[0].matmat, x)\n\n def _adjoint(self):\n A, p = self.args\n return A.H ** p\n\n\nclass MatrixLinearOperator(LinearOperator):\n def __init__(self, A):\n super(MatrixLinearOperator, self).__init__(A.dtype, A.shape)\n self.A = A\n self.__adj = None\n self.args = (A,)\n\n def _matmat(self, X):\n return self.A.dot(X)\n\n def _adjoint(self):\n if self.__adj is None:\n self.__adj = _AdjointMatrixOperator(self)\n return self.__adj\n\n\nclass _AdjointMatrixOperator(MatrixLinearOperator):\n def __init__(self, adjoint):\n self.A = adjoint.A.T.conj()\n self.__adjoint = adjoint\n self.args = (adjoint,)\n self.shape = adjoint.shape[1], adjoint.shape[0]\n\n @property\n def dtype(self):\n return self.__adjoint.dtype\n\n def _adjoint(self):\n return self.__adjoint\n\n\nclass IdentityOperator(LinearOperator):\n def __init__(self, shape, dtype=None):\n super(IdentityOperator, self).__init__(dtype, shape)\n\n def _matvec(self, x):\n return x\n\n def _rmatvec(self, x):\n return x\n\n def _matmat(self, x):\n return x\n\n def _adjoint(self):\n return self\n\n\ndef aslinearoperator(A):\n \"\"\"Return A as a LinearOperator.\n\n 'A' may be any of the following types:\n - ndarray\n - matrix\n - sparse matrix (e.g. csr_matrix, lil_matrix, etc.)\n - LinearOperator\n - An object with .shape and .matvec attributes\n\n See the LinearOperator documentation for additional information.\n\n Examples\n --------\n >>> from scipy.sparse.linalg import aslinearoperator\n >>> M = np.array([[1,2,3],[4,5,6]], dtype=np.int32)\n >>> aslinearoperator(M)\n <2x3 MatrixLinearOperator with dtype=int32>\n\n \"\"\"\n if isinstance(A, LinearOperator):\n return A\n\n elif isinstance(A, np.ndarray) or isinstance(A, np.matrix):\n if A.ndim > 2:\n raise ValueError('array must have ndim <= 2')\n A = np.atleast_2d(np.asarray(A))\n return MatrixLinearOperator(A)\n\n else:\n if hasattr(A, 'shape') and hasattr(A, 'matvec'):\n rmatvec = None\n dtype = None\n\n if hasattr(A, 'rmatvec'):\n rmatvec = A.rmatvec\n if hasattr(A, 'dtype'):\n dtype = A.dtype\n return LinearOperator(A.shape, A.matvec,\n rmatvec=rmatvec, dtype=dtype)\n\n else:\n raise TypeError('type not understood')\n", "import numpy as np\nimport pytest\n\nfrom nengo.exceptions import ValidationError\nfrom nengo.utils.least_squares_solvers import (\n SVD,\n BlockConjgrad,\n Cholesky,\n Conjgrad,\n ConjgradScipy,\n LSMRScipy,\n RandomizedSVD,\n)\n\n\ndef run_solver(solver, m=30, n=20, d=1, cond=10, sys_rng=np.random, **kwargs):\n A = sys_rng.uniform(-1, 1, size=(m, n))\n x = sys_rng.uniform(-1, 1, size=(n, d))\n\n # set condition number of system\n assert cond > 1\n U, s, VH = np.linalg.svd(A, full_matrices=False)\n smax, smin = s.max(), s.min()\n new_min = smax / cond\n s = (s - smin) / (smax - smin) * (smax - new_min) + new_min\n A = np.dot(U * s, VH)\n\n # solve system\n y = np.dot(A, x)\n x2, _ = solver(A, y, **kwargs)\n\n return x, x2, A\n\n\[email protected](\"cond, sigma\", [(5, 1e-4), (500, 1e-6), (1e5, 1e-8)])\ndef test_cholesky(cond, sigma, rng, allclose):\n rng = np.random\n solver = Cholesky()\n x, x2, _ = run_solver(solver, d=2, cond=cond, sys_rng=rng, sigma=sigma)\n\n tol = np.sqrt(cond) * 1e-7 # this is a guesstimate, and also depends on sigma\n assert allclose(x2, x, atol=tol, rtol=tol)\n\n\[email protected](\"cond, sigma, tol\", [(5, 1e-4, 1e-2), (50, 1e-5, 1e-4)])\ndef test_conjgrad_scipy(cond, sigma, tol, rng, allclose):\n pytest.importorskip(\"scipy\")\n solver = ConjgradScipy(tol=tol)\n x, x2, _ = run_solver(solver, d=2, cond=cond, sys_rng=rng, sigma=sigma)\n\n tol = cond * tol\n assert allclose(x2, x, atol=tol, rtol=tol)\n\n\[email protected](\"cond, sigma, tol\", [(5, 1e-3, 1e-4), (10, 1e-3, 1e-4)])\ndef test_lsmr_scipy(cond, sigma, tol, rng, allclose):\n pytest.importorskip(\"scipy\")\n solver = LSMRScipy(tol=tol)\n x, x2, _ = run_solver(solver, d=2, cond=cond, sys_rng=rng, sigma=sigma)\n\n tol = cond * tol\n assert allclose(x2, x, atol=tol, rtol=tol)\n\n\[email protected](\n \"cond, sigma, tol, maxiters\",\n [\n (5, 1e-8, 1e-2, None), # standard run\n (50, 1e-8, 1e-4, 100), # precision run (extra iterations help convergence)\n (1.1, 1e-15, 0, 1000), # hit \"no perceptible change in p\" line\n ],\n)\ndef test_conjgrad(cond, sigma, tol, maxiters, rng, allclose):\n solver = Conjgrad(tol=tol, maxiters=maxiters)\n x, x2, A = run_solver(solver, d=2, cond=cond, sys_rng=rng, sigma=sigma)\n\n # conjgrad stopping tol is based on residual in y, so compare y (`y = A.dot(x)`)\n # (this particularly helps in the ill-conditioned case)\n tol = cond * max(tol, 1e-5)\n assert allclose(A.dot(x2), A.dot(x), atol=tol, rtol=tol)\n\n\ndef test_conjgrad_errors():\n solver = Conjgrad(X0=np.ones((1, 1)))\n with pytest.raises(ValidationError, match=r\"Must be shape \\(2, 2\\)\"):\n solver(A=np.ones((2, 2)), Y=np.ones((2, 2)), sigma=0.001)\n\n\[email protected](\"cond, tol\", [(5, 1e-2), (100, 1e-3)])\ndef test_blockconjgrad(cond, tol, rng, allclose):\n x, x2, _ = run_solver(\n BlockConjgrad(tol=tol), d=5, cond=cond, sys_rng=rng, sigma=1e-8\n )\n assert allclose(x2, x, atol=tol, rtol=tol)\n\n\ndef test_blockconjgrad_errors():\n solver = BlockConjgrad(X0=np.ones((1, 1)))\n with pytest.raises(ValidationError, match=r\"Must be shape \\(2, 2\\)\"):\n solver(A=np.ones((2, 2)), Y=np.ones((2, 2)), sigma=0.1)\n\n\[email protected](\"cond\", [5, 1000])\ndef test_svd(cond, rng, allclose):\n x, x2, _ = run_solver(SVD(), d=5, cond=cond, sys_rng=rng, sigma=1e-8)\n assert allclose(x2, x, atol=1e-8, rtol=1e-8)\n\n\[email protected](\"cond\", [5, 1000])\ndef test_randomized_svd_fallback(cond, rng, allclose):\n \"\"\"Test the specific case where RandomizedSVD falls back to SVD\"\"\"\n pytest.importorskip(\"sklearn\")\n m, n = 30, 20\n solver = RandomizedSVD(n_components=min(m, n))\n x, x2, _ = run_solver(solver, m=m, n=n, d=5, cond=cond, sys_rng=rng, sigma=1e-8)\n assert allclose(x2, x, atol=1e-8, rtol=1e-8)\n", "import os\nimport struct\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_equal\n\nfrom nengo.exceptions import CacheIOError\nfrom nengo.utils import nco\nfrom nengo.utils.nco import Subfile\n\n\[email protected](name=\"data\")\ndef fixture_data():\n return \"0123456789\\n123456789\"\n\n\[email protected](name=\"testfile\")\ndef fixture_testfile(data, tmp_path):\n f = tmp_path / \"file.txt\"\n f.write_text(data)\n return f\n\n\ndef write_custom_nco_header(fileobj, magic_string=\"NCO\", version=0):\n magic_string = magic_string.encode(\"utf-8\")\n header_format = f\"@{len(magic_string)}sBLLLL\"\n assert struct.calcsize(header_format) == nco.HEADER_SIZE\n\n header = struct.pack(header_format, magic_string, version, 0, 1, 2, 3)\n fileobj.write(header)\n\n\nclass TestSubfile:\n def test_reads_only_from_start_to_end(self, data, testfile):\n with testfile.open() as f:\n assert Subfile(f, 2, 6).read() == data[2:6]\n with testfile.open() as f:\n assert Subfile(f, 2, 6).read(8) == data[2:6]\n with testfile.open() as f:\n assert Subfile(f, 2, 6).readline() == data[2:6]\n with testfile.open() as f:\n assert Subfile(f, 2, 6).readline(8) == data[2:6]\n\n def test_respects_read_size(self, data, testfile):\n with testfile.open() as f:\n assert Subfile(f, 2, 6).read(2) == data[2:4]\n with testfile.open() as f:\n assert Subfile(f, 2, 6).readline(2) == data[2:4]\n\n def test_readline(self, data, testfile):\n with testfile.open() as f:\n assert Subfile(f, 2, 14).readline() == data[2:11]\n with testfile.open() as f:\n assert Subfile(f, 2, 14).readline(15) == data[2:11]\n\n def test_readinto(self, data, testfile):\n b = bytearray(4)\n with testfile.open(\"rb\") as f:\n assert Subfile(f, 2, 6).readinto(b) == 4\n assert b == b\"2345\"\n\n def test_seek(self, data, testfile):\n with testfile.open() as f:\n sf = Subfile(f, 2, 6)\n sf.seek(2)\n assert sf.read() == data[4:6]\n with testfile.open() as f:\n sf = Subfile(f, 2, 6)\n sf.read(1)\n sf.seek(2, os.SEEK_CUR)\n assert sf.read() == data[5:6]\n with testfile.open() as f:\n sf = Subfile(f, 2, 6)\n sf.seek(-2, os.SEEK_END)\n assert sf.read() == data[4:6]\n\n def test_seek_before_start(self, data, testfile):\n with testfile.open() as f:\n sf = Subfile(f, 2, 6)\n sf.seek(-2)\n assert sf.read() == data[2:6]\n with testfile.open() as f:\n sf = Subfile(f, 2, 6)\n sf.read(1)\n sf.seek(-4, os.SEEK_CUR)\n assert sf.read() == data[2:6]\n with testfile.open() as f:\n sf = Subfile(f, 2, 6)\n sf.seek(-8, os.SEEK_END)\n assert sf.read() == data[2:6]\n\n def test_seek_after_end(self, testfile):\n with testfile.open() as f:\n sf = Subfile(f, 2, 6)\n sf.seek(8)\n assert sf.read() == \"\"\n with testfile.open() as f:\n sf = Subfile(f, 2, 6)\n sf.read(1)\n sf.seek(8, os.SEEK_CUR)\n assert sf.read() == \"\"\n with testfile.open() as f:\n sf = Subfile(f, 2, 6)\n sf.seek(8, os.SEEK_END)\n assert sf.read() == \"\"\n\n def test_tell(self, data, testfile):\n with testfile.open() as f:\n sf = Subfile(f, 2, 6)\n assert sf.tell() == 0\n sf.seek(3)\n assert sf.tell() == 3\n\n def test_read_errors(self, tmp_path):\n # use a bad magic string\n filepath = tmp_path / \"bad_magic_cache_file.txt\"\n with open(filepath, \"wb\") as fh:\n write_custom_nco_header(fh, magic_string=\"BAD\")\n\n with open(filepath, \"rb\") as fh:\n with pytest.raises(CacheIOError, match=\"Not a Nengo cache object file\"):\n nco.read(fh)\n\n # use a bad version number\n filepath = tmp_path / \"bad_version_cache_file.txt\"\n with open(filepath, \"wb\") as fh:\n write_custom_nco_header(fh, version=255)\n\n with open(filepath, \"rb\") as fh:\n with pytest.raises(CacheIOError, match=\"NCO protocol version 255 is\"):\n nco.read(fh)\n\n\ndef test_nco_roundtrip(tmp_path):\n tmpfile = tmp_path / \"test.nco\"\n\n pickle_data = {\"0\": 237, \"str\": \"foobar\"}\n array = np.array([[4, 3], [2, 1]])\n\n with tmpfile.open(\"wb\") as f:\n nco.write(f, pickle_data, array)\n\n with tmpfile.open(\"rb\") as f:\n pickle_data2, array2 = nco.read(f)\n\n assert pickle_data == pickle_data2\n assert_equal(array, array2)\n" ]
[ [ "numpy.conj", "numpy.asarray", "numpy.dtype", "numpy.asmatrix", "numpy.asanyarray", "numpy.isscalar", "numpy.find_common_type", "numpy.array", "numpy.zeros" ], [ "numpy.dot", "numpy.linalg.svd", "numpy.sqrt", "numpy.ones" ], [ "numpy.testing.assert_equal", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ChenFengYe/relightable-nr
[ "239a97406f4df01cf5786dcdde58e464395a682d" ]
[ "tools/train_deform.py" ]
[ "from __future__ import division\nimport os\nimport argparse\nimport glob\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom skimage.io import imread, imsave\nimport tqdm\nimport imageio\n\nimport neural_renderer as nr\n\ncurrent_dir = os.path.dirname(os.path.realpath(__file__))\ndata_dir = os.path.join(current_dir, 'data')\n\nclass Model(nn.Module):\n def __init__(self, filename_obj, filename_ref):\n super(Model, self).__init__()\n\n # load .obj\n vertices, faces = nr.load_obj(filename_obj)\n self.vertices = nn.Parameter(vertices[None, :, :])\n self.register_buffer('faces', faces[None, :, :])\n\n # create textures\n texture_size = 2\n textures = torch.ones(1, self.faces.shape[1], texture_size, texture_size, texture_size, 3, dtype=torch.float32)\n self.register_buffer('textures', textures)\n\n # load reference image\n image_ref = torch.from_numpy(imread(filename_ref).astype(np.float32).mean(-1) / 255.)[None, ::]\n self.register_buffer('image_ref', image_ref)\n\n # setup renderer\n renderer = nr.Renderer(camera_mode='look_at')\n self.renderer = renderer\n\n def forward(self):\n self.renderer.eye = nr.get_points_from_angles(2.732, 0, 90)\n image = self.renderer(self.vertices, self.faces, mode='silhouettes')\n loss = torch.sum((image - self.image_ref[None, :, :])**2)\n return loss\n\n\ndef make_gif(rs_path, savepath):\n with imageio.get_writer(savepath, mode='I') as writer:\n for filename in sorted(glob.glob(rs_path +'/*.png')):\n writer.append_data(imageio.imread(filename))\n # os.remove(filename)\n writer.close()\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-io', '--filename_obj', type=str, default=os.path.join(data_dir, 'teapot.obj'))\n parser.add_argument('-ir', '--filename_ref', type=str, default=os.path.join(data_dir, 'example2_ref.png'))\n parser.add_argument(\n '-oo', '--filename_output_optimization', type=str, default=os.path.join(data_dir, 'example2_optimization.gif'))\n parser.add_argument(\n '-or', '--filename_output_result', type=str, default=os.path.join(data_dir, 'example2_result.gif'))\n parser.add_argument('-g', '--gpu', type=int, default=0)\n args = parser.parse_args()\n\n model = Model(args.filename_obj, args.filename_ref)\n model.cuda()\n\n optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()))\n # optimizer.setup(model)\n loop = tqdm.tqdm(range(300))\n for i in loop:\n loop.set_description('Optimizing')\n # optimizer.target.cleargrads()\n optimizer.zero_grad()\n loss = model()\n loss.backward()\n optimizer.step()\n images = model.renderer(model.vertices, model.faces, mode='silhouettes')\n image = images.detach().cpu().numpy()[0]\n imsave('/tmp/_tmp_%04d.png' % i, image)\n make_gif(args.filename_output_optimization)\n\n # draw object\n loop = tqdm.tqdm(range(0, 360, 4))\n for num, azimuth in enumerate(loop):\n loop.set_description('Drawing')\n model.renderer.eye = nr.get_points_from_angles(2.732, 0, azimuth)\n images, _, _ = model.renderer(model.vertices, model.faces, model.textures)\n image = images.detach().cpu().numpy()[0].transpose((1, 2, 0))\n imsave('/tmp/_tmp_%04d.png' % num, image)\n make_gif(args.filename_output_result)\n\n\nif __name__ == '__main__':\n main()" ]
[ [ "torch.sum", "torch.nn.Parameter", "torch.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
drginm/simple-keras-tensorflow-js-integration
[ "2d3de8196216bea23eec4fb2dde435f70a858329" ]
[ "01-keras/train_model.py" ]
[ "#%% Import libraries\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow.python.client import device_lib\n\nfrom sklearn.model_selection import train_test_split\n\nfrom keras import metrics\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\n\nimport common\n\nprint(tf.__version__)\nprint(device_lib.list_local_devices())\n\n#%% Load dataset\nCSV_PATH = \"./dataset/dataset.csv\"\n\ndf = pd.read_csv(CSV_PATH, index_col=False)\n\nprint(df.head())\nprint(df.columns)\n\nX = df[common.X_colum_names]\nY = df[common.Y_colum_names]\n\nprint(X.head(), Y.head())\n\n#%% Split the dataset into different groups\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=42)\n\nprint('Training set size: ', len(X_train))\nprint(X_train.head(), y_train.head())\n\nprint('Validation set size: ', len(X_test))\nprint(X_test.head(), y_test.head())\n\n#%% Create the model\ndef build_model(x_size, y_size):\n t_model = Sequential()\n t_model.add(Dense(x_size, input_shape=(x_size,)))\n\n t_model.compile(loss='mean_squared_error',\n optimizer='sgd',\n metrics=[metrics.mae])\n return(t_model)\n\nprint(X_train.shape[1], y_train.shape[1])\n\nmodel = build_model(X_train.shape[1], y_train.shape[1])\nmodel.summary()\n\n#%% Configure the training\nepochs = 50\nbatch_size = 32\n\nprint('Epochs: ', epochs)\nprint('Batch size: ', batch_size)\n\nkeras_callbacks = [\n ModelCheckpoint(common.model_checkpoint_file_name,\n monitor='val_mean_absolute_error',\n save_best_only=True,\n verbose=0),\n EarlyStopping(monitor='val_mean_absolute_error', patience=20, verbose=2)\n]\n\n#%% Train the model\nhistory = model.fit(X_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n shuffle=True,\n verbose=2,\n validation_data=(X_test, y_test),\n callbacks=keras_callbacks)\n\nmodel.save(common.model_file_name)\n\ntrain_score = model.evaluate(X_train, y_train, verbose=2)\nvalid_score = model.evaluate(X_test, y_test, verbose=2)\n\nprint('Train MAE: ', round(train_score[1], 4), ', Train Loss: ', round(train_score[0], 4))\nprint('Val MAE: ', round(valid_score[1], 4), ', Val Loss: ', round(valid_score[0], 4))\n\n#%% See training results\nplt.style.use('ggplot')\n\ndef plot_history(history, x_size, y_size):\n print(history.keys()) \n # Prepare plotting\n plt.rcParams[\"figure.figsize\"] = [x_size, y_size]\n fig, axes = plt.subplots(nrows=4, ncols=4, sharex=True)\n\n # summarize history for MAE\n plt.subplot(211)\n plt.plot(history['mean_absolute_error'])\n plt.plot(history['val_mean_absolute_error'])\n plt.title('Training vs Validation MAE')\n plt.ylabel('MAE')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Validation'], loc='upper left')\n\n # summarize history for loss\n plt.subplot(212)\n plt.plot(history['loss'])\n plt.plot(history['val_loss'])\n plt.title('Training vs Validation Loss')\n plt.ylabel('Loss')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Validation'], loc='upper left')\n\n # Plot the results\n plt.draw()\n plt.show()\n\nplot_history(history.history, x_size=8, y_size=12)\n" ]
[ [ "matplotlib.pyplot.legend", "pandas.read_csv", "tensorflow.python.client.device_lib.list_local_devices", "matplotlib.pyplot.title", "matplotlib.pyplot.subplots", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.draw", "matplotlib.pyplot.plot", "matplotlib.pyplot.subplot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.style.use", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] } ]
KarlHammar/High-threshold-QEC-toric-RL
[ "22b14010321ea0e4298aa2640ad7816a7d89f747" ]
[ "src/RL.py" ]
[ "# standard libraries\nimport numpy as np\nimport random\nimport time\nfrom collections import namedtuple, Counter\nimport operator\nimport os\nfrom copy import deepcopy\nimport heapq\n# pytorch\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n# import from other files\nfrom .toric_model import Toric_code\nfrom .toric_model import Action\nfrom .toric_model import Perspective\nfrom .Replay_memory import Replay_memory_uniform, Replay_memory_prioritized\n# import networks \nfrom NN import NN_11, NN_17\nfrom ResNet import ResNet18, ResNet34, ResNet50, ResNet101, ResNet152\nfrom .util import incremental_mean, convert_from_np_to_tensor, Transition\n\n\nclass RL():\n def __init__(self, Network, Network_name, system_size=int, p_error=0.1, replay_memory_capacity=int, learning_rate=0.00025,\n discount_factor=0.95, number_of_actions=3, max_nbr_actions_per_episode=50, device='cpu', replay_memory='uniform'):\n # device\n self.device = device\n # Toric code\n if system_size%2 > 0:\n self.toric = Toric_code(system_size)\n else:\n raise ValueError('Invalid system_size, please use only odd system sizes.')\n self.grid_shift = int(system_size/2)\n self.max_nbr_actions_per_episode = max_nbr_actions_per_episode\n self.system_size = system_size\n self.p_error = p_error\n # Replay Memory\n self.replay_memory_capacity = replay_memory_capacity\n self.replay_memory = replay_memory\n if self.replay_memory == 'proportional':\n self.memory = Replay_memory_prioritized(replay_memory_capacity, 0.6) # alpha\n elif self.replay_memory == 'uniform':\n self.memory = Replay_memory_uniform(replay_memory_capacity)\n else:\n raise ValueError('Invalid memory type, please use only proportional or uniform.')\n # Network\n self.network_name = Network_name\n self.network = Network\n if Network == ResNet18 or Network == ResNet34 or Network == ResNet50 or Network == ResNet101 or Network == ResNet152:\n self.policy_net = self.network()\n else:\n self.policy_net = self.network(system_size, number_of_actions, device)\n self.target_net = deepcopy(self.policy_net)\n self.policy_net = self.policy_net.to(self.device)\n self.target_net = self.target_net.to(self.device)\n self.learning_rate = learning_rate\n # hyperparameters RL\n self.discount_factor = discount_factor\n self.number_of_actions = number_of_actions\n\n\n def save_network(self, PATH):\n torch.save(self.policy_net, PATH)\n\n\n def load_network(self, PATH):\n self.policy_net = torch.load(PATH, map_location='cpu')\n self.target_net = deepcopy(self.policy_net)\n self.policy_net = self.policy_net.to(self.device)\n self.target_net = self.target_net.to(self.device)\n\n\n def experience_replay(self, criterion, optimizer, batch_size):\n self.policy_net.train()\n self.target_net.eval()\n # get transitions and unpack them to minibatch\n transitions, weights, indices = self.memory.sample(batch_size, 0.4) # beta parameter \n mini_batch = Transition(*zip(*transitions))\n # unpack action batch\n batch_actions = Action(*zip(*mini_batch.action))\n batch_actions = np.array(batch_actions.action) - 1\n batch_actions = torch.Tensor(batch_actions).long()\n batch_actions = batch_actions.to(self.device)\n # preprocess batch_input and batch_target_input for the network\n batch_state = self.get_batch_input(mini_batch.state)\n batch_next_state = self.get_batch_input(mini_batch.next_state)\n # preprocess batch_terminal and batch reward\n batch_terminal = convert_from_np_to_tensor(np.array(mini_batch.terminal)) \n batch_terminal = batch_terminal.to(self.device)\n batch_reward = convert_from_np_to_tensor(np.array(mini_batch.reward))\n batch_reward = batch_reward.to(self.device)\n # compute policy net output\n output = self.policy_net(batch_state)\n output = output.gather(1, batch_actions.view(-1, 1)).squeeze(1) \n # compute target network output \n target_output = self.get_target_network_output(batch_next_state, batch_size)\n target_output = target_output.to(self.device)\n y = batch_reward + (batch_terminal * self.discount_factor * target_output)\n # compute loss and update replay memory\n loss = self.get_loss(criterion, optimizer, y, output, weights, indices)\n # backpropagate loss\n loss.backward()\n optimizer.step()\n\n\n def get_loss(self, criterion, optimizer, y, output, weights, indices):\n loss = criterion(y, output)\n optimizer.zero_grad()\n # for prioritized experience replay\n if self.replay_memory == 'proportional':\n loss = convert_from_np_to_tensor(np.array(weights)) * loss.cpu()\n priorities = loss\n priorities = np.absolute(priorities.detach().numpy())\n self.memory.priority_update(indices, priorities)\n return loss.mean()\n\n\n def get_network_output_next_state(self, batch_next_state=float, batch_size=int, action_index=None):\n self.target_net.eval()\n self.policy_net.eval()\n # init matrices\n batch_network_output = np.zeros(batch_size)\n batch_perspectives = np.zeros(shape=(batch_size, 2, self.system_size, self.system_size))\n batch_actions = np.zeros(batch_size)\n for i in range(batch_size):\n if (batch_next_state[i].cpu().sum().item() == 0):\n batch_perspectives[i,:,:,:] = np.zeros(shape=(2, self.system_size, self.system_size))\n else:\n perspectives = self.toric.generate_perspective(self.grid_shift, batch_next_state[i].cpu())\n perspectives = Perspective(*zip(*perspectives))\n perspectives = np.array(perspectives.perspective)\n perspectives = convert_from_np_to_tensor(perspectives)\n perspectives = perspectives.to(self.device)\n # select greedy action \n with torch.no_grad(): \n net_output = self.target_net(perspectives)\n q_values_table = np.array(net_output.cpu())\n row, col = np.where(q_values_table == np.max(q_values_table))\n if action_index[i] == None:\n batch_network_output[i] = q_values_table[row[0], col[0]] \n elif action_index[i] != None:\n action_from_policy_net = int(action_index[i])\n batch_network_output[i] = q_values_table[row[0], action_from_policy_net]\n perspective = perspectives[row[0]]\n perspective = np.array(perspective.cpu())\n batch_perspectives[i,:,:,:] = perspective\n batch_actions[i] = col[0]\n batch_network_output[i] = q_values_table[row[0], col[0]]\n batch_network_output = convert_from_np_to_tensor(batch_network_output)\n batch_perspectives = convert_from_np_to_tensor(batch_perspectives)\n return batch_network_output, batch_perspectives, batch_actions\n\n\n def get_target_network_output(self, batch_next_state, batch_size):\n with torch.no_grad():\n action_index = np.full(shape=(batch_size), fill_value=None)\n target_output,_,_ = self.get_network_output_next_state(batch_next_state=batch_next_state, \n batch_size=batch_size, \n action_index=action_index)\n return target_output\n\n\n def get_batch_input(self, state_batch):\n batch_input = np.stack(state_batch, axis=0)\n batch_input = convert_from_np_to_tensor(batch_input)\n return batch_input.to(self.device)\n\n\n def train(self, training_steps=int, target_update=int, epsilon_start=1.0, num_of_epsilon_steps=10, \n epsilon_end=0.1, reach_final_epsilon=0.5, optimizer=str,\n batch_size=int, replay_start_size=int, minimum_nbr_of_qubit_errors=0):\n # set network to train mode\n self.policy_net.train()\n # define criterion and optimizer\n criterion = nn.MSELoss(reduction='none')\n if optimizer == 'RMSprop':\n optimizer = optim.RMSprop(self.policy_net.parameters(), lr=self.learning_rate)\n elif optimizer == 'Adam': \n optimizer = optim.Adam(self.policy_net.parameters(), lr=self.learning_rate)\n # init counters\n steps_counter = 0\n update_counter = 1\n iteration = 0\n # define epsilon steps \n epsilon = epsilon_start\n num_of_steps = np.round(training_steps/num_of_epsilon_steps)\n epsilon_decay = np.round((epsilon_start-epsilon_end)/num_of_epsilon_steps, 5)\n epsilon_update = num_of_steps * reach_final_epsilon\n # main loop over training steps \n while iteration < training_steps: # include tqdm here?\n num_of_steps_per_episode = 0\n # initialize syndrom\n self.toric = Toric_code(self.system_size)\n terminal_state = 0\n # generate syndroms\n while terminal_state == 0:\n if minimum_nbr_of_qubit_errors == 0:\n self.toric.generate_random_error(self.p_error)\n else:\n self.toric.generate_n_random_errors(minimum_nbr_of_qubit_errors)\n terminal_state = self.toric.terminal_state(self.toric.current_state)\n # solve one episode\n while terminal_state == 1 and num_of_steps_per_episode < self.max_nbr_actions_per_episode and iteration < training_steps:\n num_of_steps_per_episode += 1\n num_of_epsilon_steps += 1\n steps_counter += 1\n iteration += 1\n # select action using epsilon greedy policy\n action = self.select_action(number_of_actions=self.number_of_actions,\n epsilon=epsilon, \n grid_shift=self.grid_shift)\n self.toric.step(action)\n reward = self.get_reward()\n # generate memory entry\n perspective, action_memory, reward, next_perspective, terminal = self.toric.generate_memory_entry(\n action, reward, self.grid_shift) \n # save transition in memory\n self.memory.save(Transition(perspective, action_memory, reward, next_perspective, terminal), 10000) # max priority\n \n # experience replay\n if steps_counter > replay_start_size:\n update_counter += 1\n self.experience_replay(criterion,\n optimizer,\n batch_size)\n # set target_net to policy_net\n if update_counter % target_update == 0:\n self.target_net = deepcopy(self.policy_net)\n # update epsilon\n if (update_counter % epsilon_update == 0):\n epsilon = np.round(np.maximum(epsilon - epsilon_decay, epsilon_end), 3)\n # set next_state to new state and update terminal state\n self.toric.current_state = self.toric.next_state\n terminal_state = self.toric.terminal_state(self.toric.current_state)\n\n\n def get_reward(self):\n terminal = np.all(self.toric.next_state==0)\n if terminal == True:\n reward = 100\n else:\n defects_state = np.sum(self.toric.current_state)\n defects_next_state = np.sum(self.toric.next_state)\n reward = defects_state - defects_next_state\n\n return reward\n\n\n def select_action(self, number_of_actions=int, epsilon=float, grid_shift=int):\n # set network in evluation mode \n self.policy_net.eval()\n # generate perspectives \n perspectives = self.toric.generate_perspective(grid_shift, self.toric.current_state)\n number_of_perspectives = len(perspectives)\n # preprocess batch of perspectives and actions \n perspectives = Perspective(*zip(*perspectives))\n batch_perspectives = np.array(perspectives.perspective)\n batch_perspectives = convert_from_np_to_tensor(batch_perspectives)\n batch_perspectives = batch_perspectives.to(self.device)\n batch_position_actions = perspectives.position\n #choose action using epsilon greedy approach\n rand = random.random()\n if(1 - epsilon > rand):\n # select greedy action \n with torch.no_grad(): \n policy_net_output = self.policy_net(batch_perspectives)\n q_values_table = np.array(policy_net_output.cpu())\n row, col = np.where(q_values_table == np.max(q_values_table))\n perspective = row[0]\n max_q_action = col[0] + 1\n step = Action(batch_position_actions[perspective], max_q_action)\n # select random action\n else:\n random_perspective = random.randint(0, number_of_perspectives-1)\n random_action = random.randint(1, number_of_actions)\n step = Action(batch_position_actions[random_perspective], random_action) \n\n return step\n\n\n def select_action_prediction(self, number_of_actions=int, epsilon=float, grid_shift=int, prev_action=float):\n # set network in eval mode\n self.policy_net.eval()\n # generate perspectives\n perspectives = self.toric.generate_perspective(grid_shift, self.toric.current_state)\n number_of_perspectives = len(perspectives)\n # preprocess batch of perspectives and actions \n perspectives = Perspective(*zip(*perspectives))\n batch_perspectives = np.array(perspectives.perspective)\n batch_perspectives = convert_from_np_to_tensor(batch_perspectives)\n batch_perspectives = batch_perspectives.to(self.device)\n batch_position_actions = perspectives.position\n # generate action value for different perspectives \n with torch.no_grad():\n policy_net_output = self.policy_net(batch_perspectives)\n q_values_table = np.array(policy_net_output.cpu())\n #choose action using epsilon greedy approach\n rand = random.random()\n if(1 - epsilon > rand):\n # select greedy action \n row, col = np.where(q_values_table == np.max(q_values_table))\n perspective = row[0]\n max_q_action = col[0] + 1\n step = Action(batch_position_actions[perspective], max_q_action)\n if prev_action == step:\n res = heapq.nlargest(2, q_values_table.flatten())\n row, col = np.where(q_values_table == res[1])\n perspective = row[0]\n max_q_action = col[0] + 1\n step = Action(batch_position_actions[perspective], max_q_action)\n q_value = q_values_table[row[0], col[0]]\n # select random action\n else:\n random_perspective = random.randint(0, number_of_perspectives-1)\n random_action = random.randint(1, number_of_actions)\n q_value = q_values_table[random_perspective, random_action-1]\n step = Action(batch_position_actions[random_perspective], random_action)\n\n return step, q_value\n\n\n def prediction(self, num_of_predictions=1, epsilon=0.0, num_of_steps=50, PATH=None, plot_one_episode=False, \n show_network=False, show_plot=False, prediction_list_p_error=float, minimum_nbr_of_qubit_errors=0, print_Q_values=False, save_prediction=True):\n # load network for prediction and set eval mode \n if PATH != None:\n self.load_network(PATH)\n self.policy_net.eval()\n # init matrices \n ground_state_list = np.zeros(len(prediction_list_p_error))\n error_corrected_list = np.zeros(len(prediction_list_p_error))\n average_number_of_steps_list = np.zeros(len(prediction_list_p_error))\n mean_q_list = np.zeros(len(prediction_list_p_error))\n failed_syndroms = []\n failure_rate = 0\n # loop through different p_error\n for i, p_error in enumerate(prediction_list_p_error):\n ground_state = np.ones(num_of_predictions, dtype=bool)\n error_corrected = np.zeros(num_of_predictions)\n mean_steps_per_p_error = 0\n mean_q_per_p_error = 0\n steps_counter = 0\n for j in range(num_of_predictions):\n num_of_steps_per_episode = 0\n prev_action = 0\n terminal_state = 0\n # generate random syndrom\n self.toric = Toric_code(self.system_size)\n\n if minimum_nbr_of_qubit_errors == 0:\n self.toric.generate_random_error(p_error)\n else:\n self.toric.generate_n_random_errors(minimum_nbr_of_qubit_errors)\n terminal_state = self.toric.terminal_state(self.toric.current_state)\n # plot one episode\n if plot_one_episode == True and j == 0 and i == 0:\n self.toric.plot_toric_code(self.toric.current_state, 'initial_syndrom')\n \n init_qubit_state = deepcopy(self.toric.qubit_matrix)\n # solve syndrome\n while terminal_state == 1 and num_of_steps_per_episode < num_of_steps:\n steps_counter += 1\n num_of_steps_per_episode += 1\n # choose greedy action\n action, q_value = self.select_action_prediction(number_of_actions=self.number_of_actions, \n epsilon=epsilon,\n grid_shift=self.grid_shift,\n prev_action=prev_action)\n prev_action = action\n self.toric.step(action)\n self.toric.current_state = self.toric.next_state\n terminal_state = self.toric.terminal_state(self.toric.current_state)\n mean_q_per_p_error = incremental_mean(q_value, mean_q_per_p_error, steps_counter)\n \n if plot_one_episode == True and j == 0 and i == 0:\n self.toric.plot_toric_code(self.toric.current_state, 'step_'+str(num_of_steps_per_episode))\n\n # compute mean steps \n mean_steps_per_p_error = incremental_mean(num_of_steps_per_episode, mean_steps_per_p_error, j+1)\n # save error corrected \n error_corrected[j] = self.toric.terminal_state(self.toric.current_state) # 0: error corrected # 1: error not corrected \n # update groundstate\n self.toric.eval_ground_state() \n ground_state[j] = self.toric.ground_state # False non trivial loops\n\n if terminal_state == 1 or self.toric.ground_state == False:\n failed_syndroms.append(init_qubit_state)\n failed_syndroms.append(self.toric.qubit_matrix)\n\n success_rate = (num_of_predictions - np.sum(error_corrected)) / num_of_predictions\n error_corrected_list[i] = success_rate\n ground_state_change = (num_of_predictions - np.sum(ground_state)) / num_of_predictions\n ground_state_list[i] = 1 - ground_state_change\n average_number_of_steps_list[i] = np.round(mean_steps_per_p_error, 1)\n mean_q_list[i] = np.round(mean_q_per_p_error, 3)\n\n return error_corrected_list, ground_state_list, average_number_of_steps_list, mean_q_list, failed_syndroms, ground_state_list, prediction_list_p_error, failure_rate\n\n\n def train_for_n_epochs(self, training_steps=int, epochs=int, num_of_predictions=100, num_of_steps_prediction=50, target_update=100, \n optimizer=str, save=True, directory_path='network', prediction_list_p_error=[0.1],\n batch_size=32, replay_start_size=32, minimum_nbr_of_qubit_errors=0):\n \n data_all = []\n data_all = np.zeros((1, 19))\n\n for i in range(epochs):\n self.train(training_steps=training_steps,\n target_update=target_update,\n optimizer=optimizer,\n batch_size=batch_size,\n replay_start_size=replay_start_size,\n minimum_nbr_of_qubit_errors=minimum_nbr_of_qubit_errors)\n print('training done, epoch: ', i+1)\n # evaluate network\n error_corrected_list, ground_state_list, average_number_of_steps_list, mean_q_list, failed_syndroms, ground_state_list, prediction_list_p_error, failure_rate = self.prediction(num_of_predictions=num_of_predictions, \n prediction_list_p_error=prediction_list_p_error, \n minimum_nbr_of_qubit_errors=0,#int(self.system_size/2)+1, # why is this not taken from args? evaluation bad?\n save_prediction=True,\n num_of_steps=num_of_steps_prediction)\n # Print evaluation lists after each epoch\n print(error_corrected_list, 'error corrected')\n print(ground_state_list, 'ground state conserved')\n print(average_number_of_steps_list, 'average number of steps')\n print(mean_q_list, 'mean q value')\n\n data_all = np.append(data_all, np.array([[self.system_size, self.network_name, i+1, self.replay_memory, self.device, self.learning_rate, target_update, optimizer,\n self.discount_factor, training_steps * (i+1), mean_q_list[0], prediction_list_p_error[0], num_of_predictions, len(failed_syndroms)/2, error_corrected_list[0], ground_state_list[0], average_number_of_steps_list[0],failure_rate, self.p_error]]), axis=0)\n # save training settings in txt file \n np.savetxt(directory_path + '/data_all.txt', data_all, \n header='system_size, network_name, epoch, replay_memory, device, learning_rate, target_update, optimizer, discount_factor, total_training_steps, mean_q_list, prediction_list_p_error, number_of_predictions, number_of_failed_syndroms, error_corrected_list, ground_state_list, average_number_of_steps_list, failure_rate, p_error_train', delimiter=',', fmt=\"%s\")\n # save network\n step = (i + 1) * training_steps\n PATH = directory_path + '/network_epoch/size_{3}_{2}_epoch_{0}_memory_{7}_target_update_{5}_optimizer_{6}__steps_{4}_q_{1}_discount_{8}_learning_rate_{9}.pt'.format(\n i+1, np.round(mean_q_list[0], 4), self.network_name, self.system_size, step, target_update, optimizer, self.replay_memory, self.discount_factor, self.learning_rate)\n self.save_network(PATH)\n \n return error_corrected_list\n" ]
[ [ "numpy.sum", "numpy.maximum", "torch.Tensor", "torch.load", "numpy.stack", "numpy.full", "numpy.round", "numpy.all", "numpy.ones", "numpy.max", "torch.no_grad", "numpy.where", "numpy.savetxt", "numpy.array", "numpy.zeros", "torch.nn.MSELoss", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jasp9559/Plastic-Sales-Forecasting-with-Pyhton-and-R
[ "25b002f83d015700492f5fa7bcc295fcc89ecdc9" ]
[ "Plastic_Sales_Py.py" ]
[ "import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom statsmodels.tsa.seasonal import seasonal_decompose\r\nfrom statsmodels.tsa.holtwinters import SimpleExpSmoothing # SES\r\nfrom statsmodels.tsa.holtwinters import Holt # Holts Exponential Smoothing\r\nfrom statsmodels.tsa.holtwinters import ExponentialSmoothing # \r\n# from datetime import datetime\r\n\r\nplastic = pd.read_csv(\"C:/Data Science/Data Science/Assignments/Ass24. Forecasting/Plastic/PlasticSales_raw.csv\")\r\n\r\nplastic.Sales.plot() # time series plot \r\n\r\n# Centering moving average for the time series\r\nplastic.Sales.plot(label = \"org\")\r\nfor i in range(2, 9, 2):\r\n plastic[\"Sales\"].rolling(i).mean().plot(label = str(i))\r\nplt.legend(loc = 3)\r\n \r\n# Time series decomposition plot \r\ndecompose_ts_add = seasonal_decompose(plastic.Sales, model = \"additive\", period = 12)\r\ndecompose_ts_add.plot()\r\ndecompose_ts_mul = seasonal_decompose(plastic.Sales, model = \"multiplicative\", period = 12)\r\ndecompose_ts_mul.plot()\r\n\r\n\r\n# splitting the data into Train and Test data\r\n# Recent 12 time period values are Test data\r\n\r\nTrain = plastic.head(48)\r\nTest = plastic.tail(12)\r\n\r\n# Data Driven approach\r\n# Creating a function to calculate the MAPE value for test data \r\ndef MAPE(pred,org):\r\n temp = np.abs((pred-org)/org)*100\r\n return np.mean(temp)\r\n\r\n# Simple Exponential Method\r\nses_model = SimpleExpSmoothing(Train[\"Sales\"]).fit()\r\npred_ses = ses_model.predict(start = Test.index[0], end = Test.index[-1])\r\nMAPE(pred_ses, Test.Sales) \r\n\r\n# Holt method \r\nhw_model = Holt(Train[\"Sales\"]).fit()\r\npred_hw = hw_model.predict(start = Test.index[0], end = Test.index[-1])\r\nMAPE(pred_hw, Test.Sales) \r\n\r\n# Holts winter exponential smoothing with additive seasonality and additive trend\r\nhwe_model_add_add = ExponentialSmoothing(Train[\"Sales\"], seasonal = \"add\", trend = \"add\", seasonal_periods = 12).fit()\r\npred_hwe_add_add = hwe_model_add_add.predict(start = Test.index[0], end = Test.index[-1])\r\nMAPE(pred_hwe_add_add, Test.Sales) \r\n\r\n# Holts winter exponential smoothing with multiplicative seasonality and additive trend\r\nhwe_model_mul_add = ExponentialSmoothing(Train[\"Sales\"], seasonal = \"mul\", trend = \"add\", seasonal_periods = 12).fit()\r\npred_hwe_mul_add = hwe_model_mul_add.predict(start = Test.index[0], end = Test.index[-1])\r\nMAPE(pred_hwe_mul_add, Test.Sales) \r\n\r\n\r\n# Final Model on 100% Data\r\nhwe_model_add_add = ExponentialSmoothing(plastic[\"Sales\"], seasonal = \"add\", trend = \"add\", seasonal_periods = 12).fit()\r\n\r\n# Load the new data which includes the entry for future 12 values\r\nnew_data = pd.read_csv(\"C:/Data Science/Data Science/Assignments/Ass24. Forecasting/Plastic/New_PlasticSales.csv\")\r\n\r\nnewdata_pred = hwe_model_add_add.predict(start = new_data.index[0], end = new_data.index[-1])\r\nnewdata_pred\r\n\r\n#########################################################\r\n##################################################\r\n#####################################\r\n#Model Based approach\r\n\r\nimport pandas as pd\r\nPlastic = pd.read_csv(\"C:/Data Science/Data Science/Assignments/Ass24. Forecasting/Plastic/PlasticSales_raw.csv\")\r\nmonth = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] \r\n\r\n# Pre processing\r\nimport numpy as np\r\n\r\nPlastic[\"t\"] = np.arange(0, 60)\r\n\r\nPlastic[\"t_square\"] = Plastic[\"t\"]*Plastic[\"t\"]\r\nPlastic[\"log_Sales\"] = np.log(Plastic[\"Sales\"])\r\nPlastic.columns\r\n\r\n\r\np = Plastic[\"Month\"][0]\r\n\r\np[0:3]\r\n\r\nPlastic['months']= 0\r\n\r\nfor i in range(59):\r\n p = Plastic[\"Month\"][i]\r\n Plastic['months'][i]= p[0:3]\r\n \r\nmonth_dummies = pd.DataFrame(pd.get_dummies(Plastic['months']))\r\nPlastic1 = pd.concat([Plastic, month_dummies], axis = 1)\r\n\r\n# Visualization - Time plot\r\nPlastic1.Sales.plot()\r\n\r\n# Data Partition\r\nTrain = Plastic1.head(48)\r\nTest = Plastic1.tail(12)\r\n\r\n# to change the index value in pandas data frame \r\n# Test.set_index(np.arange(1,13))\r\n\r\n####################### L I N E A R ##########################\r\nimport statsmodels.formula.api as smf \r\n\r\nlinear_model = smf.ols('Sales ~ t', data=Train).fit()\r\npred_linear = pd.Series(linear_model.predict(pd.DataFrame(Test['t'])))\r\nrmse_linear = np.sqrt(np.mean((np.array(Test['Sales']) - np.array(pred_linear))**2))\r\nrmse_linear\r\n\r\n##################### Exponential ##############################\r\n\r\nExp = smf.ols('log_Sales ~ t', data = Train).fit()\r\npred_Exp = pd.Series(Exp.predict(pd.DataFrame(Test['t'])))\r\nrmse_Exp = np.sqrt(np.mean((np.array(Test['Sales']) - np.array(np.exp(pred_Exp)))**2))\r\nrmse_Exp\r\n\r\n#################### Quadratic ###############################\r\n\r\nQuad = smf.ols('Sales ~ t+t_square', data=Train).fit()\r\npred_Quad = pd.Series(Quad.predict(Test[[\"t\",\"t_square\"]]))\r\nrmse_Quad = np.sqrt(np.mean((np.array(Test['Sales'])-np.array(pred_Quad))**2))\r\nrmse_Quad\r\n\r\n################### Additive seasonality ########################\r\n\r\nadd_sea = smf.ols('Sales ~ Jan+Feb+Mar+Apr+May+Jun+Jul+Aug+Sep+Oct+Nov', data=Train).fit()\r\npred_add_sea = pd.Series(add_sea.predict(Test[['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov']]))\r\nrmse_add_sea = np.sqrt(np.mean((np.array(Test['Sales'])-np.array(pred_add_sea))**2))\r\nrmse_add_sea\r\n\r\n################## Multiplicative Seasonality ##################\r\n\r\nMul_sea = smf.ols('log_Sales ~ Jan+Feb+Mar+Apr+May+Jun+Jul+Aug+Sep+Oct+Nov',data = Train).fit()\r\npred_Mult_sea = pd.Series(Mul_sea.predict(Test[['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov']]))\r\nrmse_Mult_sea = np.sqrt(np.mean((np.array(Test['Sales']) - np.array(np.exp(pred_Mult_sea)))**2))\r\nrmse_Mult_sea\r\n\r\n################### Additive seasonality with linear trend ########################\r\n\r\nlin_add_sea = smf.ols('Sales ~ t+Jan+Feb+Mar+Apr+May+Jun+Jul+Aug+Sep+Oct+Nov', data=Train).fit()\r\npred_lin_add_sea = pd.Series(lin_add_sea.predict(Test[['t','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov']]))\r\nrmse_lin_add_sea = np.sqrt(np.mean((np.array(Test['Sales'])-np.array(pred_lin_add_sea))**2))\r\nrmse_lin_add_sea\r\n\r\n\r\n################## Additive Seasonality Quadratic Trend ############################\r\n\r\nadd_sea_Quad = smf.ols('Sales ~ t+t_square+Jan+Feb+Mar+Apr+May+Jun+Jul+Aug+Sep+Oct+Nov',data=Train).fit()\r\npred_add_sea_quad = pd.Series(add_sea_Quad.predict(Test[['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','t','t_square']]))\r\nrmse_add_sea_quad = np.sqrt(np.mean((np.array(Test['Sales'])-np.array(pred_add_sea_quad))**2))\r\nrmse_add_sea_quad \r\n\r\n################## Multiplicative Seasonality Linear Trend ###########\r\n\r\nMul_Add_sea = smf.ols('log_Sales ~ t+Jan+Feb+Mar+Apr+May+Jun+Jul+Aug+Sep+Oct+Nov',data = Train).fit()\r\npred_Mult_add_sea = pd.Series(Mul_Add_sea.predict(Test[['t','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov']]))\r\nrmse_Mult_add_sea = np.sqrt(np.mean((np.array(Test['Sales'])-np.array(np.exp(pred_Mult_add_sea)))**2))\r\nrmse_Mult_add_sea \r\n\r\n################## Multiplicative Seasonality Linear Trend ###########\r\n\r\nMul_Add_sea_Quad = smf.ols('log_Sales ~ t+t_square+Jan+Feb+Mar+Apr+May+Jun+Jul+Aug+Sep+Oct+Nov',data = Train).fit()\r\npred_Mult_add_sea_Quad = pd.Series(Mul_Add_sea_Quad.predict(Test[['t','t_square','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov']]))\r\nrmse_Mult_add_sea_Quad = np.sqrt(np.mean((np.array(Test['Sales'])-np.array(np.exp(pred_Mult_add_sea_Quad)))**2))\r\nrmse_Mult_add_sea_Quad\r\n\r\n\r\n################## Testing #######################################\r\n\r\ndata = {\"MODEL\":pd.Series([\"rmse_linear\",\"rmse_Exp\",\"rmse_Quad\",\"rmse_add_sea\",\"rmse_lin_add_sea\",\"rmse_add_sea_quad\",\"rmse_Mult_sea\",\"rmse_Mult_add_sea\",\"rmse_Mult_add_sea_Quad\"]),\"RMSE_Values\":pd.Series([rmse_linear,rmse_Exp,rmse_Quad,rmse_add_sea,rmse_lin_add_sea,rmse_add_sea_quad,rmse_Mult_sea,rmse_Mult_add_sea,rmse_Mult_add_sea_Quad])}\r\ntable_rmse=pd.DataFrame(data)\r\ntable_rmse\r\n\r\n# 'rmse_Mult_add_sea' has the least value among the models prepared so far Predicting new values \r\npredict_data1 = pd.read_csv(\"C:/Data Science/Data Science/Assignments/Ass24. Forecasting/Plastic/PlasticSales_pred.csv\")\r\n\r\nmodel_full = smf.ols('Sales ~ t+Jan+Feb+Mar+Apr+May+Jun+Jul+Aug+Sep+Oct+Nov', data = Plastic1).fit()\r\n\r\npred_new = pd.Series(model_full.predict(predict_data1))\r\npred_new\r\n\r\npredict_data1[\"forecasted_Sales\"] = pd.Series(pred_new)\r\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.log", "pandas.read_csv", "pandas.concat", "pandas.Series", "numpy.abs", "numpy.arange", "pandas.DataFrame", "numpy.mean", "numpy.exp", "numpy.array", "pandas.get_dummies" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
kwrobert/qualipy
[ "a514e8d2e7d3b24d111556a1af91689ace36af9a" ]
[ "qualipy/utils/image_utils.py" ]
[ "\"\"\"Various utility functions for dealing with images, such as\nreading images as numpy arrays, resizing images or making them sharper.\"\"\"\n\nimport os.path\n\nimport cv2\nimport numpy\nimport exifread\n\nfrom .utils import file_cache\n\n\n@file_cache\ndef read_image(image_path, ROI=None):\n \"\"\"Read an image from a file in grayscale\n\n :param image_path: path to the image file\n :type image_path: str\n :returns: numpy.ndarray\n \"\"\"\n image = read_color_image(image_path, ROI)\n return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n\n@file_cache\ndef read_color_image(image_path, ROI=None):\n \"\"\"Read an image from a file in BGR format\n\n :param image_path: path to the image file\n :type image_path: str\n :returns: numpy.ndarray\n \"\"\"\n if not (isinstance(image_path, str) or\n isinstance(image_path, str)):\n raise TypeError(\"image_path should be a string, not %s\" %\n type(image_path))\n\n if not os.path.isfile(image_path):\n raise IOError(\"Image not found: %s\" % image_path)\n\n image = cv2.imread(image_path)\n if image is None:\n raise IOError(\"Unable to read image: %s\" % image_path)\n\n return extract_ROI(image_path, image, ROI)\n\n\ndef extract_ROI(image_path, image, ROI):\n \"\"\"Extract the region of interest out of an image\n\n :param image_path: path to the image file\n :type image_path: str\n :param image: the image matrix\n :type image: numpy.ndarray\n :returns: numpy.ndarray -- the region of interest\n \"\"\"\n if ROI is None:\n return image\n\n if len(ROI) != 4:\n raise TypeError(\"ROI needs to be of length 4\")\n\n x, y, w, h = ROI\n height, width, _ = image.shape\n\n if x < 0 or y < 0 or x + w > width or y + h > height:\n raise ValueError(\"Invalid dimensions for ROI for image: %s\"\n % image_path)\n\n return image[x:x + w, y:y + h]\n\n\ndef resize(image, size):\n \"\"\"Resizes an image matrix so that the longest side\n of an image is the specified size at maximum.\n\n :param image: the image matrix\n :type image: numpy.ndarray\n :param size: the maximum size for one side of the image\n :type size: int\n :returns: numpy.ndarray\n \"\"\"\n height, width = image.shape\n\n if max(height, width) <= size:\n return image\n\n ratio = max(height, width) / float(size)\n height /= ratio\n width /= ratio\n return cv2.resize(image, (int(height), int(width)))\n\n\ndef read_exif_tags(image_path):\n \"\"\"Parses the EXIF tags from an image.\n\n :param image_path: path to the image file\n :type image_path: str\n :returns: dict -- the exif tags\n \"\"\"\n with open(image_path, 'rb') as image:\n return exifread.process_file(image, details=False)\n\n\ndef reduce_colors(image, colors):\n \"\"\"Reduces the number of colors in a given image to certain\n amount. The algorithm uses the k-nearest neighbors method to\n do this. The given image must have colors, meaning three color\n channels. The algorithm is taken from\n \"http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_ml/py_kmeans\n /py_kmeans_opencv/py_kmeans_opencv.html\"\n\n :param image: the image to process (must have three channels)\n :type image: numpy.ndarray\n :param colors: how many colors the final image should have\n :type colors: int\n :returns: numpy.ndarray\n \"\"\"\n Z = image.reshape((-1, 3)).astype(numpy.float32)\n\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)\n ret, label, center = cv2.kmeans(data=Z, K=colors, criteria=criteria,\n attempts=10, flags=cv2.KMEANS_PP_CENTERS,\n bestLabels=None)\n\n center = numpy.uint8(center)\n return center[label.flatten()].reshape(image.shape)\n\n\ndef sharpen(image):\n \"\"\"Sharpens an image.\n\n :param image: the image matrix\n :type image: numpy.ndarray\n :returns: numpy.ndarray\n \"\"\"\n blur = cv2.GaussianBlur(image, (5, 5), 0)\n return cv2.addWeighted(image, 1.5, blur, -0.5, 0)\n\n\ndef logarithmic_transformation2D(array_2D):\n \"\"\"Performs a logarithmic transformation of a matrix.\n\n :param array_2D: a numpy matrix\n :type array_2D: numpy.ndarray\n :returns: numpy.ndarray\n \"\"\"\n c = 1 / numpy.log(1 + numpy.abs(numpy.amax(array_2D)))\n return c * numpy.log(1 + numpy.abs(array_2D))\n\n\ndef count_magnitude_spectrum(image):\n \"\"\"Returns the magnitude spectrum of an image.\n\n :param image: the image matrix\n :type image: numpy.ndarray\n :returns: numpy.ndarray\n \"\"\"\n fft = numpy.fft.fft2(image)\n fshift = numpy.fft.fftshift(fft)\n return logarithmic_transformation2D(fshift)\n" ]
[ [ "numpy.fft.fft2", "numpy.amax", "numpy.abs", "numpy.uint8", "numpy.fft.fftshift" ] ]
[ { "matplotlib": [], "numpy": [ "1.6", "1.10", "1.12", "1.11", "1.19", "1.13", "1.16", "1.9", "1.18", "1.21", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
dannerph/pyswarms
[ "eb84d8079fa936f49a4369010fd94f91688ddbe4" ]
[ "pyswarms/utils/plotters/plotters.py" ]
[ "# -*- coding: utf-8 -*-\n\n\"\"\"\nPlotting tool for Optimizer Analysis\n\nThis module is built on top of :code:`matplotlib` to render quick and easy\nplots for your optimizer. It can plot the best cost for each iteration, and\nshow animations of the particles in 2-D and 3-D space. Furthermore, because\nit has :code:`matplotlib` running under the hood, the plots are easily\ncustomizable.\n\nFor example, if we want to plot the cost, simply run the optimizer, get the\ncost history from the optimizer instance, and pass it to the\n:code:`plot_cost_history()` method\n\n.. code-block:: python\n\n import pyswarms as ps\n from pyswarms.utils.functions.single_obj import sphere\n from pyswarms.utils.plotters import plot_cost_history\n\n # Set up optimizer\n options = {'c1':0.5, 'c2':0.3, 'w':0.9}\n optimizer = ps.single.GlobalBestPSO(n_particles=10, dimensions=2,\n options=options)\n\n # Obtain cost history from optimizer instance\n cost_history = optimizer.cost_history\n\n # Plot!\n plot_cost_history(cost_history)\n plt.show()\n\nIn case you want to plot the particle movement, it is important that either\none of the :code:`matplotlib` animation :code:`Writers` is installed. These\ndoesn't come out of the box for :code:`pyswarms`, and must be installed\nseparately. For example, in a Linux or Windows distribution, you can install\n:code:`ffmpeg` as\n\n >>> conda install -c conda-forge ffmpeg\n\nNow, if you want to plot your particles in a 2-D environment, simply pass\nthe position history of your swarm (obtainable from swarm instance):\n\n\n.. code-block:: python\n\n import pyswarms as ps\n from pyswarms.utils.functions.single_obj import sphere\n from pyswarms.utils.plotters import plot_cost_history\n\n # Set up optimizer\n options = {'c1':0.5, 'c2':0.3, 'w':0.9}\n optimizer = ps.single.GlobalBestPSO(n_particles=10, dimensions=2,\n options=options)\n\n # Obtain pos history from optimizer instance\n pos_history = optimizer.pos_history\n\n # Plot!\n plot_contour(pos_history)\n\nYou can also supply various arguments in this method: the indices of the\nspecific dimensions to be used, the limits of the axes, and the interval/\nspeed of animation.\n\"\"\"\n\n# Import standard library\nimport logging\n\n# Import modules\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport multiprocessing as mp\nfrom matplotlib import animation, cm\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfrom ..reporter import Reporter\nfrom .formatters import Animator, Designer\n\nrep = Reporter(logger=logging.getLogger(__name__))\n\n\ndef plot_cost_history(\n cost_history, ax=None, title=\"Cost History\", designer=None, **kwargs\n):\n \"\"\"Create a simple line plot with the cost in the y-axis and\n the iteration at the x-axis\n\n Parameters\n ----------\n cost_history : array_like\n Cost history of shape :code:`(iters, )` or length :code:`iters` where\n each element contains the cost for the given iteration.\n ax : :obj:`matplotlib.axes.Axes`, optional\n The axes where the plot is to be drawn. If :code:`None` is\n passed, then the plot will be drawn to a new set of axes.\n title : str, optional\n The title of the plotted graph. Default is `Cost History`\n designer : :obj:`pyswarms.utils.formatters.Designer`, optional\n Designer class for custom attributes\n **kwargs : dict\n Keyword arguments that are passed as a keyword argument to\n :class:`matplotlib.axes.Axes`\n\n Returns\n -------\n :obj:`matplotlib.axes._subplots.AxesSubplot`\n The axes on which the plot was drawn.\n \"\"\"\n try:\n # Infer number of iterations based on the length\n # of the passed array\n iters = len(cost_history)\n\n # If no Designer class supplied, use defaults\n if designer is None:\n designer = Designer(legend=\"Cost\", label=[\"Iterations\", \"Cost\"])\n\n # If no ax supplied, create new instance\n if ax is None:\n _, ax = plt.subplots(1, 1, figsize=designer.figsize)\n\n # Plot with iters in x-axis and the cost in y-axis\n ax.plot(\n np.arange(iters), cost_history, \"k\", lw=2, label=designer.legend\n )\n\n # Customize plot depending on parameters\n ax.set_title(title, fontsize=designer.title_fontsize)\n ax.legend(fontsize=designer.text_fontsize)\n ax.set_xlabel(designer.label[0], fontsize=designer.text_fontsize)\n ax.set_ylabel(designer.label[1], fontsize=designer.text_fontsize)\n ax.tick_params(labelsize=designer.text_fontsize)\n except TypeError:\n rep.logger.exception(\"Please check your input type\")\n raise\n else:\n return ax\n\n\ndef plot_contour(\n pos_history,\n canvas=None,\n title=\"Trajectory\",\n mark=None,\n designer=None,\n mesher=None,\n animator=None,\n n_processes=None,\n **kwargs\n):\n \"\"\"Draw a 2D contour map for particle trajectories\n\n Here, the space is represented as a flat plane. The contours indicate the\n elevation with respect to the objective function. This works best with\n 2-dimensional swarms with their fitness in z-space.\n\n Parameters\n ----------\n pos_history : numpy.ndarray or list\n Position history of the swarm with shape\n :code:`(iteration, n_particles, dimensions)`\n canvas : (:obj:`matplotlib.figure.Figure`, :obj:`matplotlib.axes.Axes`),\n The (figure, axis) where all the events will be draw. If :code:`None`\n is supplied, then plot will be drawn to a fresh set of canvas.\n title : str, optional\n The title of the plotted graph. Default is `Trajectory`\n mark : tuple, optional\n Marks a particular point with a red crossmark. Useful for marking\n the optima.\n designer : :obj:`pyswarms.utils.formatters.Designer`, optional\n Designer class for custom attributes\n mesher : :obj:`pyswarms.utils.formatters.Mesher`, optional\n Mesher class for mesh plots\n animator : :obj:`pyswarms.utils.formatters.Animator`, optional\n Animator class for custom animation\n n_processes : int\n number of processes to use for parallel mesh point calculation (default: None = no parallelization)\n **kwargs : dict\n Keyword arguments that are passed as a keyword argument to\n :obj:`matplotlib.axes.Axes` plotting function\n\n Returns\n -------\n :obj:`matplotlib.animation.FuncAnimation`\n The drawn animation that can be saved to mp4 or other\n third-party tools\n \"\"\"\n\n try:\n # If no Designer class supplied, use defaults\n if designer is None:\n designer = Designer(\n limits=[(-1, 1), (-1, 1)], label=[\"x-axis\", \"y-axis\"]\n )\n\n # If no Animator class supplied, use defaults\n if animator is None:\n animator = Animator()\n\n # If ax is default, then create new plot. Set-up the figure, the\n # axis, and the plot element that we want to animate\n if canvas is None:\n fig, ax = plt.subplots(1, 1, figsize=designer.figsize)\n else:\n fig, ax = canvas\n\n # Get number of iterations\n n_iters = len(pos_history)\n\n # Customize plot\n ax.set_title(title, fontsize=designer.title_fontsize)\n ax.set_xlabel(designer.label[0], fontsize=designer.text_fontsize)\n ax.set_ylabel(designer.label[1], fontsize=designer.text_fontsize)\n ax.set_xlim(designer.limits[0])\n ax.set_ylim(designer.limits[1])\n\n # Make a contour map if possible\n if mesher is not None:\n xx, yy, zz, = _mesh(mesher, n_processes=n_processes)\n ax.contour(xx, yy, zz, levels=mesher.levels)\n\n # Mark global best if possible\n if mark is not None:\n ax.scatter(mark[0], mark[1], color=\"red\", marker=\"x\")\n\n # Put scatter skeleton\n plot = ax.scatter(x=[], y=[], c=\"black\", alpha=0.6, **kwargs)\n\n # Do animation\n anim = animation.FuncAnimation(\n fig=fig,\n func=_animate,\n frames=range(n_iters),\n fargs=(pos_history, plot),\n interval=animator.interval,\n repeat=animator.repeat,\n repeat_delay=animator.repeat_delay,\n )\n except TypeError:\n rep.logger.exception(\"Please check your input type\")\n raise\n else:\n return anim\n\n\ndef plot_surface(\n pos_history,\n canvas=None,\n title=\"Trajectory\",\n designer=None,\n mesher=None,\n animator=None,\n mark=None,\n n_processes=None,\n **kwargs\n):\n \"\"\"Plot a swarm's trajectory in 3D\n\n This is useful for plotting the swarm's 2-dimensional position with\n respect to the objective function. The value in the z-axis is the fitness\n of the 2D particle when passed to the objective function. When preparing the\n position history, make sure that the:\n\n * first column is the position in the x-axis,\n * second column is the position in the y-axis; and\n * third column is the fitness of the 2D particle\n\n The :class:`pyswarms.utils.plotters.formatters.Mesher` class provides a\n method that prepares this history given a 2D pos history from any\n optimizer.\n\n .. code-block:: python\n\n import pyswarms as ps\n from pyswarms.utils.functions.single_obj import sphere\n from pyswarms.utils.plotters import plot_surface\n from pyswarms.utils.plotters.formatters import Mesher\n\n # Run optimizer\n options = {'c1':0.5, 'c2':0.3, 'w':0.9}\n optimizer = ps.single.GlobalBestPSO(n_particles=10, dimensions=2, options)\n\n # Prepare position history\n m = Mesher(func=sphere)\n pos_history_3d = m.compute_history_3d(optimizer.pos_history)\n\n # Plot!\n plot_surface(pos_history_3d)\n\n Parameters\n ----------\n pos_history : numpy.ndarray\n Position history of the swarm with shape\n :code:`(iteration, n_particles, 3)`\n objective_func : callable\n The objective function that takes a swarm of shape\n :code:`(n_particles, 2)` and returns a fitness array\n of :code:`(n_particles, )`\n canvas : (:obj:`matplotlib.figure.Figure`, :obj:`matplotlib.axes.Axes`),\n The (figure, axis) where all the events will be draw. If :code:`None`\n is supplied, then plot will be drawn to a fresh set of canvas.\n title : str, optional\n The title of the plotted graph. Default is `Trajectory`\n mark : tuple, optional\n Marks a particular point with a red crossmark. Useful for marking the\n optima.\n designer : :obj:`pyswarms.utils.formatters.Designer`, optional\n Designer class for custom attributes\n mesher : :obj:`pyswarms.utils.formatters.Mesher`, optional\n Mesher class for mesh plots\n animator : :obj:`pyswarms.utils.formatters.Animator`, optional\n Animator class for custom animation\n n_processes : int\n number of processes to use for parallel mesh point calculation (default: None = no parallelization)\n **kwargs : dict\n Keyword arguments that are passed as a keyword argument to\n :class:`matplotlib.axes.Axes` plotting function\n\n Returns\n -------\n :class:`matplotlib.animation.FuncAnimation`\n The drawn animation that can be saved to mp4 or other\n third-party tools\n \"\"\"\n try:\n # If no Designer class supplied, use defaults\n if designer is None:\n designer = Designer(\n limits=[(-1, 1), (-1, 1), (-1, 1)],\n label=[\"x-axis\", \"y-axis\", \"z-axis\"],\n colormap=cm.viridis,\n )\n\n # If no Animator class supplied, use defaults\n if animator is None:\n animator = Animator()\n\n # Get number of iterations\n # If ax is default, then create new plot. Set-up the figure, the\n # axis, and the plot element that we want to animate\n if canvas is None:\n fig, ax = plt.subplots(1, 1, figsize=designer.figsize)\n else:\n fig, ax = canvas\n\n # Initialize 3D-axis\n ax = Axes3D(fig)\n\n n_iters = len(pos_history)\n\n # Customize plot\n ax.set_title(title, fontsize=designer.title_fontsize)\n ax.set_xlabel(designer.label[0], fontsize=designer.text_fontsize)\n ax.set_ylabel(designer.label[1], fontsize=designer.text_fontsize)\n ax.set_zlabel(designer.label[2], fontsize=designer.text_fontsize)\n ax.set_xlim(designer.limits[0])\n ax.set_ylim(designer.limits[1])\n ax.set_zlim(designer.limits[2])\n\n # Make a contour map if possible\n if mesher is not None:\n xx, yy, zz, = _mesh(mesher, n_processes=n_processes)\n ax.plot_surface(\n xx, yy, zz, cmap=designer.colormap, alpha=mesher.alpha\n )\n\n # Mark global best if possible\n if mark is not None:\n ax.scatter(mark[0], mark[1], mark[2], color=\"red\", marker=\"x\")\n\n # Put scatter skeleton\n plot = ax.scatter(xs=[], ys=[], zs=[], c=\"black\", alpha=0.6, **kwargs)\n\n # Do animation\n anim = animation.FuncAnimation(\n fig=fig,\n func=_animate,\n frames=range(n_iters),\n fargs=(pos_history, plot),\n interval=animator.interval,\n repeat=animator.repeat,\n repeat_delay=animator.repeat_delay,\n )\n except TypeError:\n rep.logger.exception(\"Please check your input type\")\n raise\n else:\n return anim\n\n\ndef _animate(i, data, plot):\n \"\"\"Helper animation function that is called sequentially\n :class:`matplotlib.animation.FuncAnimation`\n \"\"\"\n current_pos = data[i]\n if np.array(current_pos).shape[1] == 2:\n plot.set_offsets(current_pos)\n else:\n plot._offsets3d = current_pos.T\n return (plot,)\n\n\ndef _mesh(mesher, n_processes=None):\n \"\"\"Helper function to make a mesh\"\"\"\n xlim = mesher.limits[0]\n ylim = mesher.limits[1]\n x = np.arange(xlim[0], xlim[1], mesher.delta)\n y = np.arange(ylim[0], ylim[1], mesher.delta)\n xx, yy = np.meshgrid(x, y)\n xypairs = np.vstack([xx.reshape(-1), yy.reshape(-1)]).T\n\n # Get z-value\n\n # Setup Pool of processes for parallel evaluation\n pool = None if n_processes is None else mp.Pool(n_processes)\n\n if pool is None:\n z = mesher.func(xypairs)\n else:\n results = pool.map(\n mesher.func,\n np.array_split(xypairs, pool._processes),\n )\n z = np.concatenate(results)\n\n # Close Pool of Processes\n if n_processes is not None:\n pool.close()\n\n zz = z.reshape(xx.shape)\n return (xx, yy, zz)\n" ]
[ [ "numpy.arange", "matplotlib.pyplot.subplots", "numpy.concatenate", "numpy.array_split", "numpy.array", "numpy.meshgrid" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ancientmooner/DALI
[ "355e8db8130cee0d20e9ae3d698f195278544995" ]
[ "dali/python/nvidia/dali/plugin/pytorch.py" ]
[ "# Copyright (c) 2017-2019, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom nvidia.dali.pipeline import Pipeline\nimport nvidia.dali.ops as ops\nfrom nvidia.dali import types\nimport torch\nimport torch.utils.dlpack as torch_dlpack\nimport ctypes\nimport logging\nimport functools\n\nimport numpy as np\n\nto_torch_type = {\n np.dtype(np.float32) : torch.float32,\n np.dtype(np.float64) : torch.float64,\n np.dtype(np.float16) : torch.float16,\n np.dtype(np.uint8) : torch.uint8,\n np.dtype(np.int8) : torch.int8,\n np.dtype(np.int16) : torch.int16,\n np.dtype(np.int32) : torch.int32,\n np.dtype(np.int64) : torch.int64\n}\n\ndef feed_ndarray(dali_tensor, arr):\n \"\"\"\n Copy contents of DALI tensor to PyTorch's Tensor.\n\n Parameters\n ----------\n `dali_tensor` : nvidia.dali.backend.TensorCPU or nvidia.dali.backend.TensorGPU\n Tensor from which to copy\n `arr` : torch.Tensor\n Destination of the copy\n \"\"\"\n assert dali_tensor.shape() == list(arr.size()), \\\n (\"Shapes do not match: DALI tensor has size {0}\"\n \", but PyTorch Tensor has size {1}\".format(dali_tensor.shape(), list(arr.size())))\n #turn raw int to a c void pointer\n c_type_pointer = ctypes.c_void_p(arr.data_ptr())\n dali_tensor.copy_to_external(c_type_pointer)\n return arr\n\nclass DALIGenericIterator(object):\n \"\"\"\n General DALI iterator for PyTorch. It can return any number of\n outputs from the DALI pipeline in the form of PyTorch's Tensors.\n\n Please keep in mind that Tensors returned by the iterator are\n still owned by DALI. They are valid till the next iterator call.\n If the content needs to be preserved please copy it to another tensor.\n\n Parameters\n ----------\n pipelines : list of nvidia.dali.pipeline.Pipeline\n List of pipelines to use\n output_map : list of str\n List of strings which maps consecutive outputs\n of DALI pipelines to user specified name.\n Outputs will be returned from iterator as dictionary\n of those names.\n Each name should be distinct\n size : int\n Number of samples in the epoch (Usually the size of the dataset).\n Providing -1 means that the iterator will work until StopIteration is raised\n from the inside of iter_setup(). The options `fill_last_batch`, `last_batch_padded` and\n `auto_reset` don't work in such case. It works with only one pipeline inside\n the iterator.\n auto_reset : bool, optional, default = False\n Whether the iterator resets itself for the next epoch\n or it requires reset() to be called separately.\n fill_last_batch : bool, optional, default = True\n Whether to fill the last batch with data up to 'self.batch_size'.\n The iterator would return the first integer multiple\n of self._num_gpus * self.batch_size entries which exceeds 'size'.\n Setting this flag to False will cause the iterator to return\n exactly 'size' entries.\n dynamic_shape: bool, optional, default = False\n Whether the shape of the output of the DALI pipeline can\n change during execution. If True, the pytorch tensor will be resized accordingly\n if the shape of DALI returned tensors changes during execution.\n If False, the iterator will fail in case of change.\n last_batch_padded : bool, optional, default = False\n Whether the last batch provided by DALI is padded with the last sample\n or it just wraps up. In the conjunction with `fill_last_batch` it tells\n if the iterator returning last batch with data only partially filled with\n data from the current epoch is dropping padding samples or samples from\n the next epoch. If set to False next epoch will end sooner as data from\n it was consumed but dropped. If set to True next epoch would be the\n same length as the first one. For this happen, the option `pad_last_batch`\n in the reader need to be set to `True` as well.\n\n Example\n -------\n With the data set ``[1,2,3,4,5,6,7]`` and the batch size 2:\n\n fill_last_batch = False, last_batch_padded = True -> last batch = ``[7]``, next iteration will return ``[1, 2]``\n\n fill_last_batch = False, last_batch_padded = False -> last batch = ``[7]``, next iteration will return ``[2, 3]``\n\n fill_last_batch = True, last_batch_padded = True -> last batch = ``[7, 7]``, next iteration will return ``[1, 2]``\n\n fill_last_batch = True, last_batch_padded = False -> last batch = ``[7, 1]``, next iteration will return ``[2, 3]``\n \"\"\"\n def __init__(self,\n pipelines,\n output_map,\n size,\n auto_reset=False,\n fill_last_batch=True,\n dynamic_shape=False,\n last_batch_padded = False):\n if not isinstance(pipelines, list):\n pipelines = [pipelines]\n self._num_gpus = len(pipelines)\n assert pipelines is not None, \"Number of provided pipelines has to be at least 1\"\n self.batch_size = pipelines[0].batch_size\n self._size = int(size)\n self._auto_reset = auto_reset\n self._dynamic_shape = dynamic_shape\n self._fill_last_batch = fill_last_batch\n self._last_batch_padded = last_batch_padded\n assert self._size != 0, \"Size cannot be 0\"\n assert self._size > 0 or (self._size < 0 and len(pipelines) == 1), \"Negative size is supported only for a single pipeline\"\n if self._size < 0:\n self._auto_reset = False\n self._fill_last_batch = False\n self._last_batch_padded = False\n self._pipes = pipelines\n # Build all pipelines\n for p in self._pipes:\n with p._check_api_type_scope(types.PipelineAPIType.ITERATOR):\n p.build()\n # Use double-buffering of data batches\n self._data_batches = [None for i in range(self._num_gpus)]\n self._counter = 0\n assert len(set(output_map)) == len(output_map), \"output_map names should be distinct\"\n self._output_categories = set(output_map)\n self.output_map = output_map\n\n # We need data about the batches (like shape information),\n # so we need to run a single batch as part of setup to get that info\n for p in self._pipes:\n with p._check_api_type_scope(types.PipelineAPIType.ITERATOR):\n p.schedule_run()\n self._first_batch = None\n self._first_batch = self.next()\n\n def __next__(self):\n if self._first_batch is not None:\n batch = self._first_batch\n self._first_batch = None\n return batch\n if self._counter >= self._size and self._size > 0:\n if self._auto_reset:\n self.reset()\n raise StopIteration\n # Gather outputs\n outputs = []\n for p in self._pipes:\n with p._check_api_type_scope(types.PipelineAPIType.ITERATOR):\n outputs.append(p.share_outputs())\n for i in range(self._num_gpus):\n dev_id = self._pipes[i].device_id\n # initialize dict for all output categories\n category_outputs = dict()\n # segregate outputs into categories\n for j, out in enumerate(outputs[i]):\n category_outputs[self.output_map[j]] = out\n\n # Change DALI TensorLists into Tensors\n category_tensors = dict()\n category_shapes = dict()\n for category, out in category_outputs.items():\n category_tensors[category] = out.as_tensor()\n category_shapes[category] = category_tensors[category].shape()\n\n # If we did not yet allocate memory for that batch, do it now\n if self._data_batches[i] is None:\n category_torch_type = dict()\n category_device = dict()\n torch_gpu_device = torch.device('cuda', dev_id)\n torch_cpu_device = torch.device('cpu')\n # check category and device\n for category in self._output_categories:\n category_torch_type[category] = to_torch_type[np.dtype(category_tensors[category].dtype())]\n from nvidia.dali.backend import TensorGPU\n if type(category_tensors[category]) is TensorGPU:\n category_device[category] = torch_gpu_device\n else:\n category_device[category] = torch_cpu_device\n\n pyt_tensors = dict()\n for category in self._output_categories:\n pyt_tensors[category] = torch.zeros(category_shapes[category],\n dtype=category_torch_type[category],\n device=category_device[category])\n\n self._data_batches[i] = pyt_tensors\n else:\n pyt_tensors = self._data_batches[i]\n\n # Copy data from DALI Tensors to torch tensors\n for category, tensor in category_tensors.items():\n if self._dynamic_shape and tensor.shape() != list(pyt_tensors[category].size()):\n pyt_tensors[category] = torch.zeros(category_shapes[category],\n dtype=pyt_tensors[category].dtype,\n device=pyt_tensors[category].device)\n feed_ndarray(tensor, pyt_tensors[category])\n\n for p in self._pipes:\n with p._check_api_type_scope(types.PipelineAPIType.ITERATOR):\n p.release_outputs()\n p.schedule_run()\n\n self._counter += self._num_gpus * self.batch_size\n\n if (not self._fill_last_batch) and (self._counter > self._size) and self._size > 0:\n # First calculate how much data is required to return exactly self._size entries.\n diff = self._num_gpus * self.batch_size - (self._counter - self._size)\n # Figure out how many GPUs to grab from.\n numGPUs_tograb = int(np.ceil(diff/self.batch_size))\n # Figure out how many results to grab from the last GPU (as a fractional GPU batch may be required to\n # bring us right up to self._size).\n mod_diff = diff % self.batch_size\n data_fromlastGPU = mod_diff if mod_diff else self.batch_size\n\n # Grab the relevant data.\n # 1) Grab everything from the relevant GPUs.\n # 2) Grab the right data from the last GPU.\n # 3) Append data together correctly and return.\n output = self._data_batches[0:numGPUs_tograb]\n output[-1] = output[-1].copy()\n for category in self._output_categories:\n output[-1][category] = output[-1][category][0:data_fromlastGPU]\n return output\n\n return self._data_batches\n\n def next(self):\n \"\"\"\n Returns the next batch of data.\n \"\"\"\n return self.__next__()\n\n def __iter__(self):\n return self\n\n def reset(self):\n \"\"\"\n Resets the iterator after the full epoch.\n DALI iterators do not support resetting before the end of the epoch\n and will ignore such request.\n \"\"\"\n if self._counter >= self._size or self._size < 0:\n if self._fill_last_batch and not self._last_batch_padded:\n self._counter = self._counter % self._size\n else:\n self._counter = 0\n for p in self._pipes:\n p.reset()\n if p.empty():\n with p._check_api_type_scope(types.PipelineAPIType.ITERATOR):\n p.schedule_run()\n else:\n logging.warning(\"DALI iterator does not support resetting while epoch is not finished. Ignoring...\")\n\nclass DALIClassificationIterator(DALIGenericIterator):\n \"\"\"\n DALI iterator for classification tasks for PyTorch. It returns 2 outputs\n (data and label) in the form of PyTorch's Tensor.\n\n Calling\n\n .. code-block:: python\n\n DALIClassificationIterator(pipelines, size)\n\n is equivalent to calling\n\n .. code-block:: python\n\n DALIGenericIterator(pipelines, [\"data\", \"label\"], size)\n\n Please keep in mind that Tensors returned by the iterator are\n still owned by DALI. They are valid till the next iterator call.\n If the content needs to be preserved please copy it to another tensor.\n\n Parameters\n ----------\n pipelines : list of nvidia.dali.pipeline.Pipeline\n List of pipelines to use\n size : int\n Number of samples in the epoch (Usually the size of the dataset).\n Providing -1 means that the iterator will work until StopIteration is raised\n from the inside of iter_setup(). The options `fill_last_batch`, `last_batch_padded` and\n `auto_reset` don't work in such case. It works with only one pipeline inside\n the iterator.\n auto_reset : bool, optional, default = False\n Whether the iterator resets itself for the next epoch\n or it requires reset() to be called separately.\n fill_last_batch : bool, optional, default = True\n Whether to fill the last batch with data up to 'self.batch_size'.\n The iterator would return the first integer multiple\n of self._num_gpus * self.batch_size entries which exceeds 'size'.\n Setting this flag to False will cause the iterator to return\n exactly 'size' entries.\n dynamic_shape: bool, optional, default = False\n Whether the shape of the output of the DALI pipeline can\n change during execution. If True, the pytorch tensor will be resized accordingly\n if the shape of DALI returned tensors changes during execution.\n If False, the iterator will fail in case of change.\n last_batch_padded : bool, optional, default = False\n Whether the last batch provided by DALI is padded with the last sample\n or it just wraps up. In the conjunction with `fill_last_batch` it tells\n if the iterator returning last batch with data only partially filled with\n data from the current epoch is dropping padding samples or samples from\n the next epoch. If set to False next epoch will end sooner as data from\n it was consumed but dropped. If set to True next epoch would be the\n same length as the first one.\n\n Example\n -------\n With the data set ``[1,2,3,4,5,6,7]`` and the batch size 2:\n\n fill_last_batch = False, last_batch_padded = True -> last batch = ``[7]``, next iteration will return ``[1, 2]``\n\n fill_last_batch = False, last_batch_padded = False -> last batch = ``[7]``, next iteration will return ``[2, 3]``\n\n fill_last_batch = True, last_batch_padded = True -> last batch = ``[7, 7]``, next iteration will return ``[1, 2]``\n\n fill_last_batch = True, last_batch_padded = False -> last batch = ``[7, 1]``, next iteration will return ``[2, 3]``\n \"\"\"\n def __init__(self,\n pipelines,\n size,\n auto_reset=False,\n fill_last_batch=True,\n dynamic_shape=False,\n last_batch_padded=False):\n super(DALIClassificationIterator, self).__init__(pipelines, [\"data\", \"label\"],\n size, auto_reset = auto_reset,\n fill_last_batch = fill_last_batch,\n dynamic_shape = dynamic_shape,\n last_batch_padded = last_batch_padded)\n\n\nclass TorchPythonFunction(ops.PythonFunctionBase):\n ops.register_cpu_op('TorchPythonFunction')\n ops.register_gpu_op('TorchPythonFunction')\n\n def _torch_stream_wrapper(self, function, *ins):\n with torch.cuda.stream(self.stream):\n out = function(*ins)\n self.stream.synchronize()\n return out\n\n def torch_wrapper(self, batch_processing, function, device, *args):\n func = function if device == 'cpu' else \\\n lambda *ins: self._torch_stream_wrapper(function, *ins)\n if batch_processing:\n return ops.PythonFunction.function_wrapper_batch(func,\n torch.utils.dlpack.from_dlpack,\n torch.utils.dlpack.to_dlpack,\n *args)\n else:\n return ops.PythonFunction.function_wrapper_per_sample(func,\n torch_dlpack.from_dlpack,\n torch_dlpack.to_dlpack,\n *args)\n\n def __call__(self, *inputs, **kwargs):\n pipeline = Pipeline.current()\n if pipeline is None:\n Pipeline._raise_no_current_pipeline(\"TorchPythonFunction\")\n if self.stream is None:\n self.stream = torch.cuda.Stream(device=pipeline.device_id)\n return super(TorchPythonFunction, self).__call__(*inputs, **kwargs)\n\n def __init__(self, function, num_outputs=1, device='cpu', batch_processing=False, **kwargs):\n self.stream = None\n super(TorchPythonFunction, self).__init__(impl_name=\"DLTensorPythonFunctionImpl\",\n function=lambda *ins:\n self.torch_wrapper(batch_processing,\n function, device,\n *ins),\n num_outputs=num_outputs, device=device,\n batch_processing=batch_processing, **kwargs)\n" ]
[ [ "torch.zeros", "numpy.dtype", "numpy.ceil", "torch.cuda.stream", "torch.device", "torch.cuda.Stream" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
duncanmorgan/fast_tcrdist
[ "ec0a59f27757369f7093ddf871bfde5137e7f940" ]
[ "fast_tcrdist/plot.py" ]
[ "import seaborn as sns\nimport pandas as pd\nfrom . import useful\nfrom .tcrdist import stats as stat\nimport matplotlib.pyplot as plt\nimport numpy as np\t\nimport logomaker\nfrom collections import Counter\n\ndef plot_distance_matrix(\n\tdata,\n\trow_colors : str = None,\n\t**kwargs) :\n\t\n\tif row_colors :\n\t\tif row_colors not in data.obs.columns :\n\t\t\traise ValueError(\"{row_col} not in .obs\".format(row_col = row_colors))\n\t\t# Get the categories\n\t\tif not pd.api.types.is_categorical(data.obs[row_colors]) :\n\t\t\tdata.obs[row_colors] = data.obs[row_colors].astype(\"category\")\n\t\tcategories = data.obs[row_colors].cat.categories\n\n\t\tif not \"{row_col}_colors\".format(row_col = row_colors) in data.uns :\n\n\t\t\tpalette = useful.godsnot_102[:len(categories)]\n\t\t\tdata.uns[\"{row_col}_colors\".format(row_col = row_colors)] = palette\n\n\t\tcol_dict = dict(zip(categories, data.uns[\"{row_col}_colors\".format(row_col = row_colors)]))\n\n\t\trow_colors = [col_dict[gene] for gene in data.obs[row_colors]]\n\n\tif not \"linkage\" in data.uns :\n\t\tlinkage = stat.calculate_linkage(data.X, data.obs.index.values)\n\t\tdata.uns[\"linkage\"] = linkage\n\telse :\n\t\tlinkage = data.uns[\"linkage\"]\n\tplot_df = pd.DataFrame(data.X, index = data.obs.index.values)\n\tplot = sns.clustermap(plot_df, row_linkage=linkage, col_linkage=linkage, row_colors = row_colors, **kwargs)\n\treturn(plot)\n\n\ndef cluster_logo_plot(adata, obs_col, obs_val, lengths = \"all\") :\n\tlength_args = [\"all\", \"dominant\"]\n\tif lengths not in length_args :\n\t\traise ValueError(\"length argument must be one of %s\" % length_args)\n\n\t# Lets take an example cluster\n\tlogo_clust = adata.obs[adata.obs[obs_col] == obs_val][[\"TRA_cdr3\", \"TRB_cdr3\", \"TRA_cdr3_length\", \"TRB_cdr3_length\"]]\n\n\t# Figure out the dominant lengths of the clusters\n\tif lengths == \"dominant\" :\n\t\tnum_alpha_lengths = 1\n\t\tnum_beta_lengths = 1\n\telse :\n\t\tnum_beta_lengths = len(set(logo_clust[\"TRB_cdr3_length\"]))\n\t\tnum_alpha_lengths = len(set(logo_clust[\"TRA_cdr3_length\"]))\n\n\tfigRows = max([num_beta_lengths, num_alpha_lengths])\n\n\t# NEED TO FIGURE OUT HOW TO MAKE A GOOD FIGSIZE CALCULATION\n\tfig, ax = plt.subplots(nrows = figRows, ncols = 2, figsize = (10 * figRows, 3 * figRows))\n\n\tfor num, seqtype in enumerate([\"TRA\", \"TRB\"]) :\n\t\tseq_df = logo_clust[[\"{seqtype}_cdr3\".format(seqtype = seqtype), \"{seqtype}_cdr3_length\".format(seqtype = seqtype)]]\n\n\t\tif lengths == \"dominant\" :\n\t\t\tchain_lengths = [seq_df[\"{seqtype}_cdr3_length\".format(seqtype = seqtype)].value_counts().idxmax()]\n\t\telse :\n\t\t\tchain_lengths = sorted(set(seq_df[\"{seqtype}_cdr3_length\".format(seqtype = seqtype)]))\n\t\tfor row, seqlen in enumerate(chain_lengths) :\n\t\t\t# Get the seqs\n\t\t\tlogo_seqs = seq_df[seq_df[\"{seqtype}_cdr3_length\".format(seqtype = seqtype)] == seqlen][\"{seqtype}_cdr3\".format(seqtype = seqtype)]\n\t\t\t# Concatenate and determine all used AA in seqs\n\t\t\tunique_AA = set(\"\".join(seq for seq in logo_seqs))\n\t\t\t# Probability matrix\n\t\t\tprob_df = pd.DataFrame(index = range(seqlen), columns = unique_AA)\n\n\t\t\tfor indx in range(len(logo_seqs[0])) :\n\t\t\t\t# Get the letter at the position for each seq\n\t\t\t\tAAs = [seq[indx] for seq in logo_seqs]\n\n\t\t\t\t# Calculate probabilities\n\t\t\t\tprob_dict = dict(Counter(AAs))\n\t\t\t\tfor key, val in prob_dict.items() :\n\t\t\t\t\tprob = val / len(AAs)\n\t\t\t\t\tprob_df.loc[indx, key] = prob\n\t\t\tprob_df = prob_df.fillna(0)\n\t\t\tprob_df.sum(axis = 1)\n\n\t\t\tif figRows == 1 :\n\t\t\t\tlogomaker.Logo(prob_df, ax = ax[num],\n\t\t\t\t\t\t\t\twidth=.8,\n\t\t\t\t\t\t\t\tvpad=.05,\n\t\t\t\t\t\t\t\tfade_probabilities=True,\n\t\t\t\t\t\t\t\tstack_order='small_on_top',\n\t\t\t\t\t\t\t\tcolor_scheme='dodgerblue',\n\t\t\t\t\t\t\t\tfont_name='Rosewood Std'\n\t\t\t\t\t\t\t )\n\t\t\t\tax[num].set_title(\"Number of seqs: {seqlen}\".format(seqlen = len(logo_seqs)), {\"fontsize\" : 10, \"fontweight\" : \"bold\"})\n\n\t\t\t\t# Add additional title\n\t\t\t\t# Get the center of the plot\n\t\t\t\tcenter = seqlen / 1.75\n\t\t\t\theight = 1.1 + (figRows / 15)\n\t\t\t\tax[num].text(center, height, \"{seqtype} CDR3\".format(seqtype = seqtype),{\"fontsize\" : 15, \"fontweight\" : \"bold\"} ,\n\t\t\t\t\t\t\t\t horizontalalignment = \"right\")\n\t\t\t\tcontinue\n\t\t\telse :\n\t\t\t\tlogomaker.Logo(prob_df, ax = ax[row, num],\n\t\t\t\t\t\t\t\twidth=.8,\n\t\t\t\t\t\t\t\tvpad=.05,\n\t\t\t\t\t\t\t\tfade_probabilities=True,\n\t\t\t\t\t\t\t\tstack_order='small_on_top',\n\t\t\t\t\t\t\t\tcolor_scheme='dodgerblue',\n\t\t\t\t\t\t\t\tfont_name='Rosewood Std'\n\t\t\t\t\t\t\t )\n\t\t\t\tax[row, num].set_title(\"Number of seqs: {seqlen}\".format(seqlen = len(logo_seqs)), {\"fontsize\" : 10, \"fontweight\" : \"bold\"})\n\t\t\t# If the first of either alpha or beta, add additional title\n\t\t\t\tif row == 0 :\n\t\t\t\t\t# Get the center of the plot\n\t\t\t\t\tcenter = (seqlen + .75) / 2\n\t\t\t\t\theight = 1 + (figRows / 15)\n\t\t\t\t\tax[row, num].text(center, height, \"{seqtype} CDR3\".format(seqtype = seqtype),{\"fontsize\" : 15, \"fontweight\" : \"bold\"} ,\n\t\t\t\t\t\t\t\t\t horizontalalignment = \"right\")\n\tfig.tight_layout()\n\n\t# Determine which chain has more seq lengths\n\tif num_beta_lengths > num_alpha_lengths :\n\t\t# get rid of excess alpha plots\n\t\tfor noLogo in range(num_alpha_lengths, num_beta_lengths) :\n\t\t\tax[noLogo, 0].axis(\"off\")\n\telif num_beta_lengths < num_alpha_lengths :\n\t\t# Get rid of excess beta plots\n\t\tfor noLogo in range(num_beta_lengths, num_alpha_lengths) :\n\t\t\tax[noLogo, 1].axis(\"off\")\n\n\treturn(fig)" ]
[ [ "pandas.api.types.is_categorical", "matplotlib.pyplot.subplots", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
PerinatalLab/ROH
[ "703d7aa81d1c5e7d61e75597d43905b337c06f9a" ]
[ "scripts/survival/overlap_split_segment.py" ]
[ "import pandas as pd\nimport numpy as np\n\ndf_list= list()\n\nif 'frequency' not in snakemake.input[0]:\n\td= pd.read_csv(snakemake.input[0], sep= '\\t', header= None, names= ['segment', 'n', 'beta', 'sd', 'pvalue'])\n\td[['chr', 'cM1', 'cM2']]= d['segment'].str.split(':', expand= True)\n\td[['chr', 'cM1', 'cM2']]= d[['chr', 'cM1', 'cM2']].apply(lambda x: x.astype('float'))\n\tfor infile in snakemake.input[1:]:\n\t\tdf= pd.read_csv(infile, sep= '\\t', header= None, names= ['segment', 'n', 'beta', 'sd', 'pvalue'])\n\t\tdf[['chr', 'cM1', 'cM2']]= df['segment'].str.split(':', expand= True)\n\t\tdf[['chr', 'cM1', 'cM2']]= df[['chr', 'cM1', 'cM2']].apply(lambda x: x.astype('float'))\n\t\tdf= df[['chr', 'cM1', 'cM2']]\n\t\tdf_list.append(df)\n\t\n\tdf= pd.concat(df_list)\n\t\n\tdf_list= list()\n\tfor CHR in set(d.chr):\n\t\ta= df.loc[df.chr== CHR, :]\n\t\ta= pd.concat([a.cM1, a.cM2])\n\t\ta= np.unique(a)\n\t\ta= np.sort(a)\n\t\ttemp_d= d.loc[d.chr== CHR, :]\n\t\tfor index, row in temp_d.iterrows():\n\t\t\tbh= row.cM2\n\t\t\tbl= row.cM1\n\t\t\ti, j = np.where((a[:, None] >= bl) & (a[:, None] <= bh))\n\t\t\tx= pd.DataFrame(a[i], columns= ['cM1']).dropna()\n\t\t\tx['cM2']= x.cM1.shift(-1)\n\t\t\tx.dropna(inplace= True)\n\t\t\tx['chr'], x['n'], x['beta'], x['sd'], x['pvalue']= row.chr, row.n, row.beta, row.sd, row.pvalue #, row.R, row.Rpvalue\n\t\t\tdf_list.append(x.copy())\n\nif 'frequency' in snakemake.input[0]:\n\td= pd.read_csv(snakemake.input[0], sep= '\\t', header= None, names= ['chr', 'segment', 'freq'])\n\td[['cM1', 'cM2']]= d['segment'].str.split(':',expand=True)\n\td[['cM1', 'cM2']]= d[['cM1', 'cM2']].apply(lambda x: x.astype('float'))\n\tdf_list= list()\n\tfor infile in snakemake.input[1:]:\n df= pd.read_csv(infile, sep= '\\t', header= None, names= ['chr', 'segment', 'freq'])\n df[['cM1', 'cM2']]= df['segment'].str.split(':', expand= True)\n df[['cM1', 'cM2']]= df[['cM1', 'cM2']].apply(lambda x: x.astype('float'))\n df= df[['chr', 'cM1', 'cM2']]\n df_list.append(df)\n\tdf= pd.concat(df_list)\n\t\n\tdf_list= list()\n\tfor CHR in set(d.chr):\n\t\ta= df.loc[df.chr== CHR, :]\n\t\ta= pd.concat([a.cM1, a.cM2])\n\t\ta= np.unique(a)\n\t\ta= np.sort(a)\n\t\ttemp_d= d.loc[d.chr== CHR, :]\n\t\tfor index, row in temp_d.iterrows():\n\t\t\tbh= row.cM2\n\t\t\tbl= row.cM1 \n\t\t\ti, j = np.where((a[:, None] >= bl) & (a[:, None] <= bh))\n\t\t\tx= pd.DataFrame(a[i], columns= ['cM1']).dropna()\n\t\t\tx['cM2']= x.cM1.shift(-1)\n\t\t\tx.dropna(inplace= True)\n\t\t\tx['chr'], x['freq']= row.chr, row.freq\n\t\t\tdf_list.append(x.copy())\n\ndf= pd.concat(df_list)\n\ndf.to_csv(snakemake.output[0], header= True, sep= '\\t', index= False)\n" ]
[ [ "pandas.concat", "pandas.read_csv", "numpy.unique", "numpy.sort", "pandas.DataFrame", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
Ulti-Dreisteine/time-series-walk-forward-modeling
[ "5d707d1a01cdcd0bf5cbc15ef9473ef490564c1e" ]
[ "mod/config/config_loader.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2021/02/27 21:13:39\n\n@File -> config_loader.py\n\n@Author: luolei\n\n@Email: [email protected]\n\n@Describe: 项目配置工具\n\"\"\"\n\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\nimport matplotlib.pyplot as plt\nimport logging.config\nimport logging\nimport yaml\nimport sys\nimport os\n\nBASE_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '../'))\nsys.path.append(BASE_DIR)\n\nSMALL_SIZE = 6\nMEDIUM_SIZE = 8\nBIGGER_SIZE = 10\n\nplt.rc('font', size=BIGGER_SIZE, family='Times New Roman')\nplt.rc('axes', titlesize=BIGGER_SIZE)\nplt.rc('axes', labelsize=BIGGER_SIZE)\nplt.rc('xtick', labelsize=BIGGER_SIZE)\nplt.rc('ytick', labelsize=BIGGER_SIZE)\nplt.rc('legend', fontsize=BIGGER_SIZE)\nplt.rc('figure', titlesize=20)\n\n_color_map = {\n 'blue': '#1f77b4', # 蓝色\n 'orange': '#ff7f0e', # 黄橙色\n 'green': '#2ca02c', # 绿色\n 'red': '#d62728', # 红色\n 'purple': '#9467bd', # 紫色\n 'cyan': '#17becf', # 青色\n 'grey': '#7f7f7f', # 灰色\n 'black': 'k', # 黑色\n 'white': 'w',\n\n # 类似色搭配互补色, 同一色系list中颜色由亮到暗排列.\n 'similar-complement-cmap': {\n 'greens': ['#5ED1BA', '#34D1B2', '#00A383', '#1F7A68', '#006A55'],\n 'reds': ['#F97083', '#F93E58', '#F30021', '#B62E40s', '#9E0016'],\n 'yellows': ['#FFCB73', '#FFB840', '#FFA100', '#BF8A30', '#A66900'],\n 'oranges': ['#FFAA73', '#FF8B40', '#FF6400', '#BF6830', '#A64100'],\n }\n}\n\n\ndef _load_yml(fp: str) -> dict:\n with open(fp, 'r', encoding='utf-8') as f:\n conf = yaml.load(f, Loader=yaml.Loader) # yaml.FullLoader\n\n if conf is None:\n conf = {}\n\n return conf\n\n\nclass ConfigLoader(object):\n \"\"\"项目配置装载器\"\"\"\n\n def __init__(self):\n self._get_proj_root_dir()\n self._config_path = os.path.join(self.proj_dir, 'config/')\n self._set_proj_cmap()\n self._load_model_config()\n self._load_environ_config()\n self._load_test_params()\n\n def _get_proj_root_dir(self):\n \"\"\"获取项目根目录\"\"\"\n self._proj_dir = os.path.abspath(\n os.path.join(os.path.dirname(__file__), '../../'))\n\n @property\n def proj_dir(self):\n return self._proj_dir\n\n def _set_proj_cmap(self):\n \"\"\"设置项目颜色方案\"\"\"\n self._proj_cmap = _color_map\n\n @property\n def proj_cmap(self):\n return self._proj_cmap\n\n def _load_model_config(self):\n \"\"\"载入模型参数配置文件\"\"\"\n self._model_config_path = os.path.join(\n self._config_path, 'model_config.yml')\n self._model_config = _load_yml(self._model_config_path)\n\n @property\n def proj_plt(self):\n return plt\n\n @property\n def model_config(self):\n return self._model_config\n\n def _load_environ_config(self):\n \"\"\"载入环境变量配置\"\"\"\n # 读取本地文件中的环境变量设置.\n # 如果本地config中有master.yml则优先使用, 否则使用default.yml, 否则为空字典.\n _environ_config_path_ = None\n for _file_name in ['master.yml', 'default.yml']:\n if _file_name in os.listdir(self._config_path):\n print('Use environmental variables in {}'.format(_file_name))\n _environ_config_path_ = os.path.join(\n self._config_path, _file_name)\n break\n\n if _environ_config_path_ is None:\n self._local_environ_config = {}\n else:\n self._local_environ_config = _load_yml(_environ_config_path_)\n\n # 线上环境变量注入.\n # 如果存在可注入环境变量, 则采用注入值, 否则采用环境变量配置文件中的值.\n self._environ_config = self._local_environ_config\n for key in self._local_environ_config.keys():\n if key in os.environ.keys():\n self._environ_config.update({key: os.environ[key]})\n\n @property\n def environ_config(self):\n return self._environ_config\n\n def _load_test_params(self):\n _test_params_path = os.path.join(self._config_path, 'test_params.yml')\n self._test_params = _load_yml(_test_params_path)\n\n @property\n def test_params(self):\n return self._test_params\n\n def set_logging(self):\n \"\"\"日志配置\"\"\"\n # 检查本地是否有日志目录, 若没有则创建.\n if 'logs' not in os.listdir(self.proj_dir):\n os.mkdir(os.path.join(self.proj_dir, 'logs/'))\n\n # 配置日志.\n try:\n _log_config = self._model_config['logging']\n except Exception as e:\n raise RuntimeError(\n 'Cannot load logging params in model_config.yml, {}'.format(e))\n\n logging.config.dictConfig(_log_config)\n\n\nconfig_loader = ConfigLoader()\n" ]
[ [ "matplotlib.pyplot.rc" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mnemocron/FHNW
[ "e43c298cb9c8f617fa19b77dd6630a342c78bda7" ]
[ "mxst/pipeline_EXAM.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jun 29 08:58:00 2020\r\n\r\n@author: simon\r\n\r\nSEE EXAM in the SECTION BELOW\r\n\r\n\"\"\"\r\n#%%\r\nimport sympy as sp\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Quantizer\r\n# quant(0.111, [-0.125, 0.125]) ==> 1 out of range[0, 1, 2]\r\n# returns value in range [0 to n+1] where n = len(references)\r\ndef quant(x, thresholds): \r\n t = np.concatenate( ( thresholds, [1e10] ) ) \r\n r = min( [(idx,val) for (idx,val) in enumerate(t) if val>x] )[0] \r\n return r\r\n\r\n# MDAC\r\n# mdac(0.123, [-0.125, 0.125], [-0.25, 0, 0.25], 2) ==> [1, 0.246]\r\n#\r\n# thresholds => for quantizer\r\n# reference => for DAC\r\ndef mdac(x, thresholds, references, gain): \r\n # The MDAC first uses a quantizer to determine the region. \r\n r = quant(x,thresholds) \r\n y = ( x - references[r] ) * gain \r\n return [r,y]\r\n \r\n# pipeline ADC\r\ndef pipeA(x, Nstage): \r\n re15 = np.arange( -1/4, 1/4+0.01, 1/4 ) \r\n th15 = np.convolve( re15, np.array([1/2,1/2]) )[1:-1] \r\n ga15 = 2\r\n xs = np.zeros(Nstage) \r\n xs[0] = x \r\n rs = np.zeros(Nstage) \r\n cumgain = 1 \r\n \r\n # All but the last stage are 1.5-bit-stages: \r\n for k in np.arange(Nstage-1): \r\n # Use the appropriate MDAC: \r\n [rs[k],xs[k+1]] = mdac(xs[k],th15,re15,ga15) \r\n # The cumulative gain is multiplied by the gain of the stage: \r\n cumgain *= 2 \r\n # The region is then scaled by 1/cumgain; therefore the first stage \r\n # just ouputs its region number divided by its gain. \r\n rs[k] = rs[k]/cumgain \r\n \r\n # The last stage is a normal 1-bit stage with a gain of 1\r\n k=Nstage-1 \r\n rs[k] = quant(xs[k],[0]) \r\n cumgain = cumgain*1 \r\n rs[k] = rs[k]/cumgain \r\n \r\n # The output of the ADC is the sum of all region numbers, but if we want \r\n # integers, they need to be scaled back by cumgain. \r\n b = np.sum(rs)*cumgain \r\n return b\r\n\r\n# 1.5 Bit\r\ndef pipeAnonid(x, Nstage): \r\n # This is the same as pipeA, but with an incorrect gain and a shifted \r\n # reference: \r\n re15 = np.arange( -1/4, 1/4+0.01, 1/4 ) \r\n th15 = np.convolve( re15, np.array([1/2,1/2]) )[1:-1] \r\n # ------ INPUT HERE ------\r\n ga15 = 1.98 \r\n re15[0] = re15[0]-0.01 \r\n # ------ \r\n xs = np.zeros(Nstage) \r\n xs[0] = x \r\n rs = np.zeros(Nstage) \r\n cumgain = 1 \r\n for k in np.arange(Nstage-1): \r\n [rs[k],xs[k+1]] = mdac(xs[k],th15,re15,ga15) \r\n cumgain *= 2 \r\n rs[k] = rs[k]/cumgain \r\n # last stage\r\n k=Nstage-1 \r\n rs[k] = quant(xs[k],[0]) \r\n cumgain = cumgain*1 \r\n rs[k] = rs[k]/cumgain \r\n # output scale \r\n b = np.sum(rs)*cumgain \r\n return b\r\n\r\n# 1.5 Bit\r\ndef pipe1721(x,Nstage): \r\n # This is the ADC from Fig. 17.21 in the textbook; the only difference is that \r\n # the last stage is a two-bit quantizer \r\n re15 = np.arange( -1/4, 1/4+0.01, 1/4 ) \r\n th15 = np.convolve( re15, np.array([1/2,1/2]) )[1:-1] \r\n ga15 = 2 \r\n xs = np.zeros(Nstage) \r\n xs[0] = x \r\n rs = np.zeros(Nstage) \r\n cumgain = 1 \r\n for k in np.arange(Nstage-1): \r\n [rs[k],xs[k+1]] = mdac(xs[k],th15,re15,ga15) \r\n cumgain *= 2 \r\n rs[k] = rs[k]/cumgain \r\n k=Nstage-1 \r\n \r\n # The last stage is a two-bit stage. \r\n # This two-bit stage needs to have one threshold at 0! \r\n # Being a two-bit stage, it implicitly has a gain of 2 \r\n rs[k] = quant(xs[k],[-0.5,0,0.5]) \r\n cumgain = cumgain*2 \r\n rs[k] = rs[k]/cumgain \r\n \r\n # output scale \r\n b = np.sum(rs)*cumgain \r\n return b\r\n\r\n# 1.5 Bit - Nonideal\r\ndef pipe1721nonid(x,Nstage): \r\n # This is the ADC from Fig. 17.21 in the textbook; the only difference is that \r\n # the last stage is a two-bit quantizer \r\n re15 = np.arange( -1/4, 1/4+0.01, 1/4 ) \r\n th15 = np.convolve( re15, np.array([1/2,1/2]) )[1:-1]\r\n # ------ INPUT HERE ------\r\n ga15 = 1.98 \r\n re15[0] = re15[0]-0.01 \r\n # ------ \r\n xs = np.zeros(Nstage) \r\n xs[0] = x \r\n rs = np.zeros(Nstage) \r\n cumgain = 1 \r\n for k in np.arange(Nstage-1): \r\n [rs[k],xs[k+1]] = mdac(xs[k],th15,re15,ga15) \r\n cumgain *= 2 \r\n rs[k] = rs[k]/cumgain \r\n k=Nstage-1 \r\n \r\n # The last stage is a two-bit stage. \r\n # This two-bit stage needs to have one threshold at 0! \r\n # Being a two-bit stage, it implicitly has a gain of 2 \r\n rs[k] = quant(xs[k],[-0.5,0,0.5]) \r\n cumgain = cumgain*2 \r\n rs[k] = rs[k]/cumgain \r\n \r\n # output scale \r\n b = np.sum(rs)*cumgain \r\n return b\r\n\r\n# 2.5 Bit Stages followed by 1.5 Bit Stages and a final 1 Bit stage\r\ndef pipe25b15b(x,N25,N15): \r\n # This is again the same as pipeA, but it has N25 2.5-bit stages followed \r\n # by N15 1.5-bit stages and one 1-bit stage. \r\n re15 = np.arange( -1/4, 1/4+0.01, 1/4 ) \r\n th15 = np.convolve( re15, np.array([1/2,1/2]) )[1:-1] \r\n ga15 = 2 \r\n \r\n # So we also need the thresholds and gains of the 2.5-bit MDAC: \r\n re25 = np.arange( -6/16, 6/16+0.01, 1/8 ) \r\n th25 = np.convolve( re25, np.array([1/2,1/2]) )[1:-1] \r\n ga25 = 4 \r\n\r\n # The total number of stages is now \r\n Nstage = N25+N15+1 \r\n\r\n xs = np.zeros(Nstage) \r\n xs[0] = x \r\n rs = np.zeros(Nstage) \r\n cumgain = 1 \r\n\r\n # First the 2.5-bit stages. \r\n for k in np.arange(N25): \r\n [rs[k],xs[k+1]] = mdac(xs[k],th25,re25,ga25) \r\n cumgain *= 4 \r\n rs[k] = rs[k]/cumgain \r\n\r\n # Then the 1.5-bit stages: their indices go from N25 to Nstage-1: \r\n for k in np.arange(N25,Nstage-1): \r\n [rs[k],xs[k+1]] = mdac(xs[k],th15,re15,ga15) \r\n cumgain *= 2 \r\n rs[k] = rs[k]/cumgain \r\n \r\n # We finish with the one-bit stage \r\n k=Nstage-1 \r\n rs[k] = quant(xs[k],[0]) \r\n cumgain = cumgain*1 \r\n rs[k] = rs[k]/cumgain \r\n \r\n # output scale \r\n b = np.sum(rs)*cumgain \r\n return b\r\n\r\n# 2.5 Bit Stages followed by a final 1 Bit stage\r\ndef pipe25b(x,N25): \r\n # So we also need the thresholds and gains of the 2.5-bit MDAC: \r\n re25 = np.arange( -6/16, 6/16+0.01, 1/8 ) \r\n th25 = np.convolve( re25, np.array([1/2,1/2]) )[1:-1] \r\n ga25 = 4 \r\n\r\n # The total number of stages is now \r\n Nstage = N25+1\r\n\r\n xs = np.zeros(Nstage) \r\n xs[0] = x \r\n rs = np.zeros(Nstage) \r\n cumgain = 1 \r\n\r\n # First the 2.5-bit stages. \r\n for k in np.arange(N25): \r\n [rs[k],xs[k+1]] = mdac(xs[k],th25,re25,ga25)\r\n cumgain *= 4 \r\n rs[k] = rs[k]/cumgain \r\n \r\n # We finish with the one-bit stage \r\n k=Nstage-1 \r\n rs[k] = quant(xs[k],[0]) \r\n cumgain = cumgain*1 \r\n rs[k] = rs[k]/cumgain \r\n \r\n # output scale \r\n b = np.sum(rs)*cumgain \r\n return b\r\n\r\n# 2.5 Bit Stages followed by a final 1 Bit stage\r\ndef pipe25bNonid(x,N25): \r\n eps = 0.07 # comparator offset\r\n \r\n # So we also need the thresholds and gains of the 2.5-bit MDAC: \r\n re25 = np.arange( -6/16, 6/16+0.01, 1/8 ) \r\n th25 = np.convolve( re25, np.array([1/2,1/2]) )[1:-1] \r\n ga25 = 4.0\r\n \r\n th25 = th25 + eps\r\n\r\n # The total number of stages is now \r\n Nstage = N25+1\r\n\r\n xs = np.zeros(Nstage) \r\n xs[0] = x \r\n rs = np.zeros(Nstage) \r\n cumgain = 1 \r\n\r\n # First the 2.5-bit stages. \r\n for k in np.arange(N25): \r\n [rs[k],xs[k+1]] = mdac(xs[k],th25,re25,ga25)\r\n cumgain *= 4 \r\n rs[k] = rs[k]/cumgain \r\n \r\n # We finish with the one-bit stage \r\n k=Nstage-1 \r\n rs[k] = quant(xs[k],[0]) \r\n cumgain = cumgain*1 \r\n rs[k] = rs[k]/cumgain \r\n \r\n # output scale \r\n b = np.sum(rs)*cumgain \r\n return b\r\n\r\n# 2.5 Bit Stages followed by a final 1 Bit stage\r\n# Nonid - by Simon\r\ndef pipe25bNonid_vs(x,N25, offset):\r\n eps = offset # threshold offset\r\n re25 = np.arange( -6/16, 6/16+0.01, 1/8 ) \r\n th25 = np.convolve( re25, np.array([1/2,1/2]) )[1:-1] \r\n ga25 = 4.0\r\n # ------ INPUT HERE ------\r\n th25[3] = th25[3] + eps\r\n # ------\r\n # The total number of stages is now \r\n Nstage = N25+1\r\n\r\n xs = np.zeros(Nstage) \r\n xs[0] = x \r\n rs = np.zeros(Nstage) \r\n cumgain = 1 \r\n\r\n # First the 2.5-bit stages. \r\n for k in np.arange(N25): \r\n [rs[k],xs[k+1]] = mdac(xs[k],th25,re25,ga25)\r\n cumgain *= 4 \r\n rs[k] = rs[k]/cumgain \r\n \r\n # We finish with the one-bit stage \r\n k=Nstage-1 \r\n rs[k] = quant(xs[k],[0]) \r\n cumgain = cumgain*1 \r\n rs[k] = rs[k]/cumgain \r\n \r\n # output scale \r\n b = np.sum(rs)*cumgain \r\n return b\r\n\r\n# DAC \r\n# dacA(0, 16) = -0.49999237060546875\r\n# dacA(0, 2**16-1) = 0.5\r\ndef dacA(b, Nbit): \r\n # This is the correct DAC for an ideal Nbit ADC \r\n # The full range is 2**Nbit steps, 0 is -0.5+LSB/2, 15 is +0.5-LSB/2, so: \r\n y = -0.5 + b/2**Nbit + 1/2**(Nbit+1) \r\n return y \r\n\r\ndef pipe35(x, Nstage):\r\n re35 = np.arange( -14/32 , 14/32+0.01, 1/16 )\r\n th35 = np.convolve(re35, np.array([1/2,1/2]) )[1:-1] \r\n ga35 = 8\r\n \r\n xs = np.zeros(Nstage) \r\n xs[0] = x \r\n rs = np.zeros(Nstage) \r\n cumgain = 1 \r\n # All but the last stage are 1.5-bit-stages: \r\n for k in np.arange(Nstage-1): \r\n # Use the appropriate MDAC: \r\n [rs[k],xs[k+1]] = mdac(xs[k],th35,re35,ga35) \r\n # The cumulative gain is multiplied by the gain of the stage: \r\n cumgain *= 8\r\n # The region is then scaled by 1/cumgain; therefore the first stage \r\n # just ouputs its region number divided by its gain. \r\n rs[k] = rs[k]/cumgain \r\n \r\n # The last stage is a normal 1-bit stage with a gain of 1\r\n k=Nstage-1 \r\n rs[k] = quant(xs[k],[0]) \r\n cumgain = cumgain*1 \r\n rs[k] = rs[k]/cumgain \r\n \r\n # The output of the ADC is the sum of all region numbers, but if we want \r\n # integers, they need to be scaled back by cumgain. \r\n b = np.sum(rs)*cumgain \r\n return b\r\n\r\ndef pipe35Nonid(x, Nstage):\r\n re35 = np.arange( -14/32 , 14/32+0.01, 1/16 )\r\n th35 = np.convolve(re35, np.array([1/2,1/2]) )[1:-1] \r\n ga35 = 8\r\n th35[4] += 1/32*1.1\r\n \r\n xs = np.zeros(Nstage) \r\n xs[0] = x \r\n rs = np.zeros(Nstage) \r\n cumgain = 1 \r\n # All but the last stage are 1.5-bit-stages: \r\n for k in np.arange(Nstage-1): \r\n # Use the appropriate MDAC: \r\n [rs[k],xs[k+1]] = mdac(xs[k],th35,re35,ga35) \r\n # The cumulative gain is multiplied by the gain of the stage: \r\n cumgain *= 8\r\n # The region is then scaled by 1/cumgain; therefore the first stage \r\n # just ouputs its region number divided by its gain. \r\n rs[k] = rs[k]/cumgain \r\n \r\n # The last stage is a normal 1-bit stage with a gain of 1\r\n k=Nstage-1 \r\n rs[k] = quant(xs[k],[0]) \r\n cumgain = cumgain*1 \r\n rs[k] = rs[k]/cumgain \r\n \r\n # The output of the ADC is the sum of all region numbers, but if we want \r\n # integers, they need to be scaled back by cumgain. \r\n b = np.sum(rs)*cumgain \r\n return b\r\n \r\n\r\n#%% EXAM QUESTIONS BELOW\r\n\r\n#%%\r\n# Test 3.5Bit MDAC\r\n\r\neps = 0.04 # comparator offset\r\n\r\nre35 = np.arange( -14/32 , 14/32+0.01, 1/16 )\r\nth35 = np.convolve(re35, np.array([1/2,1/2]) )[1:-1] \r\nga35 = 8\r\n \r\nvi = np.arange(0,1.0001,0.0001)-0.5\r\nmo = np.array( [ mdac(x,th35,re35,ga35) for x in vi] ) \r\n\r\nfig,ax1 = plt.subplots()\r\npcolor = 'tab:red'\r\nax1.set_title('Figure 17.20 - a 1.5-bit pipelined converter stage')\r\nax1.set_xlabel('MDAC input voltage')\r\nax1.set_ylabel('MDAC digital value', color=pcolor)\r\nax1.plot(vi, mo[:,0], color=pcolor)\r\nax1.tick_params(axis='y', labelcolor=pcolor) \r\nax1.grid(axis='x')\r\n\r\nax2 = ax1.twinx()\r\npcolor = 'tab:blue'\r\nax2.set_ylabel('MDAC output voltage', color=pcolor) # we already handled the x-label with ax1\r\nax2.plot(vi, mo[:,1], color=pcolor)\r\nax2.tick_params(axis='y', labelcolor=pcolor)\r\nax2.grid()\r\n\r\nfig.tight_layout() # otherwise the right y-label is slightly clipped\r\nplt.show()\r\n\r\n#%%\r\n# Test 3.5Bit MDAC - NONIDEAL - with offset\r\n\r\noffs = 2/32*0.9 # comparator offset\r\n# 10% less offset has still a monotonic behaviour\r\noffs = 2/32\r\n# 2/32 offset produces missing codes <== Indicator for offset too large\r\n\r\nre35 = np.arange( -14/32 , 14/32+0.01, 1/16 )\r\nth35 = np.convolve(re35, np.array([1/2,1/2]) )[1:-1] \r\nga35 = 8\r\nth35[5] = th35[5] + offs\r\n \r\nvi = np.arange(0,1.0001,0.0001)-0.5\r\nmo = np.array( [ mdac(x,th35,re35,ga35) for x in vi] ) \r\n\r\nfig,ax1 = plt.subplots()\r\npcolor = 'tab:red'\r\nax1.set_title('Figure 17.20 - a 1.5-bit pipelined converter stage')\r\nax1.set_xlabel('MDAC input voltage')\r\nax1.set_ylabel('MDAC digital value', color=pcolor)\r\nax1.plot(vi, mo[:,0], color=pcolor)\r\nax1.tick_params(axis='y', labelcolor=pcolor) \r\nax1.grid(axis='x')\r\n\r\nax2 = ax1.twinx()\r\npcolor = 'tab:blue'\r\nax2.set_ylabel('MDAC output voltage', color=pcolor) # we already handled the x-label with ax1\r\nax2.plot(vi, mo[:,1], color=pcolor)\r\nax2.tick_params(axis='y', labelcolor=pcolor)\r\nax2.grid()\r\n\r\nfig.tight_layout() # otherwise the right y-label is slightly clipped\r\nplt.show()\r\n\r\n\r\n\r\n#%%\r\n# compare 3.5 bit ADC with one that has offset\r\n# does not work. some gain is wrong\r\n\r\nNbits = 13\r\nNstages = 4\r\n\r\nvi = np.arange(0,1.0001,0.0001)-0.5 \r\n\r\nro = np.array([ pipe35(x,Nstages) for x in vi ])\r\nvo = np.array( [ dacA(b,Nbits) for b in ro ] )\r\n\r\nroni = np.array([ pipe35Nonid(x,Nstages) for x in vi ])\r\nvoni = np.array( [ dacA(b,Nbits) for b in roni ] )\r\n\r\n# Diagnostic output\r\nprint('This is a %d-bit converter.'%(Nbits))\r\nprint('The five smallest an five largest numbers in the output vector are:')\r\nprint(np.unique(ro)[[0,1,2,3,4,-5,-4,-3,-2,-1]] )\r\nprint('If all is well, these numbers should be bounded by',([0,2**Nbits-1])) \r\nprint(np.unique(roni)[[0,1,2,3,4,-5,-4,-3,-2,-1]] )\r\nprint('If all is well, these numbers should be bounded by',([0,2**Nbits-1])) \r\n\r\nfig,ax1 = plt.subplots()\r\n\r\npcolor = 'tab:orange'\r\nax1.plot(vi, vo, color=pcolor)\r\npcolor = 'tab:red'\r\nax1.set_xlabel('ADC input voltage')\r\nax1.set_ylabel('ADC input and DAC ouput voltage', color=pcolor)\r\nax1.plot(vi, vi, color=pcolor)\r\nax1.plot(vi, voni, color=pcolor) \r\nax1.tick_params(axis='y', labelcolor=pcolor) \r\n\r\nax2 = ax1.twinx()\r\npcolor = 'tab:cyan'\r\nax2.plot(vi, (voni-vi)*2**Nbits, color=pcolor)\r\npcolor = 'tab:blue'\r\nax2.set_ylabel('Quantization error in LSB', color=pcolor) # we already handled the x-label with ax1\r\nax2.plot(vi, (voni-vi)*2**Nbits, color=pcolor)\r\nax2.tick_params(axis='y', labelcolor=pcolor)\r\nax2.set_ylim(-8,8) \r\nplt.grid()\r\n\r\nfig.tight_layout() # otherwise the right y-label is slightly clipped\r\nplt.show()\r\n\r\n#%%\r\n# use 6 x 2.5bit instead\r\n# I still don't see anything happening even with large offsets\r\n# plotting wrong?\r\n\r\noffset = 8/16\r\nNbits = 13 # only odd numbers\r\nN25 = int((Nbits-1)/2)\r\n\r\nvi = np.arange(0,1.0001,0.0001)-0.5 \r\n\r\nro25 = np.array( [ pipe25b(x,N25) for x in vi ] ) \r\nvo25 = np.array( [ dacA(b,Nbits) for b in ro25 ] ) \r\n\r\n# NONIDEAL\r\nro25ni = np.array( [ pipe25bNonid_vs(x,N25,offset) for x in vi ] ) \r\nvo25ni = np.array( [ dacA(b,Nbits) for b in ro25 ] ) \r\n\r\n# Diagnostic output\r\nprint('This is a %d-bit converter.'%(Nbits))\r\nprint('The five smallest an five largest numbers in the output vector are:')\r\nprint(np.unique(ro25)[[0,1,2,3,4,-5,-4,-3,-2,-1]] )\r\nprint('If all is well, these numbers should be bounded by',([0,2**Nbits-1])) \r\nprint(np.unique(ro25ni)[[0,1,2,3,4,-5,-4,-3,-2,-1]] )\r\nprint('If all is well, these numbers should be bounded by',([0,2**Nbits-1])) \r\n\r\nfig,ax1 = plt.subplots()\r\n\r\npcolor = 'tab:orange'\r\nax1.plot(vi, vo25, color=pcolor)\r\npcolor = 'tab:red'\r\nax1.set_xlabel('ADC input voltage')\r\nax1.set_ylabel('ADC input and DAC ouput voltage', color=pcolor)\r\nax1.plot(vi, vi, color=pcolor)\r\nax1.plot(vi, vo25ni, color=pcolor) \r\nax1.tick_params(axis='y', labelcolor=pcolor) \r\n\r\nax2 = ax1.twinx()\r\npcolor = 'tab:cyan'\r\nax2.plot(vi, (vo25ni-vi)*2**Nbits, color=pcolor)\r\npcolor = 'tab:blue'\r\nax2.set_ylabel('Quantization error in LSB', color=pcolor) # we already handled the x-label with ax1\r\nax2.plot(vi, (vo25ni-vi)*2**Nbits, color=pcolor)\r\nax2.tick_params(axis='y', labelcolor=pcolor)\r\nax2.set_ylim(-8,8) \r\nplt.grid()\r\n\r\n\r\n\r\n\r\n\r\n" ]
[ [ "numpy.unique", "numpy.arange", "matplotlib.pyplot.subplots", "numpy.concatenate", "matplotlib.pyplot.grid", "numpy.array", "matplotlib.pyplot.show", "numpy.zeros", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ziqi-zhang/fse20
[ "f3998abda2e40d67989ec113340236f3460f0dc3", "f3998abda2e40d67989ec113340236f3460f0dc3", "f3998abda2e40d67989ec113340236f3460f0dc3" ]
[ "submissions/available/NNSlicer/NNSlicer/eval/generate_adv_resnet10cifar10.py", "submissions/available/NNSlicer/protection/knockoff/victim/blackbox.py", "submissions/available/NNSlicer/finetune/knockoff/prune/post_process/cmp_subset_acc.py" ]
[ "from functools import partial\nfrom pdb import set_trace as st\nimport tensorflow as tf\nimport numpy as np\nimport random\n\nfrom foolbox.attacks import (\n FGSM,\n DeepFoolAttack,\n DeepFoolLinfinityAttack,\n DeepFoolL2Attack,\n IterativeGradientSignAttack,\n SaliencyMapAttack,\n RandomPGD,\n CarliniWagnerL2Attack,\n ADefAttack,\n SinglePixelAttack,\n LocalSearchAttack,\n ApproximateLBFGSAttack,\n BoundaryAttack,\n SpatialAttack,\n PointwiseAttack,\n GaussianBlurAttack,\n)\n\nimport nninst_mode as mode\nfrom dataset import mnist\nfrom dataset.mnist_transforms import *\n# from nninst.backend.tensorflow.dataset.imagenet_preprocessing import _CHANNEL_MEANS\nfrom nninst_utils.ray import ray_init\n\n# from .adversarial_patch_attack import (\n# new_patch_generate_adversarial_example,\n# patch_generate_adversarial_example,\n# )\nfrom .common import (\n lenet_mnist_example,\n resnet10_cifar10_example,\n # alexnet_imagenet_example,\n generate_examples,\n # resnet_50_imagenet_example,\n # vgg_16_imagenet_example,\n)\nfrom .cw_attack import cw_generate_adversarial_example\nfrom .cw_attacks import CarliniL2\nfrom .foolbox_attack import foolbox_generate_adversarial_example, random_targeted\nfrom .foolbox_attacks.fgsm import TargetedFGSM, TargetedIterativeFGSM\n# from .random_attack import RandomAttack, generate_negative_example\n\nclass_num = 10\nimages_per_class = 100\n# Use what dataset to generate adv examples\ncifar_dataset_mode = \"test\"\n\nnum_gpus = 0.2\n\nmodel_label = \"dropout\"\nmodel_dir = f\"result/resnet10cifar10/model_{model_label}\"\n\n\ndef generate_cifar10_examples():\n \n \n for generate_adversarial_fn, attack_name, attack_fn, attack_params in [\n [foolbox_generate_adversarial_example, \"original\", None, \n {}\n ],\n [foolbox_generate_adversarial_example, \"FGSM_2\", FGSM, \n {\"epsilons\": [2/255]}\n ],\n [foolbox_generate_adversarial_example, \"FGSM_4\", FGSM, \n {\"epsilons\": [4/255]}\n ],\n [foolbox_generate_adversarial_example, \"FGSM_8\", FGSM, \n {\"epsilons\": [8/255],}\n ],\n [foolbox_generate_adversarial_example, \"FGSM_16\", FGSM, \n {\"epsilons\": [16/255],}\n ],\n \n [foolbox_generate_adversarial_example, \"DeepFoolLinf\", DeepFoolLinfinityAttack,\n {}],\n [foolbox_generate_adversarial_example, \"DeepFoolL2\", DeepFoolL2Attack,\n {}],\n \n [foolbox_generate_adversarial_example, \"JSMA\", SaliencyMapAttack,\n {\"max_iter\": 100}],\n \n [foolbox_generate_adversarial_example, \"BIM_2\", IterativeGradientSignAttack,\n {\"epsilons\": [2/255], \"steps\": 10}],\n [foolbox_generate_adversarial_example, \"BIM_4\", IterativeGradientSignAttack,\n {\"epsilons\": [4/255], \"steps\": 10}],\n [foolbox_generate_adversarial_example, \"BIM_8\", IterativeGradientSignAttack,\n {\"epsilons\": [8/255], \"steps\": 10}],\n [foolbox_generate_adversarial_example, \"BIM_16\", IterativeGradientSignAttack,\n {\"epsilons\": [16/255], \"steps\": 10}],\n \n # [foolbox_generate_adversarial_example, \"RPGD_2\", RandomPGD,\n # {\"iterations\": 10, \"epsilon\": 2/255, \"binary_search\": False}],\n [foolbox_generate_adversarial_example, \"RPGD_4\", RandomPGD,\n {\"iterations\": 10, \"epsilon\": 4/255, \"binary_search\": False}],\n [foolbox_generate_adversarial_example, \"RPGD_8\", RandomPGD,\n {\"iterations\": 10, \"epsilon\": 8/255, \"binary_search\": False}],\n [foolbox_generate_adversarial_example, \"RPGD_16\", RandomPGD,\n {\"iterations\": 10, \"epsilon\": 16/255, \"binary_search\": False}],\n \n [foolbox_generate_adversarial_example, \"CWL2\", CarliniWagnerL2Attack, \n {\"max_iterations\": 200}],\n [foolbox_generate_adversarial_example, \"ADef\", ADefAttack, \n {}],\n \n # [foolbox_generate_adversarial_example, \"SinglePixel\", SinglePixelAttack, \n # {}],\n [foolbox_generate_adversarial_example, \"LocalSearch\", LocalSearchAttack, \n {}],\n # Too slow\n # [foolbox_generate_adversarial_example, \"ApproxLBFGS\", ApproximateLBFGSAttack, \n # {}],\n \n [foolbox_generate_adversarial_example, \"Boundary\", BoundaryAttack, \n {}],\n [foolbox_generate_adversarial_example, \"Spatial\", SpatialAttack, \n {}],\n [foolbox_generate_adversarial_example, \"Pointwise\", PointwiseAttack, \n {}],\n [foolbox_generate_adversarial_example, \"GaussianBlur\", GaussianBlurAttack, \n {}],\n ]:\n generate_adversarial_fn = partial(\n generate_adversarial_fn,\n attack_params=attack_params,\n )\n example_fn = partial(\n resnet10_cifar10_example,\n model_dir=model_dir,\n dataset_mode = cifar_dataset_mode,\n generate_adversarial_fn=generate_adversarial_fn,\n attack_fn = attack_fn,\n )\n\n class_ids = range(class_num)\n image_ids = range(images_per_class)\n arch_args = dict(\n channel_axis=3,\n preprocessing=(0, 1),\n bounds=( 0, 1),\n )\n\n generate_examples(\n example_fn=example_fn,\n class_ids=class_ids,\n image_ids=image_ids,\n attack_name=attack_name,\n transforms = None,\n transform_name = \"noop\",\n num_gpus=num_gpus,\n **arch_args,\n )\n\n\nif __name__ == \"__main__\":\n # mode.debug()\n mode.local()\n ray_init(\n log_to_driver=False\n )\n\n tf.set_random_seed(3)\n np.random.seed(3)\n random.seed(3)\n\n # generate_mnist_examples()\n \n # images_per_class, cifar_dataset_mode = 10, \"train\"\n # generate_cifar10_examples()\n\n generate_cifar10_examples()\n", "#!/usr/bin/python\n\"\"\"This is a short description.\nReplace this with a more detailed description of what this file contains.\n\"\"\"\nimport argparse\nimport os.path as osp\nimport os\nimport json\nfrom pdb import set_trace as st\nimport numpy as np\n\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom knockoff.utils.type_checks import TypeCheck\nimport knockoff.utils.model as model_utils\nimport knockoff.models.zoo as zoo\nfrom knockoff import datasets\n\n__author__ = \"Tribhuvanesh Orekondy\"\n__maintainer__ = \"Tribhuvanesh Orekondy\"\n__email__ = \"[email protected]\"\n__status__ = \"Development\"\n\n\nclass Blackbox(object):\n def __init__(self, model, device=None, output_type='probs', topk=None, rounding=None):\n self.device = torch.device('cuda') if device is None else device\n self.output_type = output_type\n self.topk = topk\n self.rounding = rounding\n\n # self.__model = model.to(device)\n self.__model = model.cuda()\n self.output_type = output_type\n self.__model.eval()\n\n self.__call_count = 0\n\n @classmethod\n def from_modeldir(cls, model_dir, device=None, output_type='probs'):\n device = torch.device('cuda') if device is None else device\n\n # What was the model architecture used by this model?\n params_path = osp.join(model_dir, 'params.json')\n with open(params_path) as jf:\n params = json.load(jf)\n model_arch = params['model_arch']\n num_classes = params['num_classes']\n victim_dataset = params.get('dataset', 'imagenet')\n modelfamily = datasets.dataset_to_modelfamily[victim_dataset]\n\n # Instantiate the model\n # model = model_utils.get_net(model_arch, n_output_classes=num_classes)\n model = zoo.get_net(model_arch, modelfamily, pretrained=None, num_classes=num_classes)\n # model = model.to(device)\n model = model.cuda()\n\n # Load weights\n checkpoint_path = osp.join(model_dir, 'model_best.pth.tar')\n if not osp.exists(checkpoint_path):\n checkpoint_path = osp.join(model_dir, 'checkpoint.pth.tar')\n print(\"=> loading checkpoint '{}'\".format(checkpoint_path))\n checkpoint = torch.load(checkpoint_path)\n epoch = checkpoint['epoch']\n best_test_acc = checkpoint['best_acc']\n # best_test_acc = checkpoint['best_prec']\n model.load_state_dict(checkpoint['state_dict'])\n # print(model.last_linear.bias, model.last_linear.weight)\n print(\"=> loaded checkpoint (epoch {}, acc={:.2f})\".format(epoch, best_test_acc))\n\n blackbox = cls(model, device, output_type)\n return blackbox\n\n def truncate_output(self, y_t_probs):\n if self.topk is not None:\n # Zero-out everything except the top-k predictions\n topk_vals, indices = torch.topk(y_t_probs, self.topk)\n newy = torch.zeros_like(y_t_probs)\n if self.rounding == 0:\n # argmax prediction\n newy = newy.scatter(1, indices, torch.ones_like(topk_vals))\n else:\n newy = newy.scatter(1, indices, topk_vals)\n y_t_probs = newy\n\n # Rounding of decimals\n if self.rounding is not None:\n y_t_probs = torch.Tensor(np.round(y_t_probs.numpy(), decimals=self.rounding))\n\n return y_t_probs\n\n def __call__(self, query_input):\n TypeCheck.multiple_image_blackbox_input_tensor(query_input)\n\n with torch.no_grad():\n query_input = query_input.to(self.device)\n query_output = self.__model(query_input)\n self.__call_count += query_input.shape[0]\n\n query_output_probs = F.softmax(query_output, dim=1).cpu()\n\n query_output_probs = self.truncate_output(query_output_probs)\n return query_output_probs\n", "import os, sys\nimport numpy as np\nfrom pdb import set_trace as st\nimport pandas as pd\n\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib import axes\nimport matplotlib.ticker as ticker\n\ndir = f\"models/prune/f1score_avg/allprune_subset_0.05\"\nmodes = [\n \"posneg_small\",\n \"posonly_small\",\n]\n\nfig_dir = os.path.join(dir, \"fig\")\nos.makedirs(fig_dir, exist_ok=True)\n\ndef load_csv(filename):\n path = os.path.join(dir, filename)\n return pd.read_csv(path, index_col=0)\n\ndef draw_by_ratio():\n subdir = \"ratio_line\"\n fig_subdir = os.path.join(fig_dir, subdir)\n os.makedirs(fig_subdir, exist_ok=True)\n \n for combination_number in range(2, 10):\n subset_dir = os.path.join(fig_subdir, f\"subset_{combination_number}\")\n os.makedirs(subset_dir, exist_ok=True)\n # All trace on each class\n df = load_csv(f\"allconv_subset_{combination_number}.csv\")\n \n for class_ids in np.unique(df[\"classes\"]):\n exp_df = df[df[\"classes\"] == class_ids]\n \n posneg_all = exp_df[\"posnegweight_small_all\"].to_list()\n posneg_subset = exp_df[\"posnegweight_small_subset\"].to_list()\n edge = exp_df[\"edgeweight_small\"].to_list()\n edge_avg = exp_df[\"edgeweight_small_avg\"].to_list()\n random = exp_df[\"randomweight_small\"].to_list()\n ratio = exp_df[\"ratio\"].to_list()\n index = list(range(len(ratio)))\n \n fig, ax = plt.subplots(figsize=(8,6))\n colormap = plt.cm.Paired\n \n # with plt.style.context('fivethirtyeight'):\n # plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9, 5)])\n plt.plot(ratio, posneg_subset, label=\"NNSlicer (Subset)\",\n marker='*', linestyle='--')\n plt.plot(ratio, posneg_all, label=\"NNSlicer (All Dataset)\",\n marker='.', linestyle='-')\n plt.plot(ratio, edge, label=\"Weight\",\n marker='v', linestyle=None)\n plt.plot(ratio, edge_avg, label=\"Weight (Profiling)\",\n marker='o', linestyle=':')\n plt.plot(ratio, random, label=\"Random\",\n marker='d', linestyle='-.')\n \n ax.set_ylabel(\"Accuracy on Subset\")\n ax.set_xlabel(\"Prune Ratio\")\n ax.set_title(f\"Prune Performance on Subset of class {class_ids}\")\n # labels = [f\"{r:.1f}\" for r in ratio]\n # ax.set_xticklabels(labels)\n plt.ylim(0, 100)\n plt.legend(loc=\"lower left\", ncol=1)\n \n fig_name = f\"subset_{class_ids}.pdf\"\n fig_path = os.path.join(subset_dir, fig_name)\n plt.savefig(fig_path)\n plt.clf()\n \n \n \ndef draw_by_subset():\n subdir = \"subset_hist\"\n fig_subdir = os.path.join(fig_dir, subdir)\n os.makedirs(fig_subdir, exist_ok=True)\n \n for combination_number in range(2, 10):\n # All trace on each class\n df = load_csv(f\"allconv_subset_{combination_number}.csv\")\n \n for ratio in np.unique(df[\"ratio\"]):\n subset_dir = os.path.join(fig_subdir, f\"subset_{combination_number}\",\n f\"ratio={ratio:.2f}\")\n os.makedirs(subset_dir, exist_ok=True)\n \n ratio_df = df[df[\"ratio\"] == ratio]\n subsets = np.unique(df[\"classes\"])\n subset_per_image = 10\n for i, idx in enumerate(range(0, len(subsets), subset_per_image)):\n fig_subset = list(subsets[idx:min(len(subsets), idx+subset_per_image)])\n \n fig_df = []\n for classes in fig_subset:\n fig_df.append( ratio_df[ratio_df[\"classes\"] == classes])\n fig_df = pd.concat(fig_df)\n \n posneg_subset = fig_df[\"posnegweight_small_subset\"].to_list()\n posneg_all = fig_df[\"posnegweight_small_all\"].to_list()\n edge = fig_df[\"edgeweight_small\"].to_list()\n edge_avg = fig_df[\"edgeweight_small_avg\"].to_list()\n random = fig_df[\"randomweight_small\"].to_list()\n ratio = fig_df[\"ratio\"].to_list()\n index = list(range(len(fig_subset)))\n index = [2*j for j in index]\n \n fig, ax = plt.subplots(figsize=(8,6))\n width = 0.3\n posneg_rect = plt.bar(left=index, height=posneg_subset, \n width=width, label=\"NNSlicer (Subset)\")\n weight_rect = plt.bar(left=[i + width for i in index], height=posneg_all, \n width=width, label=\"NNSlicer (All Dataset)\")\n weight_avg_rect = plt.bar(left=[i + 2*width for i in index], height=edge, \n width=width, label=\"Weight\")\n channel_rect = plt.bar(left=[i + 3*width for i in index], height=edge_avg, \n width=width, label=\"Weight (Profiling)\")\n random_rect = plt.bar(left=[i + 4*width for i in index], height=random, \n width=width, label=\"Random\")\n \n ax.set_ylabel(\"Accuracy on Subset\")\n ax.set_xlabel(\"Subset\")\n ax.set_title(\"Prune Performance on Subset\")\n ax.set_xticks([p + 2 * width for p in index])\n labels = fig_subset\n ax.set_xticklabels(labels)\n plt.ylim(0, 100)\n \n plt.legend(loc=\"lower left\", ncol=1)\n \n fig_name = f\"subset_acc_{i}.pdf\"\n fig_path = os.path.join(subset_dir, fig_name)\n plt.savefig(fig_path)\n plt.clf()\n\ndef draw_by_subset_alldataset():\n subdir = \"subset_hist\"\n fig_subdir = os.path.join(fig_dir, \"subset_hist\", \"subset_mean\")\n os.makedirs(fig_subdir, exist_ok=True)\n \n all_df = []\n for combination_number in range(2, 10):\n # All trace on each class\n df = load_csv(f\"allconv_subset_{combination_number}.csv\")\n df[\"combination\"] = combination_number\n all_df.append(df)\n all_df = pd.concat(all_df)\n \n \n for ratio in np.unique(all_df[\"ratio\"]):\n df = all_df[all_df[\"ratio\"] == ratio]\n \n com_df = []\n for combination_number in np.unique(df[\"combination\"]):\n com_df.append(df[df[\"combination\"] == combination_number].mean().to_frame().transpose())\n com_df = pd.concat(com_df)\n \n posneg_subset = com_df[\"posnegweight_small_subset\"].to_list()\n posneg_all = com_df[\"posnegweight_small_all\"].to_list()\n edge = com_df[\"edgeweight_small\"].to_list()\n edge_avg = com_df[\"edgeweight_small_avg\"].to_list()\n random = com_df[\"randomweight_small\"].to_list()\n subset_size = com_df[\"combination\"].astype(int).to_list()\n index = list(range(len(subset_size)))\n index = [2*j for j in index]\n \n fig, ax = plt.subplots(figsize=(8,6))\n width = 0.3\n posneg_rect = plt.bar(left=index, height=posneg_subset, \n width=width, label=\"NNSlicer (Subset)\")\n weight_rect = plt.bar(left=[i + width for i in index], height=posneg_all, \n width=width, label=\"NNSlicer (All Dataset)\")\n weight_avg_rect = plt.bar(left=[i + 2*width for i in index], height=edge, \n width=width, label=\"Weight\")\n channel_rect = plt.bar(left=[i + 3*width for i in index], height=edge_avg, \n width=width, label=\"Weight (Profiling)\")\n random_rect = plt.bar(left=[i + 4*width for i in index], height=random, \n width=width, label=\"Random\")\n \n ax.set_ylabel(\"Mean Accuracy on Subset\")\n ax.set_xlabel(\"Subset Size\")\n ax.set_title(\"Mean Accuracy on Each Subset Size\")\n ax.set_xticks([p + 2 * width for p in index])\n labels = subset_size\n ax.set_xticklabels(labels)\n plt.ylim(0, 100)\n \n plt.legend(loc=\"lower left\", ncol=1)\n \n fig_name = f\"subset_ratio{ratio:.2f}.pdf\"\n fig_path = os.path.join(fig_subdir, fig_name)\n plt.savefig(fig_path)\n plt.clf()\n \n \n \n \ndraw_by_ratio()\ndraw_by_subset()\ndraw_by_subset_alldataset()" ]
[ [ "tensorflow.set_random_seed", "numpy.random.seed" ], [ "torch.nn.functional.softmax", "torch.load", "torch.topk", "torch.zeros_like", "torch.no_grad", "torch.device", "torch.ones_like" ], [ "matplotlib.pyplot.legend", "pandas.concat", "pandas.read_csv", "numpy.unique", "matplotlib.use", "matplotlib.pyplot.ylim", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "matplotlib.pyplot.clf", "matplotlib.pyplot.bar" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
Emilurenius/RGB-controller
[ "17816b81041406761bad9531c15fda000cd8f99d" ]
[ "externalControl/MonitorColorScanner.py" ]
[ "# This code is made to run on the user's computer. Not on the server unit\n\nimport numpy as np, requests, time\nfrom PIL import ImageGrab\n\ndef timePrint(printVal, newLine=False):\n if newLine:\n print(\"\\n\")\n currentTime = time.strftime(\"%H:%M:%S\", time.localtime())\n print(f\"{currentTime}: {printVal}\")\n\ndef getAverageRGB(colors):\n average = [0, 0, 0]\n count = 0\n for color in colors:\n count += 1\n average[0] += color[0]\n average[1] += color[1]\n average[2] += color[2]\n\n return [int(average[0]/count), int(average[1]/count), int(average[2]/count)]\n\nprint(\"Please give a speed/presicion modifier value:\")\nstep = int(input(\"Higher value = higher speed, Lower value = more presicion: \")) # How many pixels to skip in both x and y direction when sampling colors\nxPixels = 1344 # Number of pixels in the x direction of the checked area\nyPixels = 756 # Number of pixels in the y direction of the checked area\noldAverage = [0, 0, 0] # Initializing a check variable\nserverAddress = \"http://172.16.4.195:3000\" # Address for the main server that controls all info about the LED strip\n\nwhile True: # Main script loop\n if requests.get(f\"{serverAddress}/modes/current\") != \"screenSync\": # Check if the LED strip is currently in the right mode\n requests.get(f\"{serverAddress}/modes/set?mode=screenSync\") # Change the mode if it is wrong\n\n img = ImageGrab.grab(bbox=(192, 108, 1536, 864)) # Take a screenshot of the screen for processing\n imgNP = np.array(img) # Turn the image into a numPy array of all RGB values for easier processing\n\n imArr = np.frombuffer(img.tobytes(), dtype=np.uint8) # Encode image as bytes\n imArr = imArr.reshape((img.size[1], img.size[0], 3)) # reshape encoded image\n pixelArray = [] # Initiate an empty list for saving all pixels that will be analyzed\n\n for y in range(0, yPixels, step): # Iterate through all pixels in the y direction, skipping the amount specified in step for every iteration\n for x in range(0, xPixels, step): # Iterate through all pixels in the x direction, skipping the amount specified in step for every iteration\n px = imArr[y][x] # Grab pixel at current x and y coordinates\n\n # if px[0] != 0 and px[1] != 0 and px[2] != 0:\n # pixelArray.append([px[0], px[1], px[2]]) # Add the color if it is not complete black\n pixelArray.append([px[0], px[1], px[2]])\n\n averageRGB = getAverageRGB(pixelArray) # Get most frequent color in list\n diffR = averageRGB[0] - oldAverage[0]\n diffG = averageRGB[1] - oldAverage[1]\n diffB = averageRGB[2] - oldAverage[2]\n if diffR < -1 or diffR > 1 or diffG < -1 or diffG > 1 or diffB < -1 or diffB > 1: # Check if difference is over one\n timePrint(averageRGB)\n oldAverage = averageRGB\n requests.get(f\"{serverAddress}/rgb?br=1000&r={averageRGB[0]}&g={averageRGB[1]}&b={averageRGB[2]}\") # Send the most frequent color to the main server" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MY-Climate-Observatory/myco-data
[ "5203fa63c7ce609bbc9bbc4186f55da78befdc50" ]
[ "CLIMATExScience/air-pollution-index/data-cleaning/version-update-3.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\n13 July 2020\nAuthor: Xiandi Ooi\n\nDataset version update 03\n \nAdding newly released datasets.\n\n\"\"\"\n\nimport pandas as pd\n\n# Adding the new datasets released in June 2020\ndf = pd.read_csv(r\"filepath\\Aggregate-API.csv\", sep = \";\")\ndf1 = pd.read_csv(r\"filepath\\API_Melaka_2019_cleaned.csv\")\ndf2 = pd.read_csv(r\"filepath\\API_NS_2019_cleaned.csv\")\ndf3 = pd.read_csv(r\"filepath\\API_Pahang_2019_cleaned.csv\")\ndf4 = pd.read_csv(r\"filepath\\API_Penang_2019_cleaned.csv\")\ndf5 = pd.read_csv(r\"filepath\\API_Perak_2019_cleaned.csv\")\ndf6 = pd.read_csv(r\"filepath\\API_Perlis_2019_cleaned.csv\")\ndf7 = pd.read_csv(r\"filepath\\API_Sabah_2019_cleaned.csv\")\ndf8 = pd.read_csv(r\"filepath\\API_Sarawak_2019_cleaned.csv\")\ndf9 = pd.read_csv(r\"filepath\\API_Terengganu_2019_cleaned.csv\")\n\ndf_total = pd.concat([df, df1, df2, df3, df4, df5, df6, df7, df8, df9])\ndf_total = df_total.drop(columns = [\"Unnamed: 0\"])\n\n# Making sure our df won't have the column \"Unnamed:0\" when we load it again\n# Also changing the way we name the dataset to reflect changes\ndf_total.to_csv(r\"filepath\\api-20200713.csv\", sep = \";\", index = False)\n" ]
[ [ "pandas.concat", "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
KingJoySaiy/genderClassification
[ "1e518c6c600a9759d196b094998e37337e2de624", "1e518c6c600a9759d196b094998e37337e2de624" ]
[ "History_Edition/5_LeNet5/constant/dataset.py", "myModel/_3LeNet5.py" ]
[ "from torch.utils.data import Dataset\nimport csv\nimport numpy as np\nfrom matplotlib import image\nfrom constant.constPath import *\nimport torch\nimport random\n\n\ndef setSeed(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n\n\ndef readImage(path):\n im = image.imread(path) # (200, 200, 3)\n return np.mean(im, axis=2).reshape((1, imageH, imageW)) # (1, 200, 200)\n\n\n# training data:label (trainSize, 1, 200, 200) (trainSize, 1)\ndef getTrainData():\n # get training id & label\n id = []\n label = []\n reader = csv.reader(open(trainCSV, 'r'))\n next(reader)\n for row in reader:\n id.append(int(row[0]))\n label.append(int(row[1]))\n\n # get matrix of training image\n data = np.zeros((len(id), 1, imageH, imageW))\n ct = 0\n for i in id:\n data[ct] = readImage(trainImage + str(i) + '.jpg')\n ct += 1\n return data, np.array(label).reshape(len(label), 1)\n\n\ndef getIdLabelSet():\n id = []\n label = []\n reader = csv.reader(open(trainCSV, 'r'))\n next(reader)\n for row in reader:\n id.append(int(row[0]))\n label.append(int(row[1]))\n return np.array(id).reshape(len(id)), np.array(label).reshape(len(id))\n\n\ndef getIdSet():\n testId = []\n reader = csv.reader(open(testCSV, 'r'))\n next(reader)\n for row in reader:\n testId.append(int(row[0]))\n return np.array(testId).reshape(len(testId))\n\n\nclass TrainData:\n def __init__(self):\n self.idSet, self.labelSet = getIdLabelSet()\n self.now = 0\n self.trainLen = int(trainBatch * trainPropotion)\n self.len = len(self.idSet)\n\n def shuffle(self):\n newId = list(range(self.len))\n random.shuffle(newId)\n newIdSet = []\n newLabelSet = []\n for i in range(self.len):\n newIdSet.append(self.idSet[newId[i]])\n newLabelSet.append(self.labelSet[newId[i]])\n self.idSet = np.array(newIdSet)\n self.labelSet = np.array(newLabelSet)\n self.now = 0\n\n # train: (trainLen, 1, 200, 200) (trainLen, 1) valid:(batch - trainLen, 1, 200, 200) (batch - trainLen, 1)\n def nextTrainValid(self):\n\n trainData = np.zeros((self.trainLen, 1, imageH, imageW))\n validData = np.zeros((trainBatch - self.trainLen, 1, imageH, imageW))\n\n ct = 0\n for i in self.idSet[self.now:self.now + self.trainLen]:\n trainData[ct] = readImage(trainImage + str(i) + '.jpg')\n ct += 1\n ct = 0\n for i in self.idSet[self.now + self.trainLen:self.now + trainBatch]:\n validData[ct] = readImage(trainImage + str(i) + '.jpg')\n ct += 1\n\n res = trainData, self.labelSet[self.now:self.now + self.trainLen], validData, self.labelSet[\n self.now + self.trainLen:self.now + trainBatch]\n self.now = (self.now + trainBatch) % self.len\n return res\n\n\nclass TestData:\n def __init__(self):\n self.idSet = getIdSet()\n self.now = 0\n self.len = len(self.idSet)\n\n # test(testLen, 1, 200, 200) (testLen, 1)\n def nextTest(self):\n if self.now == self.len:\n return None, None\n nowLen = min(predictBatch, self.len - self.now)\n testData = np.zeros((predictBatch, 1, imageH, imageW))\n ct = 0\n for i in self.idSet[self.now:self.now + nowLen]:\n testData[ct] = readImage(testImage + str(i) + '.jpg')\n ct += 1\n res = testData, self.idSet[self.now:self.now + nowLen]\n self.now += nowLen\n return res\n", "import torch.nn as nn\nfrom torch.nn import functional as F\n\n\n# 3rd Edition: LeNet-5 (up to 86.405%)\n\nclass LeNet(nn.Module):\n\n def __init__(self):\n super(LeNet, self).__init__()\n self.conv1 = nn.Conv2d(1, 6, 5)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 47 * 47, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 2)\n\n def forward(self, x):\n x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))\n x = F.max_pool2d(F.relu(self.conv2(x)), 2)\n x = x.view(-1, self.num_flat_features(x))\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n @staticmethod\n def num_flat_features(x):\n size = x.size()[1:]\n num_features = 1\n for s in size:\n num_features *= s\n return num_features\n" ]
[ [ "torch.cuda.manual_seed", "numpy.random.seed", "torch.manual_seed", "matplotlib.image.imread", "numpy.mean", "torch.cuda.manual_seed_all", "numpy.array", "numpy.zeros" ], [ "torch.nn.Linear", "torch.nn.Conv2d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zthatch/tiled
[ "156811c1cc180bb2744bcfcd9e09fc91389f3c93" ]
[ "tiled/_tests/test_object_cache.py" ]
[ "from pathlib import Path\nimport time\n\nimport numpy\nimport psutil\nimport pytest\n\nfrom ..client import from_config\nfrom ..server.object_cache import ObjectCache, get_object_cache, NO_CACHE\nfrom ..trees.files import DEFAULT_POLL_INTERVAL\n\n\ndef test_tallying_hits_and_misses():\n cache = ObjectCache(1e6)\n assert cache.get(\"a\") is None\n assert cache.misses == 1\n assert cache.hits == 0\n assert cache.get(\"a\") is None\n assert cache.misses == 2\n assert cache.hits == 0\n arr = numpy.ones((5, 5))\n cache.put(\"a\", arr, cost=1)\n assert cache.get(\"a\") is arr\n assert cache.misses == 2\n assert cache.hits == 1\n assert cache.get(\"a\") is arr\n assert cache.misses == 2\n assert cache.hits == 2\n cache.discard(\"a\")\n assert cache.get(\"a\") is None\n assert cache.misses == 3\n assert cache.hits == 2\n\n\ndef test_too_large_item():\n AVAILABLE_BYTES = 10 # very small limit\n cache = ObjectCache(AVAILABLE_BYTES)\n arr = numpy.ones((5, 5))\n assert arr.nbytes > AVAILABLE_BYTES\n cache.put(\"b\", arr, cost=1)\n assert cache.get(\"b\") is None\n # Manually specify the size.\n cache.put(\"b\", arr, cost=1, nbytes=arr.nbytes)\n assert cache.get(\"b\") is None\n\n\ndef test_eviction():\n AVAILABLE_BYTES = 300\n cache = ObjectCache(AVAILABLE_BYTES)\n arr1 = numpy.ones((5, 5)) # 200 bytes\n arr2 = 2 * numpy.ones((5, 5))\n cache.put(\"arr1\", arr1, cost=1)\n assert \"arr1\" in cache\n # Costly one evicts the previous one.\n cache.put(\"arr2\", arr2, cost=5)\n assert \"arr1\" not in cache\n assert \"arr2\" in cache\n # Cheap one does not evict the previous one.\n cache.put(\"arr1\", arr1, cost=1)\n assert \"arr1\" not in cache\n assert \"arr2\" in cache\n\n\ndef test_object_cache_hit_and_miss(tmpdir):\n with open(Path(tmpdir, \"data.csv\"), \"w\") as file:\n file.write(\n \"\"\"\na,b,c\n1,2,3\n\"\"\"\n )\n config = {\n \"trees\": [\n {\n \"tree\": \"files\",\n \"path\": \"/\",\n \"args\": {\"directory\": tmpdir},\n },\n ],\n }\n client = from_config(config)\n cache = get_object_cache()\n assert cache.hits == cache.misses == 0\n client[\"data\"].read()\n assert cache.misses == 2 # two dask objects in the cache\n assert cache.hits == 0\n client[\"data\"].read()\n assert cache.misses == 2\n assert cache.hits == 2\n # Simulate eviction.\n cache.clear()\n client[\"data\"].read()\n assert cache.misses == 4\n assert cache.hits == 2\n client[\"data\"].read()\n assert cache.misses == 4\n assert cache.hits == 4\n\n\ndef test_object_cache_disabled(tmpdir):\n with open(Path(tmpdir, \"data.csv\"), \"w\") as file:\n file.write(\n \"\"\"\na,b,c\n1,2,3\n\"\"\"\n )\n config = {\n \"trees\": [\n {\n \"tree\": \"files\",\n \"path\": \"/\",\n \"args\": {\"directory\": tmpdir},\n },\n ],\n \"object_cache\": {\"available_bytes\": 0},\n }\n client = from_config(config)\n cache = get_object_cache()\n assert cache is NO_CACHE\n client[\"data\"]\n\n\ndef test_detect_content_changed_or_removed(tmpdir):\n path = Path(tmpdir, \"data.csv\")\n with open(path, \"w\") as file:\n file.write(\n \"\"\"\na,b,c\n1,2,3\n\"\"\"\n )\n config = {\n \"trees\": [\n {\n \"tree\": \"files\",\n \"path\": \"/\",\n \"args\": {\"directory\": tmpdir},\n },\n ],\n }\n client = from_config(config)\n cache = get_object_cache()\n assert cache.hits == cache.misses == 0\n assert len(client[\"data\"].read()) == 1\n with open(path, \"w\") as file:\n file.write(\n \"\"\"\na,b,c\n1,2,3\n4,5,6\n\"\"\"\n )\n time.sleep(4 * DEFAULT_POLL_INTERVAL)\n assert len(client[\"data\"].read()) == 2\n with open(path, \"w\") as file:\n file.write(\n \"\"\"\na,b,c\n1,2,3\n4,5,6\n7,8,9\n\"\"\"\n )\n time.sleep(4 * DEFAULT_POLL_INTERVAL)\n assert len(client[\"data\"].read()) == 3\n # Remove file.\n path.unlink()\n time.sleep(4 * DEFAULT_POLL_INTERVAL)\n assert \"data\" not in client\n with pytest.raises(KeyError):\n client[\"data\"]\n\n\ndef test_cache_size_absolute(tmpdir):\n config = {\n \"trees\": [\n {\n \"tree\": \"files\",\n \"path\": \"/\",\n \"args\": {\"directory\": tmpdir},\n },\n ],\n \"object_cache\": {\"available_bytes\": 1000},\n }\n from_config(config)\n cache = get_object_cache()\n assert cache.available_bytes == 1000\n\n\ndef test_cache_size_relative(tmpdir):\n # As a fraction of system memory\n config = {\n \"trees\": [\n {\n \"tree\": \"files\",\n \"path\": \"/\",\n \"args\": {\"directory\": tmpdir},\n },\n ],\n \"object_cache\": {\"available_bytes\": 0.1},\n }\n from_config(config)\n cache = get_object_cache()\n actual = cache.available_bytes\n expected = psutil.virtual_memory().total * 0.1\n assert abs(actual - expected) / expected < 0.01 # inexact is OK\n" ]
[ [ "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Mostafa-Mansour/se3_distributions
[ "3c1c2c754e9102a031ae6ff14b703cee0163c413", "3c1c2c754e9102a031ae6ff14b703cee0163c413", "3c1c2c754e9102a031ae6ff14b703cee0163c413" ]
[ "src/se3_distributions/losses/quaternion_loss.py", "src/se3_distributions/training/multiobject_feature_grid_training.py", "src/se3_distributions/datasets/ycb_dataset.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 20 19:05:43 2017\n\n@author: bokorn\n\"\"\"\nimport numpy as np \n\nimport torch\nfrom torch.autograd import Variable\n\nfrom quat_math import quatAngularDiff, quat2AxisAngle\n\ndef quaternionLoss(preds, labels, mean = True):\n \"\"\"\n :param preds: quaternion predictions (batch_size, 1)\n :param labels: label quaternions labels (batch_size, 1)\n :return: Loss. Loss is a variable which may have a backward pass performed.\n \"\"\"\n labels = labels.float()\n labels *= torch.sign(labels[:,3]).unsqueeze(dim=1)\n preds = preds.float()\n loss = torch.zeros(1)\n\n if torch.cuda.is_available():\n loss = loss.cuda()\n loss = torch.autograd.Variable(loss)\n \n qn = torch.norm(preds, p=2, dim=1)#.detach()\n #In case of zero quats\n qn_pad = qn + (qn==0).detach().float()\n \n preds = preds.div(qn_pad.unsqueeze(1).expand_as(preds))\n loss = 1 - torch.sum(torch.mul(preds, labels.float()), 1)**2\n if(mean):\n return torch.mean(loss)\n else:\n return loss\n\ndef axisLoss(preds, labels, mean = True):\n \"\"\"\n :param preds: quaternion predictions (batch_size, 1)\n :param labels: label quaternions labels (batch_size, 1)\n :return: Loss. Loss is a variable which may have a backward pass performed.\n \"\"\"\n labels = labels.float()\n labels *= torch.sign(labels[:,3]).unsqueeze(dim=1)\n preds = preds.float()\n loss = torch.zeros(1)\n\n if torch.cuda.is_available():\n loss = loss.cuda()\n loss = torch.autograd.Variable(loss)\n \n ln = torch.norm(labels[:,:3], p=2, dim=1)#.detach()\n ax_label = labels[:,:3].div(ln.unsqueeze(1).expand_as(labels[:,:3]))\n \n pn = torch.norm(preds[:,:3], p=2, dim=1)#.detach()\n #In case of zero quats\n pn_pad = pn + (pn==0).detach().float()\n \n ax_pred = preds[:,:3].div(pn_pad.unsqueeze(1).expand_as(preds[:,:3]))\n ax_pred *= torch.sign(preds[:,3]).unsqueeze(dim=1)\n #preds = preds.div(qn_pad.unsqueeze(1).expand_as(preds))\n \n loss = .5 - .5*torch.sum(torch.mul(ax_pred, ax_label.float()), 1)\n if(mean):\n return torch.mean(loss)\n else:\n return loss\n\ndef blendedLoss(preds, labels, min_angle = np.pi/4.0, max_angle = np.pi):\n th_true = quaternionAngles(labels)\n th_true = np.minimum(np.maximum(th_true, min_angle), max_angle);\n gamma = torch.from_numpy((th_true - min_angle)/(max_angle - min_angle)).float()\n if torch.cuda.is_available():\n gamma = gamma.cuda()\n gamma = Variable(gamma)\n loss = gamma * axisLoss(preds, labels, mean = False) + (1-gamma) * quaternionLoss(preds, labels, mean = False)\n return torch.mean(loss)\n\ndef clipQuatAngle(qs, max_angle=np.pi/4.0):\n clipped_q = qs.clone()\n cos_max = np.cos(max_angle/2.0)\n sin_max = np.sin(max_angle/2.0)\n cos_th = qs[:,3].div(torch.norm(qs, p=2, dim=1))\n for j, c_th in enumerate(cos_th):\n if (torch.abs(c_th) < cos_max).all():\n axis = qs[j, :3]\n if(c_th < 0).all():\n axis = -axis\n axis_norm = torch.norm(axis, p=2)\n axis = axis.div(axis_norm.expand_as(axis))\n clipped_q[j, :3] = axis*sin_max\n clipped_q[j, 3] = cos_max\n return clipped_q\n\ndef axisAngle2Quat(axis_angle, max_angle=np.pi/4.0):\n q = torch.zeros(axis_angle.size()).float()\n if torch.cuda.is_available():\n q = q.cuda()\n q = torch.autograd.Variable(q)\n cos_th = torch.cos(0.5*torch.clamp(axis_angle[:,3], min=-max_angle, max=max_angle))\n sin_th = torch.sin(0.5*torch.clamp(axis_angle[:,3], min=-max_angle, max=max_angle))\n axis_norms = torch.norm(axis_angle[:,:3], p=2, dim=1)\n q[:,:3] = axis_angle[:,:3] * (sin_th/axis_norms).unsqueeze(1).expand_as(axis_angle[:,:3])\n q[:,3] = cos_th\n return q\n\ndef tensor2Angle(q, normalize=False, compute_axis=False):\n if(normalize):\n qn = torch.norm(q, p=2, dim=1)#.detach()\n q = q.div(qn.unsqueeze(1).expand_as(q))\n q *= torch.sign(q[:,3]).unsqueeze(dim=1)\n q[:,3] = torch.clamp(q[:,3],max=1.0)\n\n angle = 2*torch.acos(q[:,3])\n if(compute_axis):\n axis = q[:,:3].div(angle.unsqueeze(1).expand_as(q[:,:3]))\n return axis, angle\n else:\n return angle\n \ndef quaternionError(preds, labels):\n batch_size = preds.size(0)\n est_quats = preds.data.cpu().numpy()\n true_quats = labels.data.cpu().numpy()\n error = np.zeros(batch_size)\n for inst_id in range(batch_size):\n qn = np.linalg.norm(est_quats[inst_id])\n est_q = est_quats[inst_id]/qn\n est_q *= np.sign(est_q[3])\n true_q = true_quats[inst_id]\n true_q *= np.sign(true_q[3])\n diff = quatAngularDiff(est_q, true_q)\n if(diff > np.pi):\n diff = 2.0*np.pi - diff\n error[inst_id] = diff\n return error\n\ndef axisError(preds, labels):\n batch_size = preds.size(0)\n est_quats = preds.data.cpu().numpy()\n true_quats = labels.data.cpu().numpy()\n error = np.zeros(batch_size)\n for inst_id in range(batch_size):\n qn = np.linalg.norm(est_quats[inst_id])\n est_q = est_quats[inst_id]/qn\n est_q *= np.sign(est_q[3])\n true_q = true_quats[inst_id]\n true_q *= np.sign(true_q[3])\n \n est_axis = quat2AxisAngle(est_q)[0]\n true_axis = quat2AxisAngle(true_q)[0]\n error[inst_id] = np.arccos(np.dot(est_axis,true_axis))\n return error\n \ndef quaternionAngles(labels):\n batch_size = labels.size(0)\n quats = labels.data.cpu().numpy()\n angles = np.zeros(batch_size)\n for inst_id in range(batch_size):\n q = quats[inst_id]\n q *= np.sign(q[3])\n th = quat2AxisAngle(q)[1]\n if(th > np.pi):\n th = 2.0*np.pi - th\n angles[inst_id] = th\n return angles\n\ndef loopConsistencyLoss(loop_transforms, calc_angle=False):\n n = loop_transforms[0].size(0)\n q_loop = torch.zeros(n, 4).float()\n q_loop[:,3] = 1.0\n \n loss = torch.zeros(1)\n\n if torch.cuda.is_available():\n q_loop = q_loop.cuda()\n loss = loss.cuda()\n \n q_loop = torch.autograd.Variable(q_loop)\n loss = torch.autograd.Variable(loss)\n \n for q in loop_transforms:\n qn = torch.norm(q, p=2, dim=1)#.detach()\n q = q.div(qn.unsqueeze(1).expand_as(q)).float()\n\n q_loop = quaternionMultiply(q_loop, q)\n \n loss = torch.mean(1 - q_loop[:,3]**2)\n if(calc_angle):\n diff = 2*np.arccos(q_loop[:,3].data.cpu().numpy())\n angle = np.abs(diff - 2*np.pi*(diff > np.pi))\n else:\n angle = None\n \n return loss, angle\n\ndef quaternionInverse(q):\n q_inv = torch.zeros(q.size()).float()\n if torch.cuda.is_available():\n q_inv = q_inv.cuda()\n q_inv = torch.autograd.Variable(q_inv)\n \n q_inv[:,:3] = -q[:,:3]\n q_inv[:,3] = q[:,3]\n return q_inv\n\ndef quaternionMultiply(q2, q1):\n \n return torch.stack([ q2[:,0]*q1[:,3] + q2[:,1]*q1[:,2] - q2[:,2]*q1[:,1] + q2[:,3]*q1[:,0],\n -q2[:,0]*q1[:,2] + q2[:,1]*q1[:,3] + q2[:,2]*q1[:,0] + q2[:,3]*q1[:,1],\n q2[:,0]*q1[:,1] - q2[:,1]*q1[:,0] + q2[:,2]*q1[:,3] + q2[:,3]*q1[:,2],\n -q2[:,0]*q1[:,0] - q2[:,1]*q1[:,1] - q2[:,2]*q1[:,2] + q2[:,3]*q1[:,3]], dim=1)\n", "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 4 00:27:44 2018\n\n@author: bokorn\n\"\"\"\n\nimport torch\nimport torch.multiprocessing\ntorch.multiprocessing.set_sharing_strategy('file_system')\nfrom torch.optim import Adam, Adadelta, SGD\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import ConcatDataset\n\nimport os\nimport sys\nimport time\nimport numpy as np\nfrom tqdm import tqdm, trange\n\nfrom object_pose_utils.bbTrans.discretized4dSphere import S3Grid\nfrom object_pose_utils.utils import to_np, to_var\n\nfrom object_pose_utils.datasets.feature_dataset import UniformFeatureDataset, FeatureDataset\nfrom se3_distributions.losses.feature_distance_loss import multiObjectLoss\nfrom logger import Logger\n\nimport resource\nrlimit = resource.getrlimit(resource.RLIMIT_NOFILE)\nresource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1])) \n\nclass FeatureGridTrainer(object):\n def __init__(self, \n dataset_root,\n feature_root,\n falloff_angle = np.pi/4,\n batch_size = 16,\n num_workers = 4,\n seed = 0):\n \n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n\n self.falloff_angle = falloff_angle\n self.model_datasets = [UniformFeatureDataset(dataset_root = dataset_root,\n feature_root = feature_root, \n mode = 'train_sym',\n resample_on_error = True,\n object_label = obj) for obj in range(1,22)]\n \n self.train_dataset = ConcatDataset(self.model_datasets)\n\n self.train_loader = DataLoader(self.train_dataset,\n num_workers=num_workers-1,\n batch_size=batch_size, \n shuffle=True)\n\n\n self.valid_dataset = FeatureDataset(dataset_root = dataset_root,\n feature_root = feature_root,\n mode = 'valid',\n resample_on_error = True,\n object_list = list(range(1,22)))\n \n self.valid_loader = DataLoader(self.valid_dataset,\n num_workers=1, \n batch_size=batch_size, \n shuffle=True)\n\n classes = self.valid_dataset.classes\n self.grid_vertices = {}\n self.grid_features = {}\n for obj in range(1,22):\n self.grid_vertices[obj] = torch.load(os.path.join(feature_root, 'grid', \n '{}_vertices.pt'.format(classes[obj])))\n self.grid_features[obj] = torch.load(os.path.join(feature_root, 'grid', \n '{}_features.pt'.format(classes[obj])))\n\n def train(self, model, \n log_dir,\n checkpoint_dir,\n num_epochs,\n log_every_nth,\n checkpoint_every_nth,\n lr,\n optimizer,\n weight_top,\n ):\n \n model.train()\n model.cuda()\n last_checkpoint_filename = None\n if(optimizer.lower() == 'sgd'):\n self.optimizer = SGD(model.parameters(), lr=lr, momentum=0.9)\n elif(optimizer.lower() == 'adam'):\n self.optimizer = Adam(model.parameters(), lr=lr)\n elif(optimizer.lower() == 'adadelta'):\n self.optimizer = Adadelta(model.parameters(), lr=lr)\n else:\n raise AssertionError('Unsupported Optimizer {}, only SGD, Adam, and Adadelta supported'.format(optimizer))\n \n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n \n log_dir = os.path.join(log_dir,'logs')\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n train_log_dir = os.path.join(log_dir,'train')\n if not os.path.exists(train_log_dir):\n os.makedirs(train_log_dir)\n train_logger = Logger(train_log_dir) \n \n valid_log_dir = os.path.join(log_dir,'valid')\n if not os.path.exists(valid_log_dir):\n os.makedirs(valid_log_dir) \n valid_logger = Logger(valid_log_dir) \n \n weights_dir = os.path.join(checkpoint_dir,'weights')\n if not os.path.exists(weights_dir):\n os.makedirs(weights_dir)\n \n cumulative_batch_idx = 0\n min_loss = float('inf')\n print('Starting Training')\n dataset_size = len(self.train_loader)\n for epoch_idx in trange(1, num_epochs+1):\n for batch_idx, data in tqdm(enumerate(self.train_loader), total = len(self.train_loader)):\n obj, feat, quat = data\n log_data = not((cumulative_batch_idx+1) % log_every_nth)\n torch.cuda.empty_cache()\n grid_features = []\n grid_vertices = []\n for idx in to_np(obj).flat:\n grid_features.append(self.grid_features[idx])\n grid_vertices.append(self.grid_vertices[idx])\n grid_features = torch.cat(grid_features)\n grid_vertices = torch.cat(grid_vertices)\n \n train_results = multiObjectLoss(model, obj.cuda()-1, \n to_var(feat), to_var(quat),\n to_var(grid_features), to_var(grid_vertices),\n falloff_angle = self.falloff_angle,\n weight_top = weight_top,\n optimizer = self.optimizer, \n calc_metrics = log_data,\n )\n\n torch.cuda.empty_cache()\n\n if log_data:\n #print(\"epoch {} ({}):: cumulative_batch_idx {}\".format(epoch_idx, time.time() - log_time, cumulative_batch_idx + 1))\n\n train_info = {}\n for k,v in train_results.items():\n if('vec' not in k):\n train_info[k] = v\n else:\n train_logger.histo_summary(k,v, cumulative_batch_idx+1)\n\n \n for tag, value in train_info.items():\n train_logger.scalar_summary(tag, value, cumulative_batch_idx+1)\n\n for tag, value in model.named_parameters():\n tag = tag.replace('.', '/')\n train_logger.histo_summary(tag, to_np(value), cumulative_batch_idx+1)\n train_logger.histo_summary(tag+'/grad', to_np(value.grad), cumulative_batch_idx+1)\n \n self.optimizer.zero_grad()\n #########################################\n ############ VALIDATION SETS ############\n #########################################\n obj, feat, quat = next(iter(self.valid_loader))\n torch.cuda.empty_cache()\n grid_features = []\n grid_vertices = []\n for idx in to_np(obj).flat:\n grid_features.append(self.grid_features[idx])\n grid_vertices.append(self.grid_vertices[idx])\n grid_features = torch.cat(grid_features)\n grid_vertices = torch.cat(grid_vertices)\n valid_results = multiObjectLoss(model, obj.cuda()-1,\n to_var(feat), to_var(quat),\n to_var(grid_features), to_var(grid_vertices),\n falloff_angle = self.falloff_angle,\n weight_top = weight_top,\n optimizer = None, \n calc_metrics = True,\n )\n torch.cuda.empty_cache()\n valid_info = {}\n for k,v in valid_results.items():\n if('vec' not in k):\n valid_info[k] = v\n else:\n valid_logger.histo_summary(k,v, cumulative_batch_idx+1)\n\n for tag, value in valid_info.items():\n valid_logger.scalar_summary(tag, value, cumulative_batch_idx+1)\n \n #gc.collect()\n\n if('loss' in valid_results and valid_results['loss'] < min_loss):\n min_loss = valid_results['loss']\n weights_filename = os.path.join(weights_dir, 'best_quat.pth')\n print(\"saving model \", weights_filename)\n torch.save(model.state_dict(), weights_filename) \n\n checkpoint_model = not((cumulative_batch_idx+1) % checkpoint_every_nth)\n if(checkpoint_model):\n checkpoint_weights_filename = os.path.join(weights_dir, 'checkpoint_{}.pth'.format(cumulative_batch_idx+1))\n print(\"checkpointing model \", checkpoint_weights_filename)\n torch.save(model.state_dict(), checkpoint_weights_filename)\n \n if(last_checkpoint_filename is not None):\n os.remove(last_checkpoint_filename)\n last_checkpoint_filename = checkpoint_weights_filename\n\n cumulative_batch_idx += 1\n\ndef main():\n import datetime\n from argparse import ArgumentParser\n from se3_distributions.models.compare_networks import CompareNet\n\n parser = ArgumentParser()\n\n parser.add_argument('--dataset_folder', type=str, default=None)\n parser.add_argument('--feature_folder', type=str, default=None)\n\n parser.add_argument('--weight_file', type=str, default=None)\n\n parser.add_argument('--feature_size', type=int, default=1024)\n parser.add_argument('--falloff_angle', type=float, default=20.0)\n parser.add_argument('--weight_top', type=float, default=1.0)\n\n parser.add_argument('--batch_size', type=int, default=16)\n parser.add_argument('--num_workers', type=int, default=16)\n \n parser.add_argument('--lr', type=float, default=1e-5)\n parser.add_argument('--optimizer', type=str, default='Adam')\n \n parser.add_argument('--random_seed', type=int, default=0)\n\n parser.add_argument('--log_dir', type=str, default='results/') \n parser.add_argument('--checkpoint_dir', type=str, default=None) \n parser.add_argument('--num_epochs', type=int, default=100)\n parser.add_argument('--log_every_nth', type=int, default=100)\n parser.add_argument('--checkpoint_every_nth', type=int, default=1000)\n\n args = parser.parse_args()\n\n trainer = FeatureiGridTrainer(dataset_root = args.dataset_folder,\n feature_root = args.feature_folder,\n falloff_angle = args.falloff_angle*np.pi/180.0,\n batch_size = args.batch_size,\n num_workers = args.num_workers,\n seed = args.random_seed,\n )\n\n\n if(args.checkpoint_dir is None):\n args.checkpoint_dir = args.log_dir\n current_timestamp = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n log_dir = os.path.join(args.log_dir,current_timestamp) \n checkpoint_dir = os.path.join(args.checkpoint_dir,current_timestamp) \n \n model = CompareNet(args.feature_size, 21)\n\n if args.weight_file is not None:\n model.load_state_dict(torch.load(args.weight_file))\n\n trainer.train(model, \n log_dir = log_dir,\n checkpoint_dir = checkpoint_dir,\n num_epochs = args.num_epochs,\n log_every_nth = args.log_every_nth,\n checkpoint_every_nth = args.checkpoint_every_nth,\n lr = args.lr,\n optimizer = args.optimizer,\n weight_top = args.weight_top,\n )\n\nif __name__=='__main__':\n import socket\n import seuss_cluster_alerts as sca\n hostname = socket.gethostname()\n gpu_id = os.environ.get('CUDA_VISIBLE_DEVICES')\n if(gpu_id is not None):\n hostname += ' GPU {}'.format(gpu_id)\n\n try:\n main()\n sca.sendAlert('[email protected]', \n message_subject='Job Completed on {}'.format(hostname))\n\n except:\n e = sys.exc_info()\n sca.sendAlert('[email protected]', \n message_subject='Job Failed on {}'.format(hostname),\n message_text=str(e))\n raise\n", "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tues at some point in time\n@author: bokorn with some code pulled from https://github.com/yuxng/PoseCNN/blob/master/lib/datasets/lov.py\n\"\"\"\n\nimport os\nimport cv2\nimport torch\nimport numpy as np\nimport scipy.io as sio\nimport time\nimport sys\n\nfrom se3_distributions.datasets.image_dataset import PoseImageDataset\nfrom se3_distributions.datasets.ycb_data_processing import preprocessPoseCNNMetaData\nfrom se3_distributions.utils import SingularArray\nimport se3_distributions.utils.transformations as tf_trans\nfrom se3_distributions.utils.pose_processing import viewpoint2Pose\nfrom se3_distributions.utils.image_preprocessing import cropAndPad\nfrom transforms3d.quaternions import quat2mat, mat2quat\n\ndef ycbRenderTransform(q):\n trans_quat = q.copy()\n trans_quat = tf_trans.quaternion_multiply(trans_quat, tf_trans.quaternion_about_axis(-np.pi/2, [1,0,0]))\n return viewpoint2Pose(trans_quat)\n\ndef setYCBCamera(renderer, width=640, height=480):\n fx = 1066.778\n fy = 1067.487\n px = 312.9869\n py = 241.3109\n renderer.setCameraMatrix(fx, fy, px, py, width, height)\n\ndef getYCBSymmeties(obj):\n if(obj == 13):\n return [[0,0,1]], [[np.inf]]\n elif(obj == 16):\n return [[0.9789,-0.2045,0.], [0.,0.,1.]], [[0.,np.pi], [0.,np.pi/2,np.pi,3*np.pi/2]]\n elif(obj == 19):\n return [[-0.14142136, 0.98994949,0]], [[0.,np.pi]]\n elif(obj == 20):\n return [[0.9931506 , 0.11684125,0]], [[0.,np.pi]]\n elif(obj == 21):\n return [[0.,0.,1.]], [[0.,np.pi]]\n else:\n return [],[]\n\nclass YCBDataset(PoseImageDataset):\n def __init__(self, data_dir, image_set, \n obj = None, use_syn_data = False,\n use_posecnn_masks = False,\n *args, **kwargs):\n\n super(YCBDataset, self).__init__(*args, **kwargs)\n self.use_syn_data = use_syn_data\n self.data_dir = data_dir\n\n\t#self.classes = ('__background__', '002_master_chef_can', '003_cracker_box', '004_sugar_box', '005_tomato_soup_can', '006_mustard_bottle', \\\n # '007_tuna_fish_can', '008_pudding_box', '009_gelatin_box', '010_potted_meat_can', '011_banana', '019_pitcher_base', \\\n # '021_bleach_cleanser', '024_bowl', '025_mug', '035_power_drill', '036_wood_block', '037_scissors', '040_large_marker', \\\n # '051_large_clamp', '052_extra_large_clamp', '061_foam_brick')\n self.classes = ['__background__']\n with open(os.path.join(self.data_dir, 'image_sets', 'classes.txt')) as f:\n self.classes.extend([x.rstrip('\\n') for x in f.readlines()])\n\n self.num_classes = len(self.classes)\n self.model_filenames = {}\n for j in range(1, self.num_classes):\n self.model_filenames[j] = os.path.join(self.data_dir, 'models', self.classes[j], 'textured.obj')\n\n self.symmetry = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1])\n self.image_set = image_set\n self.append_rendered = False\n self.use_posecnn_masks = use_posecnn_masks\n #self.data_filenames = self.loadImageSet()\n if(obj is not None):\n self.setObject(obj)\n #self.points, self.points_all = self.load_object_points()\n\t\n def getSymmetry(self):\n return getYCBSymmeties(self.obj)\n\n def loadObjectPoints(self):\n points = [[] for _ in xrange(len(self.classes))]\n num = np.inf\n \n for i in xrange(1, len(self.classes)):\n point_file = os.path.join(self.data_dir, 'models', self.classes[i], 'points.xyz')\n #print point_file\n assert os.path.exists(point_file), 'Path does not exist: {}'.format(point_file)\n points[i] = np.loadtxt(point_file)\n if points[i].shape[0] < num:\n num = points[i].shape[0]\n\n points_all = np.zeros((self.num_classes, num, 3), dtype=np.float32)\n for i in xrange(1, len(self.classes)):\n points_all[i, :, :] = points[i][:num, :]\n\n return points, points_all\n\n def getObjectPoints(self):\n point_file = os.path.join(self.data_dir, 'models', self.classes[self.obj], 'points.xyz')\n assert os.path.exists(point_file), 'Path does not exist: {}'.format(point_file)\n points = np.loadtxt(point_file)\n\n return points\n\n\n def loadImageSet(self):\n \"\"\"\n Load the indexes listed in this dataset's image set file.\n \"\"\"\n image_set_file = os.path.join(self.data_dir, 'image_sets', \n self.obj_name+'_'+self.image_set+'.txt')\n assert os.path.exists(image_set_file), \\\n 'Path does not exist: {}'.format(image_set_file)\n\n with open(image_set_file) as f:\n image_index = [x.rstrip('\\n') for x in f.readlines()]\n if(self.use_syn_data):\n syn_set_file = os.path.join(self.data_dir, 'image_sets',\n self.obj_name+'_syn.txt')\n assert os.path.exists(syn_set_file), \\\n 'Path does not exist: {}'.format(syn_set_file)\n with open(syn_set_file) as f:\n image_index.extend([x.rstrip('\\n') for x in f.readlines()])\n\n return image_index\n\n def splitImages(self):\n self.videos = {}\n for fn in self.data_filenames:\n vid = fn.split('/')[0]\n if(vid in self.videos.keys()):\n self.videos[vid].append(fn)\n else:\n self.videos[vid] = [fn]\n\n def generateObjectImageSet(self):\n obj_image_sets = {}\n for cls in self.classes[1:]:\n obj_image_sets[cls] = []\n\n image_set_file = os.path.join(self.data_dir, 'image_sets', self.image_set+'.txt')\n assert os.path.exists(image_set_file), \\\n 'Path does not exist: {}'.format(image_set_file)\n\n with open(image_set_file) as f:\n filenames = [x.rstrip('\\n') for x in f.readlines()]\n \n for fn in filenames:\n image_prefix = os.path.join(self.data_dir, 'data', fn)\n img = cv2.imread(image_prefix + '-color.png')\n \n #if(self.use_posecnn_masks):\n # labels = cv2.imread(image_prefix + '-posecnn-seg.png')[:,:,0] \n #else:\n # label = cv2.imread(image_prefix + '-label.png')[:,:,0]\n label = cv2.imread(image_prefix + '-label.png')[:,:,0]\n for idx in np.unique(label):\n if(idx > 0):\n obj_image_sets[self.classes[idx]].append(fn)\n \n \n #with open(os.path.join(self.data_dir, 'data', fn + '-box.txt')) as f:\n # bboxes = [x.rstrip('\\n').split(' ') for x in f.readlines()]\n # for bb in bboxes:\n # (x0, y0, x1, y1) = np.array(bb[1:], dtype='float')\n # if(x1-x0 > 0 and y1-y0 > 0):\n # obj_image_sets[bb[0]].append(fn)\n \n for k,v in obj_image_sets.items():\n with open(os.path.join(self.data_dir, 'image_sets', k+'_'+self.image_set+'.txt'), 'w') as f:\n f.write('\\n'.join(v))\n\n def generateSyntheticImageSet(self):\n import glob\n syn_data_dir = os.path.join(self.data_dir, 'data_syn')\n #label_filenames = sorted(glob.glob(os.path.join(syn_data_dir,'-label.png')))\n data_filenames = sorted(glob.glob(os.path.join(syn_data_dir,'*-meta.mat')))\n\t\n obj_image_sets = {}\n for cls in self.classes[1:]:\n obj_image_sets[cls] = []\n \n for fn in data_filenames:\n data_prefix = '-'.join(fn.split('/')[-1].split('-')[:-1])\n data = sio.loadmat(os.path.join(self.data_dir, 'data_syn', data_prefix + '-meta.mat'))\n cls_idxs = data['cls_indexes'].flatten().astype(int)\n \n img = cv2.imread(os.path.join(self.data_dir, 'data_syn', data_prefix + '-label.png'))\n data_prefix = os.path.join('..', 'data_syn', data_prefix)\n for idx in cls_idxs: \n if(np.sum(img == idx) > 0):\n obj_image_sets[self.classes[idx]].append(data_prefix)\n for k,v in obj_image_sets.items():\n with open(os.path.join(self.data_dir, 'image_sets', k+'_syn.txt'), 'w') as f:\n f.write('\\n'.join(v))\n\n def generateRenderedImages(self):\n from model_renderer.pose_renderer import BpyRenderer\n renderer = BpyRenderer(transform_func = ycbRenderTransform)\n renderer.loadModel(self.getModelFilename(), emit = 0.5)\n print(\"Rendering Object {}: {}\".format(self.obj, self.getObjectName()))\n renderPoses = renderer.renderPose\n\n render_filenames = []\n render_quats = []\n for fn in self.data_filenames: \n data = sio.loadmat(os.path.join(self.data_dir, 'data', fn + '-meta.mat'))\n pose_idx = np.where(data['cls_indexes'].flatten()==self.obj)[0][0]\n mat = np.eye(4)\n mat[:3,:3] = data['poses'][:3,:3,pose_idx]\n render_filenames.append(os.path.join(self.data_dir, 'data', fn + '-{}-render.png'.format(self.obj)))\n render_quats.append(tf_trans.quaternion_from_matrix(mat))\n\n renderPoses(render_quats, camera_dist = 0.33, image_filenames = render_filenames)\n\n def getObjectName(self):\n return self.classes[self.obj]\n\n def setObject(self, obj):\n self.obj = obj\n self.obj_name = self.getObjectName()\n self.data_filenames = self.loadImageSet()\n self.data_models = SingularArray(self.obj)\n #self.quats = self.loadQuatSet()\n #print(\"Size of quats: \", sys.getsizeof(self.quats))\n\n def getModelFilename(self):\n return os.path.join(self.data_dir, 'models', self.classes[self.obj], 'textured.obj')\n\n def loadQuatSet(self):\n if(self.use_syn_data):\n quat_set_file = os.path.join(self.data_dir, 'quats', self.obj_name+'_'+self.image_set+'_syn_quats.npy')\n else:\n quat_set_file = os.path.join(self.data_dir, 'quats', self.obj_name+'_'+self.image_set+'_quats.npy')\n if(os.path.exists(quat_set_file)):\n quats = np.load(quat_set_file)\n else:\n quats = [self.loadQuat(j) for j in range(len(self))]\n if not os.path.exists(os.path.join(self.data_dir, 'quats')):\n os.makedirs(os.path.join(self.data_dir, 'quats'))\n np.save(quat_set_file, quats)\n return quats\n\n def loadQuat(self, index):\n data = sio.loadmat(os.path.join(self.data_dir, 'data', self.data_filenames[index] + '-meta.mat'))\n pose_idx = np.where(data['cls_indexes'].flatten()==self.obj)[0][0]\n mat = np.eye(4)\n mat[:3,:3] = data['poses'][:3,:3,pose_idx]\n quat = tf_trans.quaternion_from_matrix(mat)\n return quat\n\n def getQuat(self, index):\n #return self.quats[index].copy()\n return self.loadQuat(index)\n\n def getTrans(self, index, use_gt = True):\n if(use_gt):\n data = sio.loadmat(os.path.join(self.data_dir, 'data', self.data_filenames[index] + '-meta.mat'))\n pose_idx = np.where(data['cls_indexes'].flatten()==self.obj)[0][0]\n mat = np.eye(4)\n mat[:3,:] = data['poses'][:,:,pose_idx]\n else:\n data = sio.loadmat(os.path.join(self.data_dir, 'data', self.data_filenames[index] + '-posecnn.mat'))\n pose_idx = np.where(data['rois'][:,1].flatten()==self.obj)[0]\n if(len(pose_idx) == 0):\n return None\n else:\n pose_idx = pose_idx[0]\n pose = data['poses'][pose_idx]\n mat = np.eye(4)\n mat[:3, :3] = quat2mat(pose[:4])\n mat[:3, 3] = pose[4:7]\n return mat\n\n def getImage(self, index, boarder_ratio=0.25, preprocess = True):\n image_prefix = os.path.join(self.data_dir, 'data', self.data_filenames[index])\n img = cv2.imread(image_prefix + '-color.png')\n posecnn_meta = scio.loadmat('{}-posecnn.mat'.format(self.data_filenames[index]))\n\n obj_idx = np.nonzero(posecnn_meta['rois'][:,1].astype(int) == self.obj)[0][0]\n mask, bbox, object_label = preprocessPoseCNNMetaData(posecnn_meta, obj_idx)\n rmin, rmax, cmin, cmax = bbox\n #if(self.use_posecnn_masks and os.path.exists(image_prefix + '-posecnn-seg.png')):\n # mask = 255*(cv2.imread(image_prefix + '-posecnn-seg.png')[:,:,:1] == self.obj).astype('uint8')\n #else:\n # mask = 255*(cv2.imread(image_prefix + '-label.png')[:,:,:1] == self.obj).astype('uint8')\n if(np.sum(mask) < 9):\n #import IPython; IPython.embed()\n print('Index {} invalid for {} ({}:{})'.format(index, self.getObjectName(),\n self.image_set, image_prefix))\n return None, None \n img = np.concatenate([img, mask], axis=2)\n #if(preprocess):\n # crop_img = self.preprocessImages(cropAndPad(img), normalize_tensor = True, augment_img = True)\n #else:\n img = img[rmin:rmax, cmin:cmax, :]\n\n crop_img = cropAndPad(img)\n \n if(self.append_rendered):\n #import IPython; IPython.embed();\n #rendered_img = self.preprocessImages(cv2.imread(image_prefix + '-color.png'), normalize_tensor = True)\n rendered_img = cv2.imread(image_prefix + '-{}-render.png'.format(self.obj), cv2.IMREAD_UNCHANGED)\n if(rendered_img is None):\n print(image_prefix + '-{}-render.png'.format(self.obj), 'Not Found')\n rendered_img = cropAndPad(img)\n\n #rendered_img = self.preprocessImages(rendered_img, normalize_tensor = True)\n #crop_img = torch.cat((crop_img, rendered_img), 0)\n #print('='*100)\n #print(image_prefix + '-{}-render.png'.format(self.obj))\n #print(crop_img.shape)\n #print(rendered_img.shape)\n #print('='*100)\n #crop_img = np.concatenate([crop_img, rendered_img], axis=2)\n else:\n rendered_img = None\n\n return crop_img, rendered_img\n\n def __len__(self):\n return len(self.data_filenames)\n \n" ]
[ [ "torch.mean", "numpy.dot", "torch.abs", "torch.zeros", "torch.sign", "torch.acos", "torch.cuda.is_available", "torch.autograd.Variable", "torch.norm", "torch.from_numpy", "numpy.sin", "numpy.zeros", "torch.stack", "numpy.maximum", "numpy.abs", "numpy.cos", "numpy.linalg.norm", "numpy.sign", "torch.clamp" ], [ "numpy.random.seed", "torch.load", "torch.cat", "torch.manual_seed", "torch.utils.data.DataLoader", "torch.cuda.empty_cache", "torch.utils.data.ConcatDataset", "torch.cuda.manual_seed_all", "torch.multiprocessing.set_sharing_strategy" ], [ "numpy.unique", "numpy.eye", "numpy.save", "numpy.concatenate", "numpy.load", "numpy.array", "numpy.zeros", "numpy.sum", "numpy.loadtxt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ParisaO/PixelLib
[ "59de17ea02437afcb152b80ef4dc13acb14183b0" ]
[ "pixellib/instance.py" ]
[ "import cv2\r\nimport numpy as np\r\nimport random\r\nimport os\r\nimport sys\r\nimport math\r\nfrom pixellib.mask_rcnn import MaskRCNN\r\nfrom pixellib.config import Config\r\nimport colorsys\r\nimport time\r\nfrom datetime import datetime\r\nimport imantics\r\nfrom imantics import Polygons, Mask\r\n\r\n\r\nclass configuration(Config):\r\n NAME = \"configuration\"\r\n\r\ncoco_config = configuration(BACKBONE = \"resnet101\", NUM_CLASSES = 81, class_names = [\"BG\"], IMAGES_PER_GPU = 1, \r\nDETECTION_MIN_CONFIDENCE = 0.7,IMAGE_MAX_DIM = 1024, IMAGE_MIN_DIM = 800,IMAGE_RESIZE_MODE =\"square\", GPU_COUNT = 1) \r\n\r\n\r\nclass instance_segmentation():\r\n def __init__(self, infer_speed = None):\r\n if infer_speed == \"average\":\r\n coco_config.IMAGE_MAX_DIM = 512\r\n coco_config.IMAGE_MIN_DIM = 512\r\n coco_config.DETECTION_MIN_CONFIDENCE = 0.45\r\n\r\n elif infer_speed == \"fast\":\r\n coco_config.IMAGE_MAX_DIM = 384\r\n coco_config.IMAGE_MIN_DIM = 384\r\n coco_config.DETECTION_MIN_CONFIDENCE = 0.25\r\n\r\n elif infer_speed == \"rapid\":\r\n coco_config.IMAGE_MAX_DIM = 256\r\n coco_config.IMAGE_MIN_DIM = 256\r\n coco_config.DETECTION_MIN_CONFIDENCE = 0.20 \r\n \r\n\r\n self.model_dir = os.getcwd()\r\n\r\n def load_model(self, model_path):\r\n self.model = MaskRCNN(mode = \"inference\", model_dir = self.model_dir, config = coco_config)\r\n self.model.load_weights(model_path, by_name= True)\r\n\r\n \r\n def select_target_classes(self,BG = False, person=False, bicycle=False, car=False, motorcycle=False, airplane=False,\r\n bus=False, train=False, truck=False, boat=False, traffic_light=False, fire_hydrant=False,\r\n stop_sign=False,\r\n parking_meter=False, bench=False, bird=False, cat=False, dog=False, horse=False, sheep=False,\r\n cow=False, elephant=False, bear=False, zebra=False,\r\n giraffe=False, backpack=False, umbrella=False, handbag=False, tie=False, suitcase=False,\r\n frisbee=False, skis=False, snowboard=False,\r\n sports_ball=False, kite=False, baseball_bat=False, baseball_glove=False, skateboard=False,\r\n surfboard=False, tennis_racket=False,\r\n bottle=False, wine_glass=False, cup=False, fork=False, knife=False, spoon=False, bowl=False,\r\n banana=False, apple=False, sandwich=False, orange=False,\r\n broccoli=False, carrot=False, hot_dog=False, pizza=False, donut=False, cake=False, chair=False,\r\n couch=False, potted_plant=False, bed=False,\r\n dining_table=False, toilet=False, tv=False, laptop=False, mouse=False, remote=False,\r\n keyboard=False, cell_phone=False, microwave=False,\r\n oven=False, toaster=False, sink=False, refrigerator=False, book=False, clock=False, vase=False,\r\n scissors=False, teddy_bear=False, hair_dryer=False,\r\n toothbrush=False):\r\n\r\n detected_classes = {}\r\n target_class_names = [BG, person, bicycle, car, motorcycle, airplane,\r\n bus, train, truck, boat, traffic_light, fire_hydrant, stop_sign,\r\n parking_meter, bench, bird, cat, dog, horse, sheep, cow, elephant, bear, zebra,\r\n giraffe, backpack, umbrella, handbag, tie, suitcase, frisbee, skis, snowboard,\r\n sports_ball, kite, baseball_bat, baseball_glove, skateboard, surfboard, tennis_racket,\r\n bottle, wine_glass, cup, fork, knife, spoon, bowl, banana, apple, sandwich, orange,\r\n broccoli, carrot, hot_dog, pizza, donut, cake, chair, couch, potted_plant, bed,\r\n dining_table, toilet, tv, laptop, mouse, remote, keyboard, cell_phone, microwave,\r\n oven, toaster, sink, refrigerator, book, clock, vase, scissors, teddy_bear, hair_dryer,\r\n toothbrush]\r\n class_names = [\"BG\", \"person\", \"bicycle\", \"car\", \"motorcycle\", \"airplane\",\r\n \"bus\", \"train\", \"truck\", \"boat\", \"traffic light\", \"fire hydrant\", \"stop sign\",\r\n \"parking meter\", \"bench\", \"bird\", \"cat\", \"dog\", \"horse\", \"sheep\", \"cow\", \"elephant\", \"bear\",\r\n \"zebra\",\r\n \"giraffe\", \"backpack\", \"umbrella\", \"handbag\", \"tie\", \"suitcase\", \"frisbee\", \"skis\",\r\n \"snowboard\",\r\n \"sports ball\", \"kite\", \"baseball bat\", \"baseball glove\", \"skateboard\", \"surfboard\",\r\n \"tennis racket\",\r\n \"bottle\", \"wine glass\", \"cup\", \"fork\", \"knife\", \"spoon\", \"bowl\", \"banana\", \"apple\", \"sandwich\",\r\n \"orange\",\r\n \"broccoli\", \"carrot\", \"hot dog\", \"pizza\", \"donut\", \"cake\", \"chair\", \"couch\", \"potted plant\",\r\n \"bed\",\r\n \"dining table\", \"toilet\", \"tv\", \"laptop\", \"mouse\", \"remote\", \"keyboard\", \"cell phone\",\r\n \"microwave\",\r\n \"oven\", \"toaster\", \"sink\", \"refrigerator\", \"book\", \"clock\", \"vase\", \"scissors\", \"teddy bear\",\r\n \"hair dryer\",\r\n \"toothbrush\"]\r\n\r\n for target_class_name, class_name in zip(target_class_names, class_names):\r\n if (target_class_name == True):\r\n detected_classes[class_name] = \"valid\"\r\n else:\r\n detected_classes[class_name] = \"invalid\"\r\n \r\n return detected_classes\r\n\r\n def segmentImage(self, image_path, show_bboxes = False, process_frame = False, segment_target_classes = None, extract_segmented_objects = False, \r\n save_extracted_objects = False,mask_points_values = False, output_image_name = None, verbose = None):\r\n\r\n if process_frame ==False:\r\n image = cv2.imread(image_path)\r\n\r\n else:\r\n image = image_path\r\n\r\n new_img = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\r\n # Run detection\r\n if verbose is not None:\r\n print(\"Processing image...\")\r\n results = self.model.detect([new_img]) \r\n\r\n coco_config.class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',\r\n 'bus', 'train', 'truck', 'boat', 'traffic light',\r\n 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',\r\n 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',\r\n 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',\r\n 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',\r\n 'kite', 'baseball bat', 'baseball glove', 'skateboard',\r\n 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',\r\n 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',\r\n 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',\r\n 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',\r\n 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',\r\n 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',\r\n 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',\r\n 'teddy bear', 'hair drier', 'toothbrush']\r\n\r\n\r\n r = results[0] \r\n \r\n \"\"\" Code to filter out unused detections and detect specific classes \"\"\"\r\n if segment_target_classes is not None:\r\n bboxes = r['rois']\r\n scores = r['scores']\r\n masks = r['masks']\r\n class_ids = r['class_ids']\r\n \r\n \r\n com_bboxes = []\r\n com_masks = []\r\n com_scores = []\r\n com_class_ids = []\r\n \r\n final_dict = []\r\n for a, b in enumerate(r['class_ids']):\r\n name = coco_config.class_names[b]\r\n\r\n \r\n box = bboxes[a]\r\n \r\n ma = masks[:, :, a]\r\n \r\n score = scores[a]\r\n \r\n c_ids = class_ids[a]\r\n \r\n \r\n if (segment_target_classes[name] == \"invalid\"):\r\n continue\r\n \r\n com_bboxes.append(box)\r\n com_class_ids.append(c_ids)\r\n com_masks.append(ma)\r\n com_scores.append(score)\r\n \r\n \r\n final_bboxes = np.array(com_bboxes)\r\n \r\n final_class_ids = np.array(com_class_ids)\r\n final_masks = np.array(com_masks)\r\n if len(final_masks != 0):\r\n final_masks = np.stack(final_masks, axis = 2)\r\n \r\n final_scores = np.array(com_scores)\r\n \r\n final_dict.append({\r\n \"rois\": final_bboxes,\r\n \"class_ids\": final_class_ids,\r\n \"scores\": final_scores,\r\n \"masks\": final_masks,\r\n })\r\n r = final_dict[0] \r\n \r\n \r\n if show_bboxes == False:\r\n output = display_instances(image, r['rois'], r['masks'], r['class_ids'], coco_config.class_names)\r\n if output_image_name is not None:\r\n cv2.imwrite(output_image_name, output)\r\n print(\"Processed image saved successfully in your current working directory.\") \r\n \r\n \"\"\" Code to extract and crop out each of the objects segmented in an image \"\"\"\r\n if extract_segmented_objects == False:\r\n \r\n if mask_points_values == True:\r\n mask = r['masks']\r\n contain_val = []\r\n for a in range(mask.shape[2]):\r\n m = mask[:,:,a]\r\n mask_values = Mask(m).polygons()\r\n val = mask_values.points\r\n contain_val.append(val)\r\n\r\n r['masks'] = contain_val\r\n \r\n\r\n return r, output\r\n\r\n\r\n\r\n else:\r\n \r\n\r\n mask = r['masks']\r\n m = 0\r\n for a in range(mask.shape[2]):\r\n \r\n img = cv2.imread(image_path)\r\n \r\n for b in range(img.shape[2]):\r\n \r\n img[:,:,b] = img[:,:,b] * mask[:,:,a]\r\n m+=1\r\n extracted_objects = img[np.ix_(mask[:,:,a].any(1), mask[:,:,a].any(0))]\r\n \r\n if save_extracted_objects == True:\r\n save_path = os.path.join(\"segmented_object\" + \"_\" + str(m) + \".jpg\")\r\n cv2.imwrite(save_path, extracted_objects)\r\n \r\n \r\n if mask_points_values == True:\r\n mask = r['masks']\r\n contain_val = []\r\n for a in range(mask.shape[2]):\r\n m = mask[:,:,a]\r\n mask_values = Mask(m).polygons()\r\n val = mask_values.points\r\n \r\n contain_val.append(val)\r\n\r\n r['masks'] = contain_val\r\n\r\n\r\n extract_mask = extracted_objects\r\n object_val = []\r\n\r\n for a in range(extract_mask.shape[2]):\r\n m = extract_mask[:,:,a]\r\n mask_values = Mask(m).polygons()\r\n val = mask_values.points\r\n object_val.append(val)\r\n\r\n extracted_objects = object_val\r\n\r\n \r\n \"\"\" The mask values of each of the extracted cropped object in the image\r\n is added to the dictionary containing an array of output values:\r\n \"\"\" \r\n\r\n r.update({\"extracted_objects\":extracted_objects})\r\n\r\n return r, output\r\n \r\n \r\n else:\r\n output = display_box_instances(image, r['rois'], r['masks'], r['class_ids'], coco_config.class_names, r['scores'])\r\n\r\n \"\"\" Code to extract and crop out each of the objects segmented in an image \"\"\"\r\n if extract_segmented_objects == True:\r\n mask = r['masks']\r\n m = 0\r\n for a in range(mask.shape[2]):\r\n \r\n img = cv2.imread(image_path)\r\n \r\n\r\n for b in range(img.shape[2]):\r\n \r\n img[:,:,b] = img[:,:,b] * mask[:,:,a]\r\n m+=1\r\n extracted_objects = img[np.ix_(mask[:,:,a].any(1), mask[:,:,a].any(0))]\r\n \r\n if save_extracted_objects == True:\r\n save_path = os.path.join(\"segmented_object\" + \"_\" + str(m) + \".jpg\")\r\n cv2.imwrite(save_path, extracted_objects)\r\n \r\n\r\n if mask_points_values == True:\r\n mask = r['masks']\r\n contain_val = []\r\n for a in range(mask.shape[2]):\r\n m = mask[:,:,a]\r\n mask_values = Mask(m).polygons()\r\n val = mask_values.points\r\n \r\n contain_val.append(val)\r\n\r\n r['masks'] = contain_val\r\n \r\n\r\n extract_mask = extracted_objects\r\n object_val = []\r\n\r\n for a in range(extract_mask.shape[2]):\r\n m = extract_mask[:,:,a]\r\n mask_values = Mask(m).polygons()\r\n val = mask_values.points\r\n object_val.append(val)\r\n\r\n extracted_objects = object_val\r\n\r\n \r\n\r\n if output_image_name is not None:\r\n cv2.imwrite(output_image_name, output)\r\n print(\"Processed image saved successfully in your current working directory.\") \r\n \r\n \"\"\" The mask values of each of the extracted cropped object in the image\r\n is added to the dictionary containing an array of output values:\r\n \"\"\" \r\n \r\n r.update({\"extracted_objects\":extracted_objects})\r\n return r, output\r\n \r\n else:\r\n\r\n if mask_points_values == True:\r\n mask = r['masks']\r\n contain_val = []\r\n for a in range(mask.shape[2]):\r\n m = mask[:,:,a]\r\n mask_values = Mask(m).polygons()\r\n val = mask_values.points\r\n contain_val.append(val)\r\n\r\n r['masks'] = contain_val\r\n\r\n \r\n\r\n if output_image_name is not None:\r\n cv2.imwrite(output_image_name, output)\r\n print(\"Processed image saved successfully in your current working directory.\") \r\n\r\n return r, output \r\n\r\n \r\n \r\n\r\n def segmentFrame(self, frame, show_bboxes = False, segment_target_classes = None,mask_points_values = False, output_image_name = None):\r\n segmask, output = self.segmentImage(frame, show_bboxes = show_bboxes, process_frame=True, \r\n segment_target_classes = segment_target_classes, mask_points_values = mask_points_values, output_image_name = output_image_name)\r\n if output_image_name is not None:\r\n cv2.imwrite(output_image_name, output)\r\n print(\"Processed image saved successfully in your current working directory.\")\r\n\r\n return segmask, output\r\n \r\n \r\n \r\n \r\n\r\n def process_video(self, video_path, show_bboxes = False, segment_target_classes = None, mask_points_values = False, \r\n output_video_name = None, frames_per_second = None):\r\n capture = cv2.VideoCapture(video_path)\r\n width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))\r\n height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))\r\n codec = cv2.VideoWriter_fourcc(*'DIVX')\r\n \r\n if frames_per_second is not None:\r\n save_video = cv2.VideoWriter(output_video_name, codec, frames_per_second, (width, height))\r\n counter = 0\r\n start = time.time() \r\n \r\n \r\n while True:\r\n counter +=1\r\n ret, frame = capture.read()\r\n if ret:\r\n #apply segmentation mask\r\n \r\n \r\n segmask, output = self.segmentImage(frame, show_bboxes=show_bboxes, segment_target_classes= segment_target_classes,\r\n process_frame=True, mask_points_values=mask_points_values)\r\n print(\"No. of frames:\", counter)\r\n \r\n \r\n output = cv2.resize(output, (width,height), interpolation=cv2.INTER_AREA)\r\n\r\n if output_video_name is not None:\r\n save_video.write(output)\r\n\r\n output = cv2.resize(output, (width,height), interpolation=cv2.INTER_AREA)\r\n\r\n if output_video_name is not None:\r\n save_video.write(output)\r\n\r\n \r\n\r\n else:\r\n break \r\n \r\n end = time.time() \r\n print(f\"Processed {counter} frames in {end-start:.1f} seconds\") \r\n \r\n \r\n capture.release()\r\n if frames_per_second is not None:\r\n save_video.release() \r\n\r\n return segmask, output \r\n \r\n \r\n\r\n def process_camera(self, cam, show_bboxes = False, segment_target_classes = None, mask_points_values = False, output_video_name = None, frames_per_second = None, show_frames = None, frame_name = None, verbose = None, check_fps = False):\r\n capture = cam\r\n if output_video_name is not None:\r\n width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))\r\n height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))\r\n save_video = cv2.VideoWriter(output_video_name, cv2.VideoWriter_fourcc(*'DIVX'), frames_per_second, (width, height))\r\n \r\n counter = 0\r\n \r\n start = datetime.now() \r\n\r\n \r\n while True:\r\n \r\n ret, frame = capture.read()\r\n if ret:\r\n \r\n segmask, output = self.segmentImage(frame, show_bboxes=show_bboxes,segment_target_classes= segment_target_classes,\r\n process_frame=True, mask_points_values=mask_points_values)\r\n counter += 1 \r\n \r\n output = cv2.resize(output, (width,height), interpolation=cv2.INTER_AREA)\r\n\r\n if show_frames == True:\r\n if frame_name is not None:\r\n cv2.imshow(frame_name, output)\r\n \r\n if cv2.waitKey(25) & 0xFF == ord('q'):\r\n break \r\n\r\n if output_video_name is not None:\r\n save_video.write(output)\r\n\r\n elif counter == 30:\r\n break \r\n \r\n \r\n end = datetime.now()\r\n if check_fps == True:\r\n timetaken = (end-start).total_seconds()\r\n \r\n out = counter / timetaken\r\n print(f\"{out:.3f} frames per second\") \r\n\r\n if verbose is not None: \r\n print(f\"Processed {counter} frames in {timetaken:.1f} seconds\") \r\n \r\n capture.release()\r\n\r\n if output_video_name is not None:\r\n save_video.release() \r\n\r\n return segmask, output \r\n\r\n \r\n\r\n\r\n\r\n\r\n#############################################################\r\n#############################################################\r\n\"\"\" CLASS FOR PERFORMING INFERENCE WITH A CUSTOM MODEL \"\"\"\r\n#############################################################\r\n#############################################################\r\n\r\n\r\n\r\n\r\nclass custom_segmentation:\r\n def __init__(self):\r\n self.model_dir = os.getcwd()\r\n\r\n def inferConfig(self,name = None, network_backbone = \"resnet101\", num_classes = 1, class_names = [\"BG\"], batch_size = 1, detection_threshold = 0.7, \r\n image_max_dim = 512, image_min_dim = 512, image_resize_mode =\"square\", gpu_count = 1):\r\n self.config = Config(BACKBONE = network_backbone, NUM_CLASSES = 1 + num_classes, class_names = class_names, \r\n IMAGES_PER_GPU = batch_size, IMAGE_MAX_DIM = image_max_dim, IMAGE_MIN_DIM = image_min_dim, DETECTION_MIN_CONFIDENCE = detection_threshold,\r\n IMAGE_RESIZE_MODE = image_resize_mode,GPU_COUNT = gpu_count)\r\n \r\n def load_model(self, model_path):\r\n #load the weights for COCO\r\n self.model = MaskRCNN(mode=\"inference\", model_dir = self.model_dir, config=self.config)\r\n self.model.load_weights(model_path, by_name=True)\r\n \r\n def segmentImage(self, image_path, show_bboxes = False, extract_segmented_objects = False, save_extracted_objects = False,\r\n mask_points_values = False, process_frame = False,output_image_name = None, verbose = None):\r\n\r\n if process_frame ==False:\r\n image = cv2.imread(image_path)\r\n\r\n else:\r\n image = image_path\r\n\r\n new_img = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\r\n # Run detection\r\n if verbose is not None:\r\n print(\"Processing image...\")\r\n results = self.model.detect([new_img]) \r\n\r\n\r\n r = results[0] \r\n \r\n if show_bboxes == False:\r\n output = display_instances(image, r['rois'], r['masks'], r['class_ids'], self.config.class_names)\r\n if output_image_name is not None:\r\n cv2.imwrite(output_image_name, output)\r\n print(\"Processed image saved successfully in your current working directory.\") \r\n \r\n \"\"\" Code to extract and crop out each of the objects segmented in an image \"\"\"\r\n \r\n if extract_segmented_objects == False:\r\n \r\n if mask_points_values == True:\r\n mask = r['masks']\r\n contain_val = []\r\n for a in range(mask.shape[2]):\r\n m = mask[:,:,a]\r\n mask_values = Mask(m).polygons()\r\n val = mask_values.points\r\n contain_val.append(val)\r\n\r\n r['masks'] = contain_val\r\n\r\n\r\n return r, output\r\n\r\n\r\n\r\n else:\r\n \r\n\r\n mask = r['masks']\r\n m = 0\r\n for a in range(mask.shape[2]):\r\n if process_frame == False:\r\n img = cv2.imread(image_path)\r\n else:\r\n img = image_path\r\n for b in range(img.shape[2]):\r\n \r\n img[:,:,b] = img[:,:,b] * mask[:,:,a]\r\n m+=1\r\n extracted_objects = img[np.ix_(mask[:,:,a].any(1), mask[:,:,a].any(0))]\r\n \r\n if save_extracted_objects == True:\r\n save_path = os.path.join(\"segmented_object\" + \"_\" + str(m) + \".jpg\")\r\n cv2.imwrite(save_path, extracted_objects)\r\n \r\n \r\n if mask_points_values == True:\r\n mask = r['masks']\r\n contain_val = []\r\n for a in range(mask.shape[2]):\r\n m = mask[:,:,a]\r\n mask_values = Mask(m).polygons()\r\n val = mask_values.points\r\n \r\n contain_val.append(val)\r\n\r\n r['masks'] = contain_val\r\n\r\n\r\n extract_mask = extracted_objects\r\n object_val = []\r\n\r\n for a in range(extract_mask.shape[2]):\r\n m = extract_mask[:,:,a]\r\n mask_values = Mask(m).polygons()\r\n val = mask_values.points\r\n object_val.append(val)\r\n\r\n extracted_objects = object_val\r\n\r\n \r\n \"\"\" The mask values of each of the extracted cropped object in the image\r\n is added to the dictionary containing an array of output values:\r\n \"\"\" \r\n r.update({\"extracted_objects\":extracted_objects})\r\n\r\n return r, output\r\n \r\n \r\n else:\r\n output = display_box_instances(image, r['rois'], r['masks'], r['class_ids'], self.config.class_names, r['scores'])\r\n\r\n \"\"\" Code to extract and crop out each of the objects segmented in an image \"\"\"\r\n\r\n if extract_segmented_objects == True:\r\n mask = r['masks']\r\n m = 0\r\n for a in range(mask.shape[2]):\r\n if process_frame == False:\r\n img = cv2.imread(image_path)\r\n else:\r\n img = image_path\r\n\r\n for b in range(img.shape[2]):\r\n \r\n img[:,:,b] = img[:,:,b] * mask[:,:,a]\r\n m+=1\r\n extracted_objects = img[np.ix_(mask[:,:,a].any(1), mask[:,:,a].any(0))]\r\n \r\n if save_extracted_objects == True:\r\n save_path = os.path.join(\"segmented_object\" + \"_\" + str(m) + \".jpg\")\r\n cv2.imwrite(save_path, extracted_objects)\r\n \r\n \r\n\r\n if mask_points_values == True:\r\n mask = r['masks']\r\n contain_val = []\r\n for a in range(mask.shape[2]):\r\n m = mask[:,:,a]\r\n mask_values = Mask(m).polygons()\r\n val = mask_values.points\r\n \r\n contain_val.append(val)\r\n\r\n r['masks'] = contain_val\r\n \r\n\r\n extract_mask = extracted_objects\r\n object_val = []\r\n\r\n for a in range(extract_mask.shape[2]):\r\n m = extract_mask[:,:,a]\r\n mask_values = Mask(m).polygons()\r\n val = mask_values.points\r\n object_val.append(val)\r\n\r\n extracted_objects = object_val\r\n\r\n \r\n\r\n if output_image_name is not None:\r\n cv2.imwrite(output_image_name, output)\r\n print(\"Processed image saved successfully in your current working directory.\") \r\n \r\n\r\n \"\"\" The mask values of each of the extracted cropped object in the image\r\n is added to the dictionary containing an array of output values:\r\n \"\"\"\r\n \r\n r.update({\"extracted_objects\":extracted_objects})\r\n return r, output\r\n \r\n else:\r\n \r\n if mask_points_values == True:\r\n mask = r['masks']\r\n contain_val = []\r\n for a in range(mask.shape[2]):\r\n m = mask[:,:,a]\r\n mask_values = Mask(m).polygons()\r\n val = mask_values.points\r\n contain_val.append(val)\r\n\r\n r['masks'] = contain_val\r\n\r\n \r\n\r\n if output_image_name is not None:\r\n cv2.imwrite(output_image_name, output)\r\n print(\"Processed image saved successfully in your current working directory.\") \r\n\r\n return r, output \r\n\r\n \r\n \r\n \r\n \r\n\r\n\r\n def segmentFrame(self, frame, show_bboxes = False, mask_points_values = False, output_image_name = None, verbose= None):\r\n\r\n segmask, output = self.segmentImage(frame, show_bboxes=show_bboxes, process_frame=True, mask_points_values=mask_points_values)\r\n \r\n if output_image_name is not None:\r\n cv2.imwrite(output_image_name, output)\r\n print(\"Processed image saved successfully in your current working directory.\")\r\n\r\n return segmask, output\r\n\r\n \r\n\r\n \r\n def process_video(self, video_path, show_bboxes = False, mask_points_values = False, output_video_name = None, frames_per_second = None):\r\n capture = cv2.VideoCapture(video_path)\r\n width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))\r\n height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))\r\n codec = cv2.VideoWriter_fourcc(*'DIVX')\r\n if frames_per_second is not None:\r\n save_video = cv2.VideoWriter(output_video_name, codec, frames_per_second, (width, height))\r\n counter = 0\r\n start = time.time() \r\n \r\n \r\n while True:\r\n counter +=1\r\n ret, frame = capture.read()\r\n if ret:\r\n \r\n segmask, output = self.segmentImage(frame, show_bboxes=show_bboxes,process_frame=True, mask_points_values=mask_points_values)\r\n print(\"No. of frames:\", counter)\r\n \r\n \r\n output = cv2.resize(output, (width,height), interpolation=cv2.INTER_AREA)\r\n\r\n if output_video_name is not None:\r\n save_video.write(output)\r\n\r\n \r\n else:\r\n break \r\n \r\n end = time.time() \r\n print(f\"Processed {counter} frames in {end-start:.1f} seconds\") \r\n \r\n \r\n capture.release()\r\n if frames_per_second is not None:\r\n save_video.release() \r\n\r\n return segmask, output \r\n\r\n \r\n \r\n def process_camera(self, cam, show_bboxes = False, mask_points_values = False, output_video_name = None, frames_per_second = None, show_frames = None, frame_name = None, verbose = None, check_fps = False):\r\n capture = cam\r\n \r\n if output_video_name is not None:\r\n width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))\r\n height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))\r\n codec = cv2.VideoWriter_fourcc(*'DIVX')\r\n save_video = cv2.VideoWriter(output_video_name, codec, frames_per_second, (width, height))\r\n\r\n counter = 0\r\n start = datetime.now() \r\n\r\n \r\n while True:\r\n \r\n ret, frame = capture.read()\r\n if ret:\r\n \r\n segmask, output = self.segmentImage(frame, show_bboxes=False,process_frame=True, mask_points_values=mask_points_values)\r\n\r\n \r\n output = cv2.resize(output, (width,height), interpolation=cv2.INTER_AREA)\r\n\r\n if show_frames == True:\r\n if frame_name is not None:\r\n cv2.imshow(frame_name, output)\r\n \r\n if cv2.waitKey(25) & 0xFF == ord('q'):\r\n break \r\n\r\n if output_video_name is not None:\r\n save_video.write(output)\r\n\r\n \r\n \r\n elif counter == 30:\r\n break \r\n \r\n end = datetime.now() \r\n \r\n \r\n if check_fps == True:\r\n timetaken = (end-start).total_seconds()\r\n fps = counter/timetaken\r\n print(f\"{fps} frames per seconds\") \r\n\r\n if verbose is not None:\r\n print(f\"Processed {counter} frames in {timetaken:.1f} seconds\") \r\n \r\n \r\n capture.release()\r\n\r\n if output_video_name is not None:\r\n save_video.release() \r\n \r\n\r\n return segmask, output \r\n\r\n \r\n\r\n\r\n\r\n################VISUALIZATION CODE ##################\r\n\r\n\r\n\r\n\r\ndef random_colors(N, bright=True):\r\n \"\"\"\r\n Generate random colors.\r\n To get visually distinct colors, generate them in HSV space then\r\n convert to RGB.\r\n \"\"\"\r\n brightness = 1.0 if bright else 0.7\r\n hsv = [(i / N, 1, brightness) for i in range(N)]\r\n colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))\r\n random.shuffle(colors)\r\n return colors\r\n\r\n\r\ndef apply_mask(image, mask, color, alpha=0.5):\r\n \"\"\"Apply the given mask to the image.\r\n \"\"\"\r\n for c in range(3):\r\n image[:, :, c] = np.where(mask == 1,\r\n image[:, :, c] *\r\n (1 - alpha) + alpha * color[c] * 255,\r\n image[:, :, c])\r\n return image\r\n\r\n \r\n\r\n\r\ndef display_instances(image, boxes, masks, class_ids, class_name):\r\n \r\n n_instances = boxes.shape[0]\r\n colors = random_colors(n_instances)\r\n\r\n \r\n assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0]\r\n\r\n for i, color in enumerate(colors):\r\n mask = masks[:, :, i]\r\n\r\n image = apply_mask(image, mask, color)\r\n\r\n\r\n return image\r\n\r\n\r\n\r\n\r\n\r\ndef display_box_instances(image, boxes, masks, class_ids, class_name, scores):\r\n \r\n n_instances = boxes.shape[0]\r\n colors = random_colors(n_instances)\r\n\r\n \r\n assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0]\r\n\r\n for i, color in enumerate(colors):\r\n if not np.any(boxes[i]):\r\n continue\r\n\r\n y1, x1, y2, x2 = boxes[i]\r\n label = class_name[class_ids[i]]\r\n score = scores[i] if scores is not None else None\r\n caption = '{} {:.2f}'.format(label, score) if score else label\r\n mask = masks[:, :, i]\r\n\r\n image = apply_mask(image, mask, color)\r\n color_rec = [int(c) for c in np.array(colors[i]) * 255]\r\n image = cv2.rectangle(image, (x1, y1), (x2, y2), color_rec, 2)\r\n image = cv2.putText(\r\n image, caption, (x1, y1), cv2.FONT_HERSHEY_COMPLEX, 0.5, color = (255, 255, 255))\r\n\r\n return image\r\n\r\n\r\n\r\n" ]
[ [ "numpy.array", "numpy.where", "numpy.any", "numpy.stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
oeway/torch-em
[ "1a0eca1c9da5748ab48708b1b1fe31bb3c7e8e09", "1a0eca1c9da5748ab48708b1b1fe31bb3c7e8e09" ]
[ "torch_em/shallow2deep/shallow2deep_model.py", "torch_em/data/pseudo_label_dataset.py" ]
[ "import os\nimport pickle\nimport torch\nfrom torch_em.util import get_trainer, import_bioimageio_model\nfrom .prepare_shallow2deep import _get_filters, _apply_filters\n\n# optional imports only needed for using ilastik api for the predictio\ntry:\n import lazyflow\n from ilastik.experimental.api import from_project_file\n # set the number of threads used by ilastik to 0.\n # otherwise it does not work inside of the torch loader (and we want to limit number of threads anyways)\n # see https://github.com/ilastik/ilastik/issues/2517\n lazyflow.request.Request.reset_thread_pool(0)\nexcept ImportError:\n from_project_file = None\ntry:\n from xarray import DataArray\nexcept ImportError:\n DataArray = None\n\n\nclass RFWithFilters:\n def __init__(self, rf_path, ndim, filter_config, output_channel):\n with open(rf_path, \"rb\") as f:\n self.rf = pickle.load(f)\n self.filters_and_sigmas = _get_filters(ndim, filter_config)\n self.output_channel = output_channel\n\n def __call__(self, x):\n features = _apply_filters(x, self.filters_and_sigmas)\n assert features.shape[1] == self.rf.n_features_in_, f\"{features.shape[1]}, {self.rf.n_features_in_}\"\n out = self.rf.predict_proba(features)[:, self.output_channel].reshape(x.shape).astype(\"float32\")\n return out\n\n\n# TODO need installation that does not downgrade numpy; talk to Dominik about this\n# currently ilastik-api deps are installed via:\n# conda install --strict-channel-priority -c ilastik-forge/label/freepy -c conda-forge ilastik-core\n# print hint on how to install it once this is more stable\nclass IlastikPredicter:\n def __init__(self, ilp_path, ndim, output_channel=None):\n assert from_project_file is not None\n assert DataArray is not None\n assert ndim in (2, 3)\n self.ilp = from_project_file(ilp_path)\n self.dims = (\"y\", \"x\") if ndim == 2 else (\"z\", \"y\", \"x\")\n self.output_channel = output_channel\n\n def __call__(self, x):\n assert x.ndim == len(self.dims), f\"{x.ndim}, {self.dims}\"\n out = self.ilp.predict(DataArray(x, dims=self.dims)).values\n if self.output_channel is not None:\n out = out[..., self.output_channel]\n return out\n\n\nclass Shallow2DeepModel:\n\n @staticmethod\n def load_model(checkpoint, device):\n try:\n model = get_trainer(checkpoint, device=device).model\n return model\n except Exception as e:\n print(\"Could not load torch_em checkpoint from\", checkpoint, \"due to exception:\", e)\n print(\"Trying to load as bioimageio model instead\")\n model = import_bioimageio_model(checkpoint, device=device)[0]\n model.eval()\n return model\n\n @staticmethod\n def load_rf(rf_config, rf_channel):\n if len(rf_config) == 3: # random forest path and feature config\n rf_path, ndim, filter_config = rf_config\n assert os.path.exists(rf_path)\n return RFWithFilters(rf_path, ndim, filter_config, rf_channel)\n elif len(rf_config) == 2: # ilastik project and dimensionality\n ilp_path, ndim = rf_config\n return IlastikPredicter(ilp_path, ndim, rf_channel)\n else:\n raise ValueError(f\"Invalid rf config: {rf_config}\")\n\n def __init__(self, checkpoint, rf_config, device, rf_channel=1):\n self.model = self.load_model(checkpoint, device)\n self.rf_predicter = self.load_rf(rf_config, rf_channel)\n self.device = device\n\n self.checkpoint = checkpoint\n self.rf_config = rf_config\n self.device = device\n\n def __call__(self, x):\n out = self.rf_predicter(x[0, 0].numpy())\n out = torch.from_numpy(out[None, None]).to(self.device)\n out = self.model(out)\n return out\n\n # need to overwrite pickle to support the rf / ilastik predicter\n def __getstate__(self):\n state = self.__dict__.copy()\n del state[\"rf_predicter\"]\n return state\n\n def __setstate__(self, state):\n state[\"rf_predicter\"] = self.load_rf(state[\"rf_config\"])\n self.__dict__.update(state)\n", "import torch\nfrom .raw_dataset import RawDataset\nfrom ..util import ensure_tensor_with_channels\n\n\nclass PseudoLabelDataset(RawDataset):\n def __init__(\n self,\n raw_path,\n raw_key,\n patch_shape,\n pseudo_labeler,\n raw_transform=None,\n label_transform=None,\n transform=None,\n roi=None,\n dtype=torch.float32,\n n_samples=None,\n sampler=None,\n ndim=None,\n with_channels=False,\n labeler_device=None,\n ):\n super().__init__(raw_path, raw_key, patch_shape, raw_transform=raw_transform, transform=transform,\n roi=roi, dtype=dtype, n_samples=n_samples, sampler=sampler,\n ndim=ndim, with_channels=with_channels)\n self.pseudo_labeler = pseudo_labeler\n self.label_transform = label_transform\n self.labeler_device = next(pseudo_labeler.parameters()).device if labeler_device is None else labeler_device\n\n def __getitem__(self, index):\n raw = self._get_sample(index)\n\n if self.raw_transform is not None:\n raw = self.raw_transform(raw)\n\n if self.transform is not None:\n raw = self.transform(raw)[0]\n if self.trafo_halo is not None:\n raw = self.crop(raw)\n\n raw = ensure_tensor_with_channels(raw, ndim=self._ndim, dtype=self.dtype)\n with torch.no_grad():\n labels = self.pseudo_labeler(raw[None].to(self.labeler_device))[0]\n if self.label_transform is not None:\n labels = self.label_transform(labels)\n labels = ensure_tensor_with_channels(labels, ndim=self._ndim)\n\n return raw, labels\n" ]
[ [ "torch.from_numpy" ], [ "torch.no_grad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ralic/RadeonProRenderBlenderAddon
[ "ff4ede164c1e1e909f182be709422bc8c8878b1c" ]
[ "src/rprblender/engine/render_engine.py" ]
[ "#**********************************************************************\n# Copyright 2020 Advanced Micro Devices, Inc\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 socket\nimport time\nimport datetime\nimport math\nimport numpy as np\n\nimport pyrpr\n\nfrom rprblender import utils\nfrom .engine import Engine\nfrom rprblender.export import world, camera, object, instance, particle\nfrom rprblender.utils import render_stamp\nfrom rprblender.utils.conversion import perfcounter_to_str\nfrom rprblender.utils.user_settings import get_user_settings\nfrom rprblender import bl_info\n\nfrom rprblender.utils import logging\nlog = logging.Log(tag='RenderEngine')\n\n\nMAX_RENDER_ITERATIONS = 32\n\n\nclass RenderEngine(Engine):\n \"\"\" Final render engine \"\"\"\n\n TYPE = 'FINAL'\n\n def __init__(self, rpr_engine):\n super().__init__(rpr_engine)\n\n self.width = 0\n self.height = 0\n\n self.is_synced = False\n self.render_layer_name = None\n\n self.render_samples = 0\n self.current_sample = 0\n self.render_update_samples = 1\n self.render_time = 0\n self.current_render_time = 0\n self.sync_time = 0\n\n self.status_title = \"\"\n\n self.tile_size = None\n self.camera_data: camera.CameraData = None\n self.tile_order = None\n\n self.use_contour = False\n\n self.world_backplate = None\n\n self.render_stamp_text = \"\"\n self.render_iteration = 0\n\n self.cryptomatte_allowed = False # only Full mode supports cryptomatte AOVs\n\n def notify_status(self, progress, info):\n \"\"\" Display export/render status \"\"\"\n self.rpr_engine.update_progress(progress)\n self.rpr_engine.update_stats(self.status_title, info)\n\n def _render(self):\n athena_data = {}\n\n time_begin = time.perf_counter()\n athena_data['Start Time'] = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n athena_data['End Status'] = \"successful\"\n\n self.current_sample = 0\n is_adaptive = self.rpr_context.is_aov_enabled(pyrpr.AOV_VARIANCE)\n if is_adaptive:\n all_pixels = active_pixels = self.rpr_context.width * self.rpr_context.height\n\n while True:\n if self.rpr_engine.test_break():\n athena_data['End Status'] = \"cancelled\"\n break\n\n self.current_render_time = time.perf_counter() - time_begin\n is_adaptive_active = is_adaptive and self.current_sample >= \\\n self.rpr_context.get_parameter(pyrpr.CONTEXT_ADAPTIVE_SAMPLING_MIN_SPP)\n\n # if less than update_samples left, use the remainder\n update_samples = min(self.render_update_samples,\n self.render_samples - self.current_sample)\n\n # we report time/iterations left as fractions if limit enabled\n time_str = f\"{self.current_render_time:.1f}/{self.render_time}\" if self.render_time \\\n else f\"{self.current_render_time:.1f}\"\n\n # percent done is one of percent iterations or percent time so pick whichever is greater\n progress = max(\n self.current_sample / self.render_samples,\n self.current_render_time / self.render_time if self.render_time else 0\n )\n info_str = f\"Render Time: {time_str} sec | \"\\\n f\"Samples: {self.current_sample}/{self.render_samples}\"\n log_str = f\" samples: {self.current_sample} +{update_samples} / {self.render_samples}\"\\\n f\", progress: {progress * 100:.1f}%, time: {self.current_render_time:.2f}\"\n if is_adaptive_active:\n adaptive_progress = max((all_pixels - active_pixels) / all_pixels, 0.0)\n\n progress = max(progress, adaptive_progress)\n info_str += f\" | Adaptive Sampling: {math.floor(adaptive_progress * 100)}%\"\n log_str += f\", active_pixels: {active_pixels}\"\n\n self.notify_status(progress, info_str)\n\n log(log_str)\n\n self.rpr_context.set_parameter(pyrpr.CONTEXT_ITERATIONS, update_samples)\n self.rpr_context.set_parameter(pyrpr.CONTEXT_FRAMECOUNT, self.render_iteration)\n self.rpr_context.render(restart=(self.current_sample == 0))\n\n self.current_sample += update_samples\n\n self.rpr_context.resolve()\n if self.background_filter:\n self.update_background_filter_inputs()\n self.background_filter.run()\n self.update_render_result((0, 0), (self.width, self.height),\n layer_name=self.render_layer_name)\n\n # stop at whichever comes first:\n # max samples or max time if enabled or active_pixels == 0\n if is_adaptive_active:\n active_pixels = self.rpr_context.get_info(pyrpr.CONTEXT_ACTIVE_PIXEL_COUNT, int)\n if active_pixels == 0:\n break\n\n if self.current_sample == self.render_samples:\n break\n\n if self.render_time and self.current_render_time >= self.render_time:\n break\n\n self.render_iteration += 1\n if self.render_iteration > 1 and self.render_update_samples < MAX_RENDER_ITERATIONS and not self.use_contour:\n # progressively increase update samples up to 32\n self.render_update_samples *= 2\n\n if self.image_filter:\n self.notify_status(1.0, \"Applying denoising final image\")\n self.update_image_filter_inputs()\n self.image_filter.run()\n self.update_render_result((0, 0), (self.width, self.height),\n layer_name=self.render_layer_name,\n apply_image_filter=True)\n\n self.apply_render_stamp_to_image()\n\n athena_data['Stop Time'] = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n athena_data['Samples'] = self.current_sample\n\n log.info(f\"Scene synchronization time:\", perfcounter_to_str(self.sync_time))\n log.info(f\"Render time:\", perfcounter_to_str(self.current_render_time))\n self.athena_send(athena_data)\n\n def _render_tiles(self):\n athena_data = {}\n\n tile_iterator = utils.tile_iterator(self.tile_order, self.width, self.height, *self.tile_size)\n tiles_number = tile_iterator.len\n is_adaptive = self.rpr_context.is_aov_enabled(pyrpr.AOV_VARIANCE)\n\n rpr_camera = self.rpr_context.scene.camera\n\n time_begin = time.perf_counter()\n athena_data['Start Time'] = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n athena_data['End Status'] = \"successful\"\n progress = 0.0\n\n for tile_index, (tile_pos, tile_size) in enumerate(tile_iterator()):\n if self.rpr_engine.test_break():\n athena_data['End Status'] = \"cancelled\"\n break\n\n log(f\"Render tile {tile_index} / {tiles_number}: [{tile_pos}, {tile_size}]\")\n\n tile = ((tile_pos[0] / self.width, tile_pos[1] / self.height),\n (tile_size[0] / self.width, tile_size[1] / self.height))\n # set camera for tile\n self.camera_data.export(rpr_camera, tile=tile)\n self.rpr_context.resize(*tile_size)\n\n # export backplate section for tile if backplate present\n if self.world_backplate:\n self.world_backplate.export(self.rpr_context, (self.width, self.height), tile)\n\n sample = 0\n if is_adaptive:\n all_pixels = active_pixels = self.rpr_context.width * self.rpr_context.height\n\n render_iteration = 0\n while True:\n if self.rpr_engine.test_break():\n break\n\n update_samples = min(self.render_update_samples, self.render_samples - sample)\n self.current_render_time = time.perf_counter() - time_begin\n progress = (tile_index + sample/self.render_samples) / tiles_number\n info_str = f\"Render Time: {self.current_render_time:.1f} sec\"\\\n f\" | Tile: {tile_index}/{tiles_number}\"\\\n f\" | Samples: {sample}/{self.render_samples}\"\n log_str = f\" samples: {sample} +{update_samples} / {self.render_samples}\"\\\n f\", progress: {progress * 100:.1f}%, time: {self.current_render_time:.2f}\"\n\n is_adaptive_active = is_adaptive and sample >= \\\n self.rpr_context.get_parameter(pyrpr.CONTEXT_ADAPTIVE_SAMPLING_MIN_SPP)\n if is_adaptive_active:\n adaptive_progress = max((all_pixels - active_pixels) / all_pixels, 0.0)\n progress = max(progress, (tile_index + adaptive_progress) / tiles_number)\n info_str += f\" | Adaptive Sampling: {adaptive_progress * 100:.0f}%\"\n log_str += f\", active_pixels: {active_pixels}\"\n\n self.notify_status(progress, info_str)\n log(log_str)\n\n self.rpr_context.set_parameter(pyrpr.CONTEXT_ITERATIONS, update_samples)\n self.rpr_context.set_parameter(pyrpr.CONTEXT_FRAMECOUNT, render_iteration)\n self.rpr_context.render(restart=(sample == 0))\n\n sample += update_samples\n\n self.rpr_context.resolve()\n self.update_render_result(tile_pos, tile_size,\n layer_name=self.render_layer_name)\n\n # store maximum actual number of used samples for render stamp info\n self.current_sample = max(self.current_sample, sample)\n\n if is_adaptive_active:\n active_pixels = self.rpr_context.get_info(pyrpr.CONTEXT_ACTIVE_PIXEL_COUNT, int)\n if active_pixels == 0:\n break\n\n if sample == self.render_samples:\n break\n\n render_iteration += 1\n if render_iteration > 1 and self.render_update_samples < MAX_RENDER_ITERATIONS and not self.use_contour:\n # progressively increase update samples up to 32\n self.render_update_samples *= 2\n\n if self.image_filter and not self.rpr_engine.test_break():\n self.update_image_filter_inputs(tile_pos)\n\n if self.image_filter and not self.rpr_engine.test_break():\n self.notify_status(1.0, \"Applying denoising final image\")\n\n # getting already rendered images for every render pass\n result = self.rpr_engine.get_result()\n render_passes = result.layers[self.render_layer_name].passes\n length = sum((len(p.rect) * p.channels for p in render_passes))\n images = np.empty(length, dtype=np.float32)\n render_passes.foreach_get('rect', images)\n\n # updating points\n result = self.rpr_engine.begin_result(\n 0, 0, self.width, self.height,\n layer=self.render_layer_name)\n\n render_passes = result.layers[0].passes\n pos = 0\n for p in render_passes:\n length = len(p.rect) * p.channels\n\n # we will update only Combined pass\n if p.name == \"Combined\":\n self.image_filter.run()\n image = self.image_filter.get_data()\n images[pos: pos + length] = image.flatten()\n break\n\n pos += length\n\n render_passes.foreach_set('rect', images)\n\n self.rpr_engine.end_result(result)\n\n if not self.rpr_engine.test_break():\n self.apply_render_stamp_to_image()\n\n athena_data['Stop Time'] = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n athena_data['Samples'] = round(self.render_samples * progress)\n\n log.info(f\"Scene synchronization time:\", perfcounter_to_str(self.sync_time))\n log.info(f\"Render time:\", perfcounter_to_str(self.current_render_time))\n\n self.athena_send(athena_data)\n\n def render(self):\n if not self.is_synced:\n return\n\n self.rpr_context.sync_auto_adapt_subdivision()\n self.rpr_context.sync_portal_lights()\n\n log(f\"Start render [{self.width}, {self.height}]\")\n self.notify_status(0, \"Start render\")\n\n if self.tile_size:\n self._render_tiles()\n else:\n self._render()\n\n self.notify_status(1, \"Finish render\")\n log('Finish render')\n\n def _init_rpr_context(self, scene):\n scene.rpr.init_rpr_context(self.rpr_context, use_contour_integrator=self.use_contour)\n\n self.rpr_context.scene.set_name(scene.name)\n\n def sync(self, depsgraph):\n log('Start syncing')\n\n # Preparations for syncing\n self.is_synced = False\n\n self.sync_time = time.perf_counter()\n\n scene = depsgraph.scene\n view_layer = depsgraph.view_layer\n material_override = view_layer.material_override\n\n self.render_layer_name = view_layer.name\n self.status_title = f\"{scene.name}: {self.render_layer_name}\"\n\n self.notify_status(0, \"Start syncing\")\n\n self.use_contour = scene.rpr.is_contour_used()\n self._init_rpr_context(scene)\n\n border = ((0, 0), (1, 1)) if not scene.render.use_border else \\\n ((scene.render.border_min_x, scene.render.border_min_y),\n (scene.render.border_max_x - scene.render.border_min_x, scene.render.border_max_y - scene.render.border_min_y))\n\n screen_width = int(scene.render.resolution_x * scene.render.resolution_percentage / 100)\n screen_height = int(scene.render.resolution_y * scene.render.resolution_percentage / 100)\n\n self.width = int(screen_width * border[1][0])\n self.height = int(screen_height * border[1][1])\n\n self.rpr_context.resize(self.width, self.height)\n\n if self.use_contour:\n scene.rpr.export_contour_mode(self.rpr_context)\n\n self.rpr_context.blender_data['depsgraph'] = depsgraph\n\n # EXPORT OBJECTS\n objects_len = len(depsgraph.objects)\n for i, obj in enumerate(self.depsgraph_objects(depsgraph)):\n self.notify_status(0, \"Syncing object (%d/%d): %s\" % (i, objects_len, obj.name))\n\n # the correct collection visibility info is stored in original object\n indirect_only = obj.original.indirect_only_get(view_layer=view_layer)\n object.sync(self.rpr_context, obj,\n indirect_only=indirect_only, material_override=material_override,\n frame_current=scene.frame_current, use_contour=self.use_contour)\n\n if self.rpr_engine.test_break():\n log.warn(\"Syncing stopped by user termination\")\n return\n\n # EXPORT INSTANCES\n instances_len = len(depsgraph.object_instances)\n last_instances_percent = 0\n self.notify_status(0, \"Syncing instances 0%\")\n\n for i, inst in enumerate(self.depsgraph_instances(depsgraph)):\n instances_percent = (i * 100) // instances_len\n if instances_percent > last_instances_percent:\n self.notify_status(0, f\"Syncing instances {instances_percent}%\")\n last_instances_percent = instances_percent\n\n indirect_only = inst.parent.original.indirect_only_get(view_layer=view_layer)\n instance.sync(self.rpr_context, inst,\n indirect_only=indirect_only, material_override=material_override,\n frame_current=scene.frame_current, use_contour=self.use_contour)\n\n if self.rpr_engine.test_break():\n log.warn(\"Syncing stopped by user termination\")\n return\n\n self.notify_status(0, \"Syncing instances 100%\")\n\n # EXPORT CAMERA\n camera_key = object.key(scene.camera) # current camera key\n rpr_camera = self.rpr_context.create_camera(camera_key)\n self.rpr_context.scene.set_camera(rpr_camera)\n\n # Camera object should be taken from depsgrapgh objects.\n # Use bpy.scene.camera if none found\n camera_obj = depsgraph.objects.get(camera_key, None)\n if not camera_obj:\n camera_obj = scene.camera\n\n self.camera_data = camera.CameraData.init_from_camera(camera_obj.data, camera_obj.matrix_world,\n screen_width / screen_height, border)\n\n if scene.rpr.is_tile_render_available:\n if scene.camera.data.type == 'PANO':\n log.warn(\"Tiles rendering is not supported for Panoramic camera\")\n else:\n # create adaptive subdivision camera to use total render area for calculations\n subdivision_camera_key = camera_key + \".RPR_ADAPTIVE_SUBDIVISION_CAMERA\"\n subdivision_camera = self.rpr_context.create_camera(subdivision_camera_key)\n self.camera_data.export(subdivision_camera)\n self.rpr_context.scene.set_subdivision_camera(subdivision_camera)\n\n # apply tiles settings\n self.tile_size = (min(self.width, scene.rpr.tile_x), min(self.height, scene.rpr.tile_y))\n self.tile_order = scene.rpr.tile_order\n self.rpr_context.resize(*self.tile_size)\n\n else:\n self.camera_data.export(rpr_camera)\n\n # Environment is synced once per frame\n if scene.world.is_evaluated: # for some reason World data can came in unevaluated\n world_data = scene.world\n else:\n world_data = scene.world.evaluated_get(depsgraph)\n world_settings = world.sync(self.rpr_context, world_data)\n self.world_backplate = world_settings.backplate\n\n # SYNC MOTION BLUR\n self.rpr_context.do_motion_blur = scene.render.use_motion_blur and \\\n not math.isclose(scene.camera.data.rpr.motion_blur_exposure, 0.0)\n\n if self.rpr_context.do_motion_blur:\n self.sync_motion_blur(depsgraph)\n rpr_camera.set_exposure(scene.camera.data.rpr.motion_blur_exposure)\n self.set_motion_blur_mode(scene)\n\n # EXPORT PARTICLES\n # Note: particles should be exported after motion blur,\n # otherwise prev_location of particle will be (0, 0, 0)\n self.notify_status(0, \"Syncing particles\")\n for obj in self.depsgraph_objects(depsgraph):\n particle.sync(self.rpr_context, obj)\n\n # objects linked to scene as a collection are instanced, so walk thru them for particles\n for entry in self.depsgraph_instances(depsgraph):\n particle.sync(self.rpr_context, entry.instance_object)\n\n # EXPORT: AOVS, adaptive sampling, shadow catcher, denoiser\n enable_adaptive = scene.rpr.limits.noise_threshold > 0.0\n view_layer.rpr.export_aovs(view_layer, self.rpr_context, self.rpr_engine, enable_adaptive, self.cryptomatte_allowed)\n\n if enable_adaptive:\n # if adaptive is enable turn on aov and settings\n self.rpr_context.enable_aov(pyrpr.AOV_VARIANCE)\n scene.rpr.limits.set_adaptive_params(self.rpr_context)\n\n # Image filter\n image_filter_settings = view_layer.rpr.denoiser.get_settings(scene)\n image_filter_settings['resolution'] = (self.width, self.height)\n self.setup_image_filter(image_filter_settings)\n\n # Shadow catcher\n if scene.rpr.render_quality != 'FULL':\n self.rpr_context.sync_catchers(False)\n background_filter_settings = {\n 'enable': scene.render.film_transparent,\n 'resolution': (self.width, self.height),\n }\n self.setup_background_filter(background_filter_settings)\n else:\n self.rpr_context.sync_catchers(scene.render.film_transparent)\n\n # SET rpr_context parameters\n self.rpr_context.set_parameter(pyrpr.CONTEXT_PREVIEW, False)\n scene.rpr.export_ray_depth(self.rpr_context)\n scene.rpr.export_pixel_filter(self.rpr_context)\n\n self.render_samples, self.render_time = (scene.rpr.limits.max_samples, scene.rpr.limits.seconds)\n\n if scene.rpr.render_quality == 'FULL2':\n if self.use_contour:\n self.render_update_samples = 1\n else:\n self.render_update_samples = scene.rpr.limits.update_samples_rpr2\n else:\n self.render_update_samples = scene.rpr.limits.update_samples\n\n if scene.rpr.use_render_stamp:\n self.render_stamp_text = self.prepare_scene_stamp_text(scene)\n\n self.sync_time = time.perf_counter() - self.sync_time\n\n self.is_synced = True\n self.notify_status(0, \"Finish syncing\")\n log('Finish sync')\n\n def athena_send(self, data: dict):\n if not (utils.IS_WIN or utils.IS_MAC):\n return\n\n settings = get_user_settings()\n if not settings.collect_stat:\n return\n\n from rprblender.utils import athena\n if athena.is_disabled():\n return\n\n devices = settings.final_devices\n\n data['CPU Enabled'] = devices.cpu_state\n for i, gpu_state in enumerate(devices.available_gpu_states):\n data[f'GPU{i} Enabled'] = gpu_state\n\n data['Resolution'] = (self.width, self.height)\n data['Number Lights'] = sum(1 for o in self.rpr_context.scene.objects\n if isinstance(o, pyrpr.Light))\n data['AOVs Enabled'] = tuple(\n f'RPR_{v}' for v in dir(pyrpr) if v.startswith('AOV_')\n and getattr(pyrpr, v) in self.rpr_context.frame_buffers_aovs\n )\n\n data['Ray Depth'] = self.rpr_context.get_parameter(pyrpr.CONTEXT_MAX_RECURSION)\n data['Shadow Ray Depth'] = self.rpr_context.get_parameter(pyrpr.CONTEXT_MAX_DEPTH_SHADOW)\n data['Reflection Ray Depth'] = \\\n self.rpr_context.get_parameter(pyrpr.CONTEXT_MAX_DEPTH_DIFFUSE, 0) + \\\n self.rpr_context.get_parameter(pyrpr.CONTEXT_MAX_DEPTH_GLOSSY, 0)\n data['Refraction Ray Depth'] = \\\n self.rpr_context.get_parameter(pyrpr.CONTEXT_MAX_DEPTH_REFRACTION, 0) + \\\n self.rpr_context.get_parameter(pyrpr.CONTEXT_MAX_DEPTH_GLOSSY_REFRACTION, 0)\n\n data['Num Polygons'] = sum(\n (o.mesh.poly_count if isinstance(o, pyrpr.Instance) else o.poly_count)\n for o in self.rpr_context.objects.values() if isinstance(o, pyrpr.Shape)\n )\n data['Num Textures'] = len(self.rpr_context.images)\n\n # temporary ignore getting texture sizes with hybrid,\n # until it'll be fixed on hybrid core side\n from . context_hybrid import RPRContext as RPRContextHybrid\n if not isinstance(self.rpr_context, RPRContextHybrid):\n data['Textures Size'] = sum(im.size_byte for im in self.rpr_context.images.values()) \\\n // (1024 * 1024) # in MB\n\n data['RIF Type'] = self.image_filter.settings['filter_type'] if self.image_filter else None\n\n self._update_athena_data(data)\n\n # sending data\n athena.send_data(data)\n\n def _update_athena_data(self, data):\n data['Quality'] = \"full\"\n\n def prepare_scene_stamp_text(self, scene):\n \"\"\" Fill stamp with static scene and render devices info that user can ask for \"\"\"\n text = str(scene.rpr.render_stamp)\n text = text.replace(\"%i\", socket.gethostname())\n\n lights_count = len([\n e for e in self.rpr_context.objects.values()\n if isinstance(e, pyrpr.Light)])\n text = text.replace(\"%sl\", str(lights_count))\n\n objects_count = len([\n e for e in self.rpr_context.objects.values()\n if isinstance(e, (pyrpr.Curve, pyrpr.Shape, pyrpr.HeteroVolume,))\n and hasattr(e, 'is_visible') and e.is_visible\n ])\n text = text.replace(\"%so\", str(objects_count))\n\n cpu_name = pyrpr.Context.cpu_device['name']\n text = text.replace(\"%c\", cpu_name)\n\n selected_gpu_names = ''\n settings = get_user_settings()\n devices = settings.final_devices\n for i, gpu_state in enumerate(devices.available_gpu_states):\n if gpu_state:\n name = pyrpr.Context.gpu_devices[i]['name']\n if selected_gpu_names:\n selected_gpu_names += f\" + {name}\"\n else:\n selected_gpu_names += name\n\n hardware = ''\n render_mode = ''\n if selected_gpu_names:\n hardware = selected_gpu_names\n render_mode = \"GPU\"\n if devices.cpu_state:\n hardware += \" / \"\n render_mode += \" + \"\n if devices.cpu_state:\n hardware += cpu_name\n render_mode = render_mode + \"CPU\"\n text = text.replace(\"%g\", selected_gpu_names)\n text = text.replace(\"%r\", render_mode)\n text = text.replace(\"%h\", hardware)\n\n ver = bl_info['version']\n text = text.replace(\"%b\", f\"v{ver[0]}.{ver[1]}.{ver[2]}\")\n\n return text\n\n def apply_render_stamp_to_image(self):\n \"\"\"\n Apply render stamp if enabled to \"Combined\" view layer pass.\n \"\"\"\n if self.render_stamp_text:\n # fill render iteration info\n text = self.render_stamp_text\n text = text.replace(\"%pt\", time.strftime(\"%H:%M:%S\", time.gmtime(self.current_render_time)))\n text = text.replace(\"%d\", time.strftime(\"%a, %d %b %Y\", time.localtime()))\n text = text.replace(\"%pp\", str(self.current_sample))\n\n try:\n ordered_text_bytes, width, height = \\\n render_stamp.render(text, self.width, self.height)\n except NotImplementedError:\n return\n\n # Write stamp pixels to the RenderResult\n result = self.rpr_engine.begin_result(self.width - width, 0,\n width, height, layer=self.render_layer_name)\n\n for p in result.layers[0].passes:\n p.rect = [e[:p.channels] for e in ordered_text_bytes]\n\n self.rpr_engine.end_result(result)\n" ]
[ [ "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
evanlohn/flowpp
[ "a7b175c226f8a348fc02d50f373732107d58b91a", "a7b175c226f8a348fc02d50f373732107d58b91a" ]
[ "flows_imagenet/create_imagenet_benchmark_datasets.py", "flows_imagenet/launchers/imagenet32_official.py" ]
[ "\"\"\"\nRun the following commands in ~ before running this file\nwget http://image-net.org/small/train_64x64.tar\nwget http://image-net.org/small/valid_64x64.tar\ntar -xvf train_64x64.tar\ntar -xvf valid_64x64.tar\nwget http://image-net.org/small/train_32x32.tar\nwget http://image-net.org/small/valid_32x32.tar\ntar -xvf train_32x32.tar\ntar -xvf valid_32x32.tar\n\"\"\"\n\nimport numpy as np\nimport scipy.ndimage\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nimport sys\nfrom tqdm import tqdm\n\ndef convert_path_to_npy(*, path='~/train_64x64', outfile='~/train_64x64.npy'):\n assert isinstance(path, str), \"Expected a string input for the path\"\n assert os.path.exists(path), \"Input path doesn't exist\"\n files = [f for f in listdir(path) if isfile(join(path, f))]\n print('Number of valid images is:', len(files))\n imgs = []\n for i in tqdm(range(len(files))):\n img = scipy.ndimage.imread(join(path, files[i]))\n img = img.astype('uint8')\n assert img.shape == (64, 64, 3)\n assert np.max(img) <= 255\n assert np.min(img) >= 0\n assert img.dtype == 'uint8'\n assert isinstance(img, np.ndarray)\n imgs.append(img)\n resolution_x, resolution_y = img.shape[0], img.shape[1]\n imgs = np.asarray(imgs).astype('uint8')\n assert imgs.shape[1:] == (resolution_x, resolution_y, 3)\n assert np.max(imgs) <= 255\n assert np.min(imgs) >= 0\n print('Total number of images is:', imgs.shape[0])\n print('All assertions done, dumping into npy file')\n np.save(outfile, imgs)\n\nif __name__ == '__main__':\n convert_path_to_npy(path='~/train_64x64', outfile='~/train_64x64.npy') \n convert_path_to_npy(path='~/valid_64x64', outfile='~/valid_64x64.npy') \n convert_path_to_npy(path='~/train_32x32', outfile='~/train_32x32.npy') \n convert_path_to_npy(path='~/valid_32x32', outfile='~/valid_32x32.npy') \n", "\"\"\"\nNum params: 168955724\nRun it as: mpiexec -n {num_processes} python3.6 -m flows_imagenet.launchers.imagenet32_official from the flows master directory of the git repo. \n num_processes=8 was used for this launcher on a DGX-1 with 8 V100 GPUs and 52GB CPU RAM. \nIf you want to use python3.5, remove the f string in the logdir.\nCaution: The model's really large and it is unlikely you will be able to run it on anything other than a V100 GPU or a TPU pod.\n The model also trains really slowly because of weight normalization in the conv2d and dense layers. To achieve 3.86 bits/dim, it should take 2.5 weeks.\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.distributions import Normal\nfrom tqdm import tqdm\nfrom flows_imagenet.logistic import mixlogistic_logpdf, mixlogistic_logcdf, mixlogistic_invcdf\nfrom flows_imagenet import flow_training_imagenet\n\nDEFAULT_FLOATX = tf.float32\nSTORAGE_FLOATX = tf.float32\n\ndef to_default_floatx(x):\n return tf.cast(x, DEFAULT_FLOATX)\n\ndef at_least_float32(x):\n assert x.dtype in [tf.float16, tf.float32, tf.float64]\n if x.dtype == tf.float16:\n return tf.cast(x, tf.float32)\n return x\n\ndef get_var(var_name, *, ema, initializer, trainable=True, **kwargs):\n \"\"\"forced storage dtype\"\"\"\n assert 'dtype' not in kwargs\n if isinstance(initializer, np.ndarray):\n initializer = initializer.astype(STORAGE_FLOATX.as_numpy_dtype)\n v = tf.get_variable(var_name, dtype=STORAGE_FLOATX, initializer=initializer, trainable=trainable, **kwargs)\n if ema is not None:\n assert isinstance(ema, tf.train.ExponentialMovingAverage)\n v = ema.average(v)\n return v\n\ndef _norm(x, *, axis, g, b, e=1e-5):\n assert x.shape.ndims == g.shape.ndims == b.shape.ndims\n u = tf.reduce_mean(x, axis=axis, keepdims=True)\n s = tf.reduce_mean(tf.squared_difference(x, u), axis=axis, keepdims=True)\n x = (x - u) * tf.rsqrt(s + e)\n return x * g + b\n\ndef norm(x, *, name, ema):\n \"\"\"Layer norm over last axis\"\"\"\n with tf.variable_scope(name):\n dim = int(x.shape[-1])\n _g = get_var('g', ema=ema, shape=[dim], initializer=tf.constant_initializer(1))\n _b = get_var('b', ema=ema, shape=[dim], initializer=tf.constant_initializer(0))\n g, b = map(to_default_floatx, [_g, _b])\n bcast_shape = [1] * (x.shape.ndims - 1) + [dim]\n return _norm(x, g=tf.reshape(g, bcast_shape), b=tf.reshape(b, bcast_shape), axis=-1)\n\ndef int_shape(x):\n return list(map(int, x.shape.as_list())) \n\ndef sumflat(x):\n return tf.reduce_sum(tf.reshape(x, [x.shape[0], -1]), axis=1)\n\ndef inverse_sigmoid(x):\n return -tf.log(tf.reciprocal(x) - 1.)\n\ndef init_normalization(x, *, name, init_scale=1., init, ema):\n with tf.variable_scope(name):\n g = get_var('g', shape=x.shape[1:], initializer=tf.constant_initializer(1.), ema=ema)\n b = get_var('b', shape=x.shape[1:], initializer=tf.constant_initializer(0.), ema=ema)\n if init:\n # data based normalization\n m_init, v_init = tf.nn.moments(x, [0])\n scale_init = init_scale * tf.rsqrt(v_init + 1e-8)\n assert m_init.shape == v_init.shape == scale_init.shape == g.shape == b.shape\n with tf.control_dependencies([\n g.assign(scale_init),\n b.assign(-m_init * scale_init)\n ]):\n g, b = tf.identity_n([g, b])\n return g, b\n\ndef dense(x, *, name, num_units, init_scale=1., init, ema):\n # use weight normalization (Salimans & Kingma, 2016)\n with tf.variable_scope(name):\n assert x.shape.ndims == 2\n _V = get_var('V', shape=[int(x.shape[1]), num_units], initializer=tf.random_normal_initializer(0, 0.05),\n ema=ema)\n _g = get_var('g', shape=[num_units], initializer=tf.constant_initializer(1.), ema=ema)\n _b = get_var('b', shape=[num_units], initializer=tf.constant_initializer(0.), ema=ema)\n _vinvnorm = tf.rsqrt(tf.reduce_sum(tf.square(_V), [0]))\n V, g, b, vinvnorm = map(to_default_floatx, [_V, _g, _b, _vinvnorm])\n\n x0 = x = tf.matmul(x, V)\n x = (g * vinvnorm)[None, :] * x + b[None, :]\n\n if init: # normalize x\n m_init, v_init = tf.nn.moments(x, [0])\n scale_init = init_scale / tf.sqrt(v_init + 1e-8)\n with tf.control_dependencies([\n _g.assign(tf.cast(g * scale_init, dtype=_g.dtype)),\n _b.assign_add(tf.cast(-m_init * scale_init, dtype=_b.dtype))\n ]):\n g, b = map(to_default_floatx, [_g, _b])\n x = (g * vinvnorm)[None, :] * x0 + b[None, :]\n\n return x\n\ndef conv2d(x, *, name, num_units, filter_size=(3, 3), stride=(1, 1), pad='SAME', init_scale=1., init, ema):\n # use weight normalization (Salimans & Kingma, 2016)\n with tf.variable_scope(name):\n assert x.shape.ndims == 4\n _V = get_var('V', shape=[*filter_size, int(x.shape[-1]), num_units],\n initializer=tf.random_normal_initializer(0, 0.05), ema=ema)\n _g = get_var('g', shape=[num_units], initializer=tf.constant_initializer(1.), ema=ema)\n _b = get_var('b', shape=[num_units], initializer=tf.constant_initializer(0.), ema=ema)\n _vnorm = tf.nn.l2_normalize(_V, [0, 1, 2])\n V, g, b, vnorm = map(to_default_floatx, [_V, _g, _b, _vnorm])\n\n W = g[None, None, None, :] * vnorm\n\n # calculate convolutional layer output\n input_x = x\n x = tf.nn.bias_add(tf.nn.conv2d(x, W, [1, *stride, 1], pad), b)\n\n if init: # normalize x\n m_init, v_init = tf.nn.moments(x, [0, 1, 2])\n scale_init = init_scale * tf.rsqrt(v_init + 1e-8)\n with tf.control_dependencies([\n _g.assign(tf.cast(g * scale_init, dtype=_g.dtype)),\n _b.assign_add(tf.cast(-m_init * scale_init, dtype=_b.dtype))\n ]):\n g, b = map(to_default_floatx, [_g, _b])\n W = g[None, None, None, :] * vnorm\n x = tf.nn.bias_add(tf.nn.conv2d(input_x, W, [1, *stride, 1], pad), b)\n\n return x\n\ndef nin(x, *, num_units, **kwargs):\n assert 'num_units' not in kwargs\n s = x.shape.as_list()\n x = tf.reshape(x, [np.prod(s[:-1]), s[-1]])\n x = dense(x, num_units=num_units, **kwargs)\n return tf.reshape(x, s[:-1] + [num_units])\n\ndef matmul_last_axis(x, w):\n _, out_dim = w.shape\n s = x.shape.as_list()\n x = tf.reshape(x, [np.prod(s[:-1]), s[-1]])\n x = tf.matmul(x, w)\n return tf.reshape(x, s[:-1] + [out_dim])\n\ndef concat_elu(x, *, axis=-1):\n return tf.nn.elu(tf.concat([x, -x], axis=axis))\n\ndef gate(x, *, axis):\n a, b = tf.split(x, 2, axis=axis)\n return a * tf.sigmoid(b)\n\ndef gated_resnet(x, *, name, a, nonlinearity=concat_elu, conv=conv2d, use_nin, init, ema, dropout_p):\n with tf.variable_scope(name):\n num_filters = int(x.shape[-1])\n\n c1 = conv(nonlinearity(x), name='c1', num_units=num_filters, init=init, ema=ema)\n if a is not None: # add short-cut connection if auxiliary input 'a' is given\n c1 += nin(nonlinearity(a), name='a_proj', num_units=num_filters, init=init, ema=ema)\n c1 = nonlinearity(c1)\n if dropout_p > 0:\n c1 = tf.nn.dropout(c1, keep_prob=1. - dropout_p)\n\n c2 = (nin if use_nin else conv)(c1, name='c2', num_units=num_filters * 2, init_scale=0.1, init=init, ema=ema)\n return x + gate(c2, axis=3)\n\ndef attn(x, *, name, pos_emb, heads, init, ema, dropout_p):\n with tf.variable_scope(name):\n bs, height, width, ch = x.shape.as_list()\n assert pos_emb.shape == [height, width, ch]\n assert ch % heads == 0\n timesteps = height * width\n dim = ch // heads\n # Position embeddings\n c = x + pos_emb[None, :, :, :]\n # b, h, t, d == batch, num heads, num timesteps, per-head dim (C // heads)\n c = nin(c, name='proj1', num_units=3 * ch, init=init, ema=ema)\n assert c.shape == [bs, height, width, 3 * ch]\n # Split into heads / Q / K / V\n c = tf.reshape(c, [bs, timesteps, 3, heads, dim]) # b, t, 3, h, d\n c = tf.transpose(c, [2, 0, 3, 1, 4]) # 3, b, h, t, d\n q_bhtd, k_bhtd, v_bhtd = tf.unstack(c, axis=0)\n assert q_bhtd.shape == k_bhtd.shape == v_bhtd.shape == [bs, heads, timesteps, dim]\n # Attention\n w_bhtt = tf.matmul(q_bhtd, k_bhtd, transpose_b=True) / np.sqrt(float(dim))\n w_bhtt = tf.cast(tf.nn.softmax(at_least_float32(w_bhtt)), dtype=x.dtype)\n assert w_bhtt.shape == [bs, heads, timesteps, timesteps]\n a_bhtd = tf.matmul(w_bhtt, v_bhtd)\n # Merge heads\n a_bthd = tf.transpose(a_bhtd, [0, 2, 1, 3])\n assert a_bthd.shape == [bs, timesteps, heads, dim]\n a_btc = tf.reshape(a_bthd, [bs, timesteps, ch])\n # Project\n c1 = tf.reshape(a_btc, [bs, height, width, ch])\n if dropout_p > 0:\n c1 = tf.nn.dropout(c1, keep_prob=1. - dropout_p)\n c2 = nin(c1, name='proj2', num_units=ch * 2, init_scale=0.1, init=init, ema=ema)\n return x + gate(c2, axis=3)\n\nclass Flow:\n def forward(self, x, **kwargs):\n raise NotImplementedError\n def backward(self, y, **kwargs):\n raise NotImplementedError\n\nclass Inverse(Flow):\n def __init__(self, base_flow):\n self.base_flow = base_flow\n\n def forward(self, x, **kwargs):\n return self.base_flow.inverse(x, **kwargs)\n \n def inverse(self, y, **kwargs):\n return self.base_flow.forward(y, **kwargs)\n\nclass Compose(Flow):\n def __init__(self, flows):\n self.flows = flows\n\n def _maybe_tqdm(self, iterable, desc, verbose):\n return tqdm(iterable, desc=desc) if verbose else iterable\n\n def forward(self, x, **kwargs):\n bs = int((x[0] if isinstance(x, tuple) else x).shape[0])\n logd_terms = []\n for i, f in enumerate(self._maybe_tqdm(self.flows, desc='forward {}'.format(kwargs),\n verbose=kwargs.get('verbose'))):\n assert isinstance(f, Flow)\n x, l = f.forward(x, **kwargs)\n if l is not None:\n assert l.shape == [bs]\n logd_terms.append(l)\n return x, tf.add_n(logd_terms) if logd_terms else tf.constant(0.)\n\n def inverse(self, y, **kwargs):\n bs = int((y[0] if isinstance(y, tuple) else y).shape[0])\n logd_terms = []\n for i, f in enumerate(\n self._maybe_tqdm(self.flows[::-1], desc='inverse {}'.format(kwargs), verbose=kwargs.get('verbose'))):\n assert isinstance(f, Flow)\n y, l = f.inverse(y, **kwargs)\n if l is not None:\n assert l.shape == [bs]\n logd_terms.append(l)\n return y, tf.add_n(logd_terms) if logd_terms else tf.constant(0.)\n\nclass ImgProc(Flow):\n def forward(self, x, **kwargs):\n x = x * (.9 / 256) + .05 # [0, 256] -> [.05, .95]\n x = -tf.log(1. / x - 1.) # inverse sigmoid\n logd = np.log(.9 / 256) + tf.nn.softplus(x) + tf.nn.softplus(-x)\n logd = tf.reduce_sum(tf.reshape(logd, [int_shape(logd)[0], -1]), 1)\n return x, logd\n\n def inverse(self, y, **kwargs):\n y = tf.sigmoid(y)\n logd = tf.log(y) + tf.log(1. - y)\n y = (y - .05) / (.9 / 256) # [.05, .95] -> [0, 256]\n logd -= np.log(.9 / 256)\n logd = tf.reduce_sum(tf.reshape(logd, [int_shape(logd)[0], -1]), 1)\n return y, logd\n\nclass TupleFlip(Flow):\n def forward(self, x, **kwargs):\n assert isinstance(x, tuple)\n a, b = x\n return (b, a), None\n\n def inverse(self, y, **kwargs):\n assert isinstance(y, tuple)\n a, b = y\n return (b, a), None\n\nclass SpaceToDepth(Flow):\n def __init__(self, block_size=2):\n self.block_size = block_size\n\n def forward(self, x, **kwargs):\n return tf.space_to_depth(x, self.block_size), None\n\n def inverse(self, y, **kwargs):\n return tf.depth_to_space(y, self.block_size), None\n\nclass CheckerboardSplit(Flow):\n def forward(self, x, **kwargs):\n assert isinstance(x, tf.Tensor)\n B, H, W, C = x.shape\n x = tf.reshape(x, [B, H, W // 2, 2, C])\n a, b = tf.unstack(x, axis=3)\n assert a.shape == b.shape == [B, H, W // 2, C]\n return (a, b), None\n\n def inverse(self, y, **kwargs):\n assert isinstance(y, tuple)\n a, b = y\n assert a.shape == b.shape\n B, H, W_half, C = a.shape\n x = tf.stack([a, b], axis=3)\n assert x.shape == [B, H, W_half, 2, C]\n return tf.reshape(x, [B, H, W_half * 2, C]), None\n\nclass ChannelSplit(Flow):\n def forward(self, x, **kwargs):\n assert isinstance(x, tf.Tensor)\n assert len(x.shape) == 4 and x.shape[3] % 2 == 0\n return tuple(tf.split(x, 2, axis=3)), None\n\n def inverse(self, y, **kwargs):\n assert isinstance(y, tuple)\n a, b = y\n return tf.concat([a, b], axis=3), None\n\nclass Sigmoid(Flow):\n def forward(self, x, **kwargs):\n y = tf.sigmoid(x)\n logd = -tf.nn.softplus(x) - tf.nn.softplus(-x)\n return y, sumflat(logd)\n def inverse(self, y, **kwargs):\n x = inverse_sigmoid(y)\n logd = -tf.log(y) - tf.log(1. - y)\n return x, sumflat(logd)\n\nclass Norm(Flow):\n def __init__(self, init_scale=1.):\n def f(input_, forward, init, ema):\n assert not isinstance(input_, list)\n if isinstance(input_, tuple):\n is_tuple = True\n else:\n assert isinstance(input_, tf.Tensor)\n input_ = [input_]\n is_tuple = False\n\n bs = int(input_[0].shape[0])\n g_and_b = []\n for (i, x) in enumerate(input_):\n g, b = init_normalization(x, name='norm{}'.format(i), init_scale=init_scale, init=init, ema=ema)\n g = tf.maximum(g, 1e-10)\n assert x.shape[0] == bs and g.shape == b.shape == x.shape[1:]\n g_and_b.append((g, b))\n\n logd = tf.fill([bs], tf.add_n([tf.reduce_sum(tf.log(g)) for (g, _) in g_and_b]))\n if forward:\n out = [x * g[None] + b[None] for (x, (g, b)) in zip(input_, g_and_b)]\n else:\n out = [(x - b[None]) / g[None] for (x, (g, b)) in zip(input_, g_and_b)]\n logd = -logd\n\n if not is_tuple:\n assert len(out) == 1\n return out[0], logd\n return tuple(out), logd\n\n self.template = tf.make_template(self.__class__.__name__, f)\n\n def forward(self, x, init=False, ema=None, **kwargs):\n return self.template(x, forward=True, init=init, ema=ema)\n\n def inverse(self, y, init=False, ema=None, **kwargs):\n return self.template(y, forward=False, init=init, ema=ema) \n\nclass MixLogisticCoupling(Flow):\n \"\"\"\n CDF of mixture of logistics, followed by affine\n \"\"\"\n\n def __init__(self, filters, blocks, use_nin, components, attn_heads, use_ln,\n with_affine=True, use_final_nin=False, init_scale=0.1, nonlinearity=concat_elu):\n self.components = components\n self.with_affine = with_affine\n self.scale_flow = Inverse(Sigmoid())\n\n def f(x, init, ema, dropout_p, verbose, context):\n # if verbose and context is not None:\n # print('got context')\n if init and verbose:\n # debug stuff\n with tf.variable_scope('debug'):\n xmean, xvar = tf.nn.moments(x, axes=list(range(len(x.get_shape()))))\n x = tf.Print(\n x,\n [\n tf.shape(x), xmean, tf.sqrt(xvar), tf.reduce_min(x), tf.reduce_max(x),\n tf.reduce_any(tf.is_nan(x)), tf.reduce_any(tf.is_inf(x))\n ],\n message='{} (shape/mean/std/min/max/nan/inf) '.format(self.template.variable_scope.name),\n summarize=10,\n )\n B, H, W, C = x.shape.as_list()\n\n pos_emb = to_default_floatx(get_var(\n 'pos_emb', ema=ema, shape=[H, W, filters], initializer=tf.random_normal_initializer(stddev=0.01),\n ))\n x = conv2d(x, name='c1', num_units=filters, init=init, ema=ema)\n for i_block in range(blocks):\n with tf.variable_scope('block{}'.format(i_block)):\n x = gated_resnet(\n x, name='conv', a=context, use_nin=use_nin, init=init, ema=ema, dropout_p=dropout_p\n )\n if use_ln:\n x = norm(x, name='ln1', ema=ema)\n x = nonlinearity(x)\n x = (nin if use_final_nin else conv2d)(\n x, name='c2', num_units=C * (2 + 3 * components), init_scale=init_scale, init=init, ema=ema\n )\n assert x.shape == [B, H, W, C * (2 + 3 * components)]\n x = tf.reshape(x, [B, H, W, C, 2 + 3 * components])\n\n x = at_least_float32(x) # do mix-logistics in tf.float32\n\n s, t = tf.tanh(x[:, :, :, :, 0]), x[:, :, :, :, 1]\n ml_logits, ml_means, ml_logscales = tf.split(x[:, :, :, :, 2:], 3, axis=4)\n ml_logscales = tf.maximum(ml_logscales, -7.)\n\n assert s.shape == t.shape == [B, H, W, C]\n assert ml_logits.shape == ml_means.shape == ml_logscales.shape == [B, H, W, C, components]\n return s, t, ml_logits, ml_means, ml_logscales\n\n self.template = tf.make_template(self.__class__.__name__, f)\n\n def forward(self, x, init=False, ema=None, dropout_p=0., verbose=True, context=None, **kwargs):\n assert isinstance(x, tuple)\n cf, ef = x\n float_ef = at_least_float32(ef)\n s, t, ml_logits, ml_means, ml_logscales = self.template(\n cf, init=init, ema=ema, dropout_p=dropout_p, verbose=verbose, context=context\n )\n\n out = tf.exp(\n mixlogistic_logcdf(x=float_ef, prior_logits=ml_logits, means=ml_means, logscales=ml_logscales)\n )\n out, scale_logd = self.scale_flow.forward(out)\n if self.with_affine:\n assert out.shape == s.shape == t.shape\n out = tf.exp(s) * out + t\n\n logd = mixlogistic_logpdf(x=float_ef, prior_logits=ml_logits, means=ml_means, logscales=ml_logscales)\n if self.with_affine:\n assert s.shape == logd.shape\n logd += s\n logd = tf.reduce_sum(tf.layers.flatten(logd), axis=1)\n assert scale_logd.shape == logd.shape\n logd += scale_logd\n\n out, logd = map(to_default_floatx, [out, logd])\n assert out.shape == ef.shape == cf.shape and out.dtype == ef.dtype == logd.dtype == cf.dtype\n return (cf, out), logd\n\n def inverse(self, y, init=False, ema=None, dropout_p=0., verbose=True, context=None, **kwargs):\n assert isinstance(y, tuple)\n cf, ef = y\n float_ef = at_least_float32(ef)\n s, t, ml_logits, ml_means, ml_logscales = self.template(\n cf, init=init, ema=ema, dropout_p=dropout_p, verbose=verbose, context=context\n )\n\n out = float_ef\n if self.with_affine:\n out = tf.exp(-s) * (out - t)\n out, invscale_logd = self.scale_flow.inverse(out)\n out = tf.clip_by_value(out, 1e-5, 1. - 1e-5)\n out = mixlogistic_invcdf(y=out, prior_logits=ml_logits, means=ml_means, logscales=ml_logscales)\n\n logd = mixlogistic_logpdf(x=out, prior_logits=ml_logits, means=ml_means, logscales=ml_logscales)\n if self.with_affine:\n assert s.shape == logd.shape\n logd += s\n logd = -tf.reduce_sum(tf.layers.flatten(logd), axis=1)\n assert invscale_logd.shape == logd.shape\n logd += invscale_logd\n\n out, logd = map(to_default_floatx, [out, logd])\n assert out.shape == ef.shape == cf.shape and out.dtype == ef.dtype == logd.dtype == cf.dtype\n return (cf, out), logd\n\nclass MixLogisticAttnCoupling(Flow):\n \"\"\"\n CDF of mixture of logistics, followed by affine\n \"\"\"\n\n def __init__(self, filters, blocks, use_nin, components, attn_heads, use_ln,\n with_affine=True, use_final_nin=False, init_scale=0.1, nonlinearity=concat_elu):\n self.components = components\n self.with_affine = with_affine\n self.scale_flow = Inverse(Sigmoid())\n\n def f(x, init, ema, dropout_p, verbose, context):\n if init and verbose:\n with tf.variable_scope('debug'):\n xmean, xvar = tf.nn.moments(x, axes=list(range(len(x.get_shape()))))\n x = tf.Print(\n x,\n [\n tf.shape(x), xmean, tf.sqrt(xvar), tf.reduce_min(x), tf.reduce_max(x),\n tf.reduce_any(tf.is_nan(x)), tf.reduce_any(tf.is_inf(x))\n ],\n message='{} (shape/mean/std/min/max/nan/inf) '.format(self.template.variable_scope.name),\n summarize=10,\n )\n B, H, W, C = x.shape.as_list()\n\n pos_emb = to_default_floatx(get_var(\n 'pos_emb', ema=ema, shape=[H, W, filters], initializer=tf.random_normal_initializer(stddev=0.01),\n ))\n x = conv2d(x, name='c1', num_units=filters, init=init, ema=ema)\n for i_block in range(blocks):\n with tf.variable_scope('block{}'.format(i_block)):\n x = gated_resnet(\n x, name='conv', a=context, use_nin=use_nin, init=init, ema=ema, dropout_p=dropout_p\n )\n if use_ln:\n x = norm(x, name='ln1', ema=ema)\n x = attn(\n x, name='attn', pos_emb=pos_emb, heads=attn_heads, init=init, ema=ema, dropout_p=dropout_p\n )\n if use_ln:\n x = norm(x, name='ln2', ema=ema)\n assert x.shape == [B, H, W, filters]\n x = nonlinearity(x)\n x = (nin if use_final_nin else conv2d)(\n x, name='c2', num_units=C * (2 + 3 * components), init_scale=init_scale, init=init, ema=ema\n )\n assert x.shape == [B, H, W, C * (2 + 3 * components)]\n x = tf.reshape(x, [B, H, W, C, 2 + 3 * components])\n\n x = at_least_float32(x) # do mix-logistics stuff in float32\n\n s, t = tf.tanh(x[:, :, :, :, 0]), x[:, :, :, :, 1]\n ml_logits, ml_means, ml_logscales = tf.split(x[:, :, :, :, 2:], 3, axis=4)\n ml_logscales = tf.maximum(ml_logscales, -7.)\n\n assert s.shape == t.shape == [B, H, W, C]\n assert ml_logits.shape == ml_means.shape == ml_logscales.shape == [B, H, W, C, components]\n return s, t, ml_logits, ml_means, ml_logscales\n\n self.template = tf.make_template(self.__class__.__name__, f)\n\n def forward(self, x, init=False, ema=None, dropout_p=0., verbose=True, context=None, **kwargs):\n assert isinstance(x, tuple)\n cf, ef = x\n float_ef = at_least_float32(ef)\n s, t, ml_logits, ml_means, ml_logscales = self.template(\n cf, init=init, ema=ema, dropout_p=dropout_p, verbose=verbose, context=context\n )\n\n out = tf.exp(\n mixlogistic_logcdf(x=float_ef, prior_logits=ml_logits, means=ml_means, logscales=ml_logscales)\n )\n out, scale_logd = self.scale_flow.forward(out)\n if self.with_affine:\n assert out.shape == s.shape == t.shape\n out = tf.exp(s) * out + t\n\n logd = mixlogistic_logpdf(x=float_ef, prior_logits=ml_logits, means=ml_means, logscales=ml_logscales)\n if self.with_affine:\n assert s.shape == logd.shape\n logd += s\n logd = tf.reduce_sum(tf.layers.flatten(logd), axis=1)\n assert scale_logd.shape == logd.shape\n logd += scale_logd\n\n out, logd = map(to_default_floatx, [out, logd])\n assert out.shape == ef.shape == cf.shape and out.dtype == ef.dtype == logd.dtype == cf.dtype\n return (cf, out), logd\n\n def inverse(self, y, init=False, ema=None, dropout_p=0., verbose=True, context=None, **kwargs):\n assert isinstance(y, tuple)\n cf, ef = y\n float_ef = at_least_float32(ef)\n s, t, ml_logits, ml_means, ml_logscales = self.template(\n cf, init=init, ema=ema, dropout_p=dropout_p, verbose=verbose, context=context\n )\n\n out = float_ef\n if self.with_affine:\n out = tf.exp(-s) * (out - t)\n out, invscale_logd = self.scale_flow.inverse(out)\n out = tf.clip_by_value(out, 1e-5, 1. - 1e-5)\n out = mixlogistic_invcdf(y=out, prior_logits=ml_logits, means=ml_means, logscales=ml_logscales)\n\n logd = mixlogistic_logpdf(x=out, prior_logits=ml_logits, means=ml_means, logscales=ml_logscales)\n if self.with_affine:\n assert s.shape == logd.shape\n logd += s\n logd = -tf.reduce_sum(tf.layers.flatten(logd), axis=1)\n assert invscale_logd.shape == logd.shape\n logd += invscale_logd\n\n out, logd = map(to_default_floatx, [out, logd])\n assert out.shape == ef.shape == cf.shape and out.dtype == ef.dtype == logd.dtype == cf.dtype\n return (cf, out), logd\n\ndef gaussian_sample_logp(shape, dtype):\n eps = tf.random_normal(shape)\n logp = Normal(0., 1.).log_prob(eps)\n assert logp.shape == eps.shape\n logp = tf.reduce_sum(tf.layers.flatten(logp), axis=1)\n return tf.cast(eps, dtype=dtype), tf.cast(logp, dtype=dtype)\n\nclass Dequantizer(Flow):\n def __init__(self, dequant_flow):\n super().__init__()\n assert isinstance(dequant_flow, Flow)\n self.dequant_flow = dequant_flow\n\n\n def deep_processor(x, *, init, ema, dropout_p):\n (this, that), _ = CheckerboardSplit().forward(x)\n processed_context = conv2d(tf.concat([this, that], 3), name='proj', num_units=32, init=init, ema=ema)\n B, H, W, C = processed_context.shape.as_list()\n\n pos_emb = to_default_floatx(get_var(\n 'pos_emb_dq', ema=ema, shape=[H, W, C], initializer=tf.random_normal_initializer(stddev=0.01),\n ))\n\n for i in range(8):\n processed_context = gated_resnet(\n processed_context, name=f'c{i}',\n a=None, dropout_p=dropout_p, ema=ema, init=init,\n use_nin=False\n )\n processed_context = norm(processed_context, name=f'dqln{i}', ema=ema)\n processed_context = attn(processed_context, name=f'dqattn{i}', pos_emb=pos_emb, heads=4, init=init, ema=ema, dropout_p=dropout_p)\n processed_context = norm(processed_context, name=f'ln{i}', ema=ema)\n\n return processed_context\n\n self.context_proc = tf.make_template(\"context_proc\", deep_processor)\n\n def forward(self, x, init=False, ema=None, dropout_p=0., verbose=True, **kwargs):\n eps, eps_logli = gaussian_sample_logp(x.shape, dtype=DEFAULT_FLOATX)\n unbound_xd, logd = self.dequant_flow.forward(\n eps,\n context=self.context_proc(x / 256.0 - 0.5, init=init, ema=ema, dropout_p=dropout_p),\n init=init, ema=ema, dropout_p=dropout_p, verbose=verbose\n )\n xd, sigmoid_logd = Sigmoid().forward(unbound_xd)\n assert x.shape == xd.shape and logd.shape == sigmoid_logd.shape == eps_logli.shape\n return x + xd, logd + sigmoid_logd - eps_logli\n\ndef construct(*, filters, blocks, components, attn_heads, use_nin, use_ln):\n dequant_coupling_kwargs = dict(\n filters=filters, blocks=8, use_nin=use_nin, components=components, attn_heads=attn_heads, use_ln=use_ln\n )\n dequant_flow = Dequantizer(Compose([\n CheckerboardSplit(),\n Norm(), MixLogisticAttnCoupling(**dequant_coupling_kwargs), TupleFlip(),\n Norm(), MixLogisticAttnCoupling(**dequant_coupling_kwargs), TupleFlip(),\n Norm(), MixLogisticAttnCoupling(**dequant_coupling_kwargs), TupleFlip(),\n Norm(), MixLogisticAttnCoupling(**dequant_coupling_kwargs), TupleFlip(),\n Inverse(CheckerboardSplit()),\n\n CheckerboardSplit(),\n Norm(), MixLogisticAttnCoupling(**dequant_coupling_kwargs), TupleFlip(),\n Norm(), MixLogisticAttnCoupling(**dequant_coupling_kwargs), TupleFlip(),\n Norm(), MixLogisticAttnCoupling(**dequant_coupling_kwargs), TupleFlip(),\n Norm(), MixLogisticAttnCoupling(**dequant_coupling_kwargs), TupleFlip(),\n Inverse(CheckerboardSplit()),\n ]))\n\n coupling_kwargs = dict(\n filters=filters, blocks=blocks, use_nin=use_nin, components=components, attn_heads=attn_heads, use_ln=use_ln\n )\n flow = Compose([\n ImgProc(),\n\n CheckerboardSplit(),\n Norm(), MixLogisticAttnCoupling(**coupling_kwargs), TupleFlip(),\n Norm(), MixLogisticAttnCoupling(**coupling_kwargs), TupleFlip(),\n Norm(), MixLogisticAttnCoupling(**coupling_kwargs), TupleFlip(),\n Norm(), MixLogisticAttnCoupling(**coupling_kwargs), TupleFlip(),\n Inverse(CheckerboardSplit()),\n\n CheckerboardSplit(),\n Norm(), MixLogisticAttnCoupling(**coupling_kwargs), TupleFlip(),\n Norm(), MixLogisticAttnCoupling(**coupling_kwargs), TupleFlip(),\n Norm(), MixLogisticAttnCoupling(**coupling_kwargs), TupleFlip(),\n Inverse(CheckerboardSplit()),\n\n SpaceToDepth(),\n\n ChannelSplit(),\n Norm(), MixLogisticAttnCoupling(**coupling_kwargs), TupleFlip(),\n Norm(), MixLogisticAttnCoupling(**coupling_kwargs), TupleFlip(),\n Norm(), MixLogisticAttnCoupling(**coupling_kwargs), TupleFlip(),\n Inverse(ChannelSplit()),\n\n CheckerboardSplit(),\n Norm(), MixLogisticAttnCoupling(**coupling_kwargs), TupleFlip(),\n Norm(), MixLogisticAttnCoupling(**coupling_kwargs), TupleFlip(),\n Norm(), MixLogisticAttnCoupling(**coupling_kwargs), TupleFlip(),\n Inverse(CheckerboardSplit()),\n ])\n return dequant_flow, flow\n\ndef main():\n global DEFAULT_FLOATX\n DEFAULT_FLOATX = tf.float32\n\n max_lr = 1e-3\n min_lr = 3e-4\n warmup_steps = 5000\n bs = 32\n\n def lr_schedule(step, *, decay=0.99995, min_lr=3e-4):\n global curr_lr\n if step < warmup_steps:\n curr_lr = max_lr * step / warmup_steps\n return max_lr * step / warmup_steps\n elif step > (warmup_steps * 10) and curr_lr > min_lr:\n curr_lr *= decay\n return curr_lr\n return curr_lr\n\n dropout_p = 0.\n filters = 128\n blocks = 20\n components = 32 # logistic mixture components\n attn_heads = 4\n use_ln = True\n\n floatx_str = {tf.float32: 'fp32', tf.float16: 'fp16'}[DEFAULT_FLOATX]\n flow_training_imagenet.train(\n flow_constructor=lambda: construct(\n filters=filters,\n components=components,\n attn_heads=attn_heads,\n blocks=blocks,\n use_nin=True,\n use_ln=use_ln\n ),\n logdir=f'~/logs/2018-10-26/imagenet32_ELU_WN_code_release_mix{components}_b{blocks}_f{filters}_h{attn_heads}_ln{int(use_ln)}_lr{max_lr}_bs{bs}_drop{dropout_p}_{floatx_str}',\n lr_schedule=lr_schedule,\n dropout_p=dropout_p,\n seed=0,\n init_bs=32,\n dataset='imagenet32',\n total_bs=bs,\n ema_decay=.999222,\n steps_per_log=100,\n steps_per_val=50000,\n steps_per_dump=5000,\n steps_per_samples=5000,\n max_grad_norm=1.,\n dtype=DEFAULT_FLOATX,\n scale_loss=1e-2 if DEFAULT_FLOATX == tf.float16 else None,\n n_epochs=2,\n restore_checkpoint=None, # put in path to checkpoint in the format: path_to_checkpoint/model (no .meta / .ckpt)\n dump_samples_to_tensorboard=False, # if you want to push the tiled simples to tensorboard. \n )\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.asarray", "numpy.max", "numpy.save", "numpy.min" ], [ "tensorflow.is_nan", "tensorflow.get_variable", "tensorflow.concat", "tensorflow.stack", "tensorflow.cast", "tensorflow.tanh", "tensorflow.make_template", "tensorflow.add_n", "tensorflow.nn.conv2d", "tensorflow.nn.moments", "tensorflow.identity_n", "tensorflow.square", "tensorflow.random_normal_initializer", "tensorflow.sqrt", "tensorflow.nn.dropout", "tensorflow.nn.l2_normalize", "tensorflow.reciprocal", "tensorflow.matmul", "numpy.log", "tensorflow.depth_to_space", "tensorflow.unstack", "tensorflow.shape", "tensorflow.exp", "tensorflow.is_inf", "tensorflow.split", "tensorflow.clip_by_value", "tensorflow.layers.flatten", "tensorflow.reduce_max", "tensorflow.transpose", "tensorflow.distributions.Normal", "tensorflow.constant", "tensorflow.reduce_mean", "tensorflow.space_to_depth", "tensorflow.maximum", "tensorflow.reshape", "tensorflow.sigmoid", "tensorflow.constant_initializer", "tensorflow.reduce_min", "tensorflow.log", "numpy.prod", "tensorflow.variable_scope", "tensorflow.rsqrt", "tensorflow.squared_difference", "tensorflow.nn.softplus", "tensorflow.random_normal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
komori556/PINTO_model_zoo
[ "0703bf1837d0d0e39f1d0dc9d523b6d8fa8145bd", "0703bf1837d0d0e39f1d0dc9d523b6d8fa8145bd", "0703bf1837d0d0e39f1d0dc9d523b6d8fa8145bd" ]
[ "049_iris_landmark/01_float32/09_tensorrt_inf_test.py", "053_BlazePose/01_float32/07_tensorrt_inf_test.py", "041_DBFace/01_float32/03_freeze_graph_to_saved_model.py" ]
[ "### tensorflow==2.3.0\n\n### https://developer.nvidia.com/compute/machine-learning/tensorrt/secure/6.0/GA_6.0.1.5/local_repos/nv-tensorrt-repo-ubuntu1804-cuda10.1-trt6.0.1.5-ga-20190913_1-1_amd64.deb\n\n# os=\"ubuntu1804\"\n# tag=\"cuda10.1-trt6.0.1.5-ga-20190913\"\n# sudo dpkg -i nv-tensorrt-repo-${os}-${tag}_1-1_amd64.deb\n# sudo apt-key add /var/nv-tensorrt-repo-${tag}/7fa2af80.pub\n\n# sudo apt-get update\n# sudo apt-get install tensorrt\n\n# sudo apt-get install python3-libnvinfer-dev\n# python3-libnvinfer\n# sudo apt-get install uff-converter-tf\n# sudo apt-get install onnx-graphsurgeon\n\nimport tensorflow as tf\nimport numpy as np\nimport time\n\nheight = 64\nwidth = 64\n\n\ndef input_fn():\n input_shapes = [1, height, width, 3]\n yield [np.zeros(input_shapes).astype(np.float32)]\n\n\n\nparams = tf.experimental.tensorrt.ConversionParams(precision_mode='FP32', maximum_cached_engines=1000)\nconverter = tf.experimental.tensorrt.Converter(input_saved_model_dir='saved_model', conversion_params=params)\nconverter.convert()\nconverter.build(input_fn=input_fn)\nconverter.save('tensorrt_saved_model_float32')\n\nparams = tf.experimental.tensorrt.ConversionParams(precision_mode='FP16', maximum_cached_engines=1000)\nconverter = tf.experimental.tensorrt.Converter(input_saved_model_dir='saved_model', conversion_params=params)\nconverter.convert()\nconverter.build(input_fn=input_fn)\nconverter.save('tensorrt_saved_model_float16')\n\n\n\nmodel = tf.saved_model.load('tensorrt_saved_model_float16', tags=[tf.saved_model.SERVING])\ninfer = model.signatures[tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY]\ninfer.inputs[0].shape\nx = np.random.uniform(size=(1, height, width, 3)).astype(np.float32)\n\nstart = time.perf_counter()\ninfer(tf.convert_to_tensor(x))\nend = time.perf_counter()\nprint('@@@@@@@@@@@@@@ First Inference')\nprint('elapsed time:', end - start)\n\nstart = time.perf_counter()\ninfer(tf.convert_to_tensor(x))\nend = time.perf_counter()\nprint('@@@@@@@@@@@@@@ Second Inference')\nprint('elapsed time:', end - start)\n", "### tensorflow==2.3.0\n\n### https://developer.nvidia.com/compute/machine-learning/tensorrt/secure/6.0/GA_6.0.1.5/local_repos/nv-tensorrt-repo-ubuntu1804-cuda10.1-trt6.0.1.5-ga-20190913_1-1_amd64.deb\n\n# os=\"ubuntu1804\"\n# tag=\"cuda10.1-trt6.0.1.5-ga-20190913\"\n# sudo dpkg -i nv-tensorrt-repo-${os}-${tag}_1-1_amd64.deb\n# sudo apt-key add /var/nv-tensorrt-repo-${tag}/7fa2af80.pub\n\n# sudo apt-get update\n# sudo apt-get install tensorrt\n\n# sudo apt-get install python3-libnvinfer-dev\n# python3-libnvinfer\n# sudo apt-get install uff-converter-tf\n# sudo apt-get install onnx-graphsurgeon\n\nimport tensorflow as tf\nimport numpy as np\nimport time\n\nheight_det = 128\nwidth_det = 128\n\nheight_land = 256\nwidth_land = 256\n\n\ndef input_fn_detection():\n input_shapes = [1, height_det, width_det, 3]\n yield [np.zeros(input_shapes).astype(np.float32)]\n\ndef input_fn_landmark():\n input_shapes = [1, height_land, width_land, 3]\n yield [np.zeros(input_shapes).astype(np.float32)]\n\n\nparams = tf.experimental.tensorrt.ConversionParams(precision_mode='FP32', maximum_cached_engines=1000)\nconverter = tf.experimental.tensorrt.Converter(input_saved_model_dir='saved_model_pose_detection', conversion_params=params)\nconverter.convert()\nconverter.build(input_fn=input_fn_detection)\nconverter.save('tensorrt_saved_model_pose_detection_float32')\n\n\nparams = tf.experimental.tensorrt.ConversionParams(precision_mode='FP16', maximum_cached_engines=1000)\nconverter = tf.experimental.tensorrt.Converter(input_saved_model_dir='saved_model_pose_detection', conversion_params=params)\nconverter.convert()\nconverter.build(input_fn=input_fn_detection)\nconverter.save('tensorrt_saved_model_pose_detection_float16')\n\n\nparams = tf.experimental.tensorrt.ConversionParams(precision_mode='FP32', maximum_cached_engines=1000)\nconverter = tf.experimental.tensorrt.Converter(input_saved_model_dir='saved_model_pose_landmark_upper_body', conversion_params=params)\nconverter.convert()\nconverter.build(input_fn=input_fn_landmark)\nconverter.save('tensorrt_saved_model_pose_landmark_upper_body_float32')\n\n\nparams = tf.experimental.tensorrt.ConversionParams(precision_mode='FP16', maximum_cached_engines=1000)\nconverter = tf.experimental.tensorrt.Converter(input_saved_model_dir='saved_model_pose_landmark_upper_body', conversion_params=params)\nconverter.convert()\nconverter.build(input_fn=input_fn_landmark)\nconverter.save('tensorrt_saved_model_pose_landmark_upper_body_float16')\n\n\n\n\nmodel = tf.saved_model.load('tensorrt_saved_model_pose_detection_float32', tags=[tf.saved_model.SERVING])\ninfer = model.signatures[tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY]\ninfer.inputs[0].shape\nx = np.random.uniform(size=(1,height_det,width_det,3)).astype(np.float32)\n\nstart = time.perf_counter()\ninfer(tf.convert_to_tensor(x))\nend = time.perf_counter()\nprint('@@@@@@@@@@@@@@ First Inference')\nprint('elapsed time:', end - start)\n\nstart = time.perf_counter()\ninfer(tf.convert_to_tensor(x))\nend = time.perf_counter()\nprint('@@@@@@@@@@@@@@ Second Inference')\nprint('elapsed time:', end - start)\n\n\nmodel = tf.saved_model.load('tensorrt_saved_model_pose_detection_float16', tags=[tf.saved_model.SERVING])\ninfer = model.signatures[tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY]\ninfer.inputs[0].shape\nx = np.random.uniform(size=(1,height_det,width_det,3)).astype(np.float32)\n\nstart = time.perf_counter()\ninfer(tf.convert_to_tensor(x))\nend = time.perf_counter()\nprint('@@@@@@@@@@@@@@ First Inference')\nprint('elapsed time:', end - start)\n\nstart = time.perf_counter()\ninfer(tf.convert_to_tensor(x))\nend = time.perf_counter()\nprint('@@@@@@@@@@@@@@ Second Inference')\nprint('elapsed time:', end - start)\n\n\n\n\nmodel = tf.saved_model.load('tensorrt_saved_model_pose_landmark_upper_body_float32', tags=[tf.saved_model.SERVING])\ninfer = model.signatures[tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY]\ninfer.inputs[0].shape\nx = np.random.uniform(size=(1,height_land,width_land,3)).astype(np.float32)\n\nstart = time.perf_counter()\ninfer(tf.convert_to_tensor(x))\nend = time.perf_counter()\nprint('@@@@@@@@@@@@@@ First Inference')\nprint('elapsed time:', end - start)\n\nstart = time.perf_counter()\ninfer(tf.convert_to_tensor(x))\nend = time.perf_counter()\nprint('@@@@@@@@@@@@@@ Second Inference')\nprint('elapsed time:', end - start)\n\n\nmodel = tf.saved_model.load('tensorrt_saved_model_pose_landmark_upper_body_float16', tags=[tf.saved_model.SERVING])\ninfer = model.signatures[tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY]\ninfer.inputs[0].shape\nx = np.random.uniform(size=(1,height_land,width_land,3)).astype(np.float32)\n\nstart = time.perf_counter()\ninfer(tf.convert_to_tensor(x))\nend = time.perf_counter()\nprint('@@@@@@@@@@@@@@ First Inference')\nprint('elapsed time:', end - start)\n\nstart = time.perf_counter()\ninfer(tf.convert_to_tensor(x))\nend = time.perf_counter()\nprint('@@@@@@@@@@@@@@ Second Inference')\nprint('elapsed time:', end - start)\n", "### tensorflow==2.2.0\n\nimport tensorflow as tf\nfrom tensorflow.python import ops\nimport shutil\n\ndef get_graph_def_from_file(graph_filepath):\n tf.compat.v1.reset_default_graph()\n with ops.Graph().as_default():\n with tf.compat.v1.gfile.GFile(graph_filepath, 'rb') as f:\n graph_def = tf.compat.v1.GraphDef()\n graph_def.ParseFromString(f.read())\n return graph_def\n\ndef convert_graph_def_to_saved_model(export_dir, graph_filepath, input_name, outputs):\n graph_def = get_graph_def_from_file(graph_filepath)\n with tf.compat.v1.Session(graph=tf.Graph()) as session:\n tf.import_graph_def(graph_def, name='')\n tf.compat.v1.saved_model.simple_save(\n session,\n export_dir,# change input_image to node.name if you know the name\n inputs={input_name: session.graph.get_tensor_by_name('{}:0'.format(node.name))\n for node in graph_def.node if node.op=='Placeholder'},\n outputs={t.rstrip(\":0\"):session.graph.get_tensor_by_name(t) for t in outputs}\n )\n print('Optimized graph converted to SavedModel!')\n\nshutil.rmtree('saved_model_tf', ignore_errors=True)\nconvert_graph_def_to_saved_model('saved_model_tf', 'dbface_tf.pb', 'x', ['sigmoid_hm:0','tlrb:0','landmark:0'])\n" ]
[ [ "tensorflow.convert_to_tensor", "tensorflow.saved_model.load", "tensorflow.experimental.tensorrt.Converter", "tensorflow.experimental.tensorrt.ConversionParams", "numpy.random.uniform", "numpy.zeros" ], [ "tensorflow.convert_to_tensor", "tensorflow.saved_model.load", "tensorflow.experimental.tensorrt.Converter", "tensorflow.experimental.tensorrt.ConversionParams", "numpy.random.uniform", "numpy.zeros" ], [ "tensorflow.Graph", "tensorflow.import_graph_def", "tensorflow.compat.v1.GraphDef", "tensorflow.compat.v1.gfile.GFile", "tensorflow.python.ops.Graph", "tensorflow.compat.v1.reset_default_graph" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
FedericoV/jax
[ "95ea04ed9076526bd0e12cdf68838ebcf6fb804b" ]
[ "examples/mnist_classifier_fromscratch.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\"\"\"A basic MNIST example using Numpy and JAX.\n\nThe primary aim here is simplicity and minimal dependencies.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\n\nimport numpy.random as npr\n\nfrom jax.api import jit, grad\nfrom jax.config import config\nfrom jax.scipy.special import logsumexp\nimport jax.numpy as np\nfrom examples import datasets\n\n\ndef init_random_params(scale, layer_sizes, rng=npr.RandomState(0)):\n return [(scale * rng.randn(m, n), scale * rng.randn(n))\n for m, n, in zip(layer_sizes[:-1], layer_sizes[1:])]\n\ndef predict(params, inputs):\n activations = inputs\n for w, b in params[:-1]:\n outputs = np.dot(activations, w) + b\n activations = np.tanh(outputs)\n\n final_w, final_b = params[-1]\n logits = np.dot(activations, final_w) + final_b\n return logits - logsumexp(logits, axis=1, keepdims=True)\n\ndef loss(params, batch):\n inputs, targets = batch\n preds = predict(params, inputs)\n return -np.mean(preds * targets)\n\ndef accuracy(params, batch):\n inputs, targets = batch\n target_class = np.argmax(targets, axis=1)\n predicted_class = np.argmax(predict(params, inputs), axis=1)\n return np.mean(predicted_class == target_class)\n\n\nif __name__ == \"__main__\":\n layer_sizes = [784, 1024, 1024, 10] # TODO(mattjj): revise to standard arch\n param_scale = 0.1\n step_size = 0.001\n num_epochs = 10\n batch_size = 128\n\n train_images, train_labels, test_images, test_labels = datasets.mnist()\n num_train = train_images.shape[0]\n num_complete_batches, leftover = divmod(num_train, batch_size)\n num_batches = num_complete_batches + bool(leftover)\n\n def data_stream():\n rng = npr.RandomState(0)\n while True:\n perm = rng.permutation(num_train)\n for i in range(num_batches):\n batch_idx = perm[i * batch_size:(i + 1) * batch_size]\n yield train_images[batch_idx], train_labels[batch_idx]\n batches = data_stream()\n\n @jit\n def update(params, batch):\n grads = grad(loss)(params, batch)\n return [(w - step_size * dw, b - step_size * db)\n for (w, b), (dw, db) in zip(params, grads)]\n\n params = init_random_params(param_scale, layer_sizes)\n for epoch in range(num_epochs):\n start_time = time.time()\n for _ in range(num_batches):\n params = update(params, next(batches))\n epoch_time = time.time() - start_time\n\n train_acc = accuracy(params, (train_images, train_labels))\n test_acc = accuracy(params, (test_images, test_labels))\n print(\"Epoch {} in {:0.2f} sec\".format(epoch, epoch_time))\n print(\"Training set accuracy {}\".format(train_acc))\n print(\"Test set accuracy {}\".format(test_acc))\n" ]
[ [ "numpy.random.RandomState" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yakovdan/encoder4editing
[ "7d1310f82421c5c168f94c404d05ee96087f7bdc" ]
[ "scripts/train.py" ]
[ "\"\"\"\nThis file runs the main training/val loop\n\"\"\"\nimport os\nimport json\nimport math\nimport sys\nimport pprint\nimport torch\nfrom argparse import Namespace\n\nsys.path.append(\".\")\nsys.path.append(\"..\")\n\nfrom options.train_options import TrainOptions\nfrom training.coach import Coach\n\n\ndef main():\n\topts = TrainOptions().parse()\n\tprevious_train_ckpt = None\n\tif opts.resume_training_from_ckpt:\n\t\topts, previous_train_ckpt = load_train_checkpoint(opts)\n\telse:\n\t\tsetup_progressive_steps(opts)\n\t\tcreate_initial_experiment_dir(opts)\n\n\tcoach = Coach(opts, previous_train_ckpt)\n\tcoach.train()\n\n\ndef load_train_checkpoint(opts):\n\ttrain_ckpt_path = opts.resume_training_from_ckpt\n\tprevious_train_ckpt = torch.load(opts.resume_training_from_ckpt, map_location='cpu')\n\tnew_opts_dict = vars(opts)\n\topts = previous_train_ckpt['opts']\n\topts['resume_training_from_ckpt'] = train_ckpt_path\n\tupdate_new_configs(opts, new_opts_dict)\n\tpprint.pprint(opts)\n\topts = Namespace(**opts)\n\tif opts.sub_exp_dir is not None:\n\t\tsub_exp_dir = opts.sub_exp_dir\n\t\topts.exp_dir = os.path.join(opts.exp_dir, sub_exp_dir)\n\t\tcreate_initial_experiment_dir(opts)\n\treturn opts, previous_train_ckpt\n\n\ndef setup_progressive_steps(opts):\n\tlog_size = int(math.log(opts.stylegan_size, 2))\n\tnum_style_layers = 2*log_size - 2\n\tnum_deltas = num_style_layers - 1\n\tif opts.progressive_start is not None: # If progressive delta training\n\t\topts.progressive_steps = [0]\n\t\tnext_progressive_step = opts.progressive_start\n\t\tfor i in range(num_deltas):\n\t\t\topts.progressive_steps.append(next_progressive_step)\n\t\t\tnext_progressive_step += opts.progressive_step_every\n\n\tprint(\"YAKOV: \"+str(opts.progressive_steps))\n\n\tassert opts.progressive_steps is None or is_valid_progressive_steps(opts, num_style_layers), \\\n\t\t\"Invalid progressive training input\"\n\n\ndef is_valid_progressive_steps(opts, num_style_layers):\n\treturn len(opts.progressive_steps) == num_style_layers and opts.progressive_steps[0] == 0\n\n\ndef create_initial_experiment_dir(opts):\n\tif os.path.exists(opts.exp_dir):\n\t\traise Exception('Oops... {} already exists'.format(opts.exp_dir))\n\tos.makedirs(opts.exp_dir)\n\n\topts_dict = vars(opts)\n\tpprint.pprint(opts_dict)\n\twith open(os.path.join(opts.exp_dir, 'opt.json'), 'w') as f:\n\t\tjson.dump(opts_dict, f, indent=4, sort_keys=True)\n\n\ndef update_new_configs(ckpt_opts, new_opts):\n\tfor k, v in new_opts.items():\n\t\t#if k not in ckpt_opts:\n\t\tckpt_opts[k] = v\n\tif new_opts['update_param_list']:\n\t\tfor param in new_opts['update_param_list']:\n\t\t\tckpt_opts[param] = new_opts[param]\n\n\nif __name__ == '__main__':\n\tmain()\n" ]
[ [ "torch.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ktodorov/diagnostics-shapes
[ "aea1c3669afd596a8d3908cd310c1e0bec5f85b1" ]
[ "baseline/train_image_recognition.py" ]
[ "# Baseline setting in which there are only two agents\n# - no evolution\n\nimport pickle\nimport argparse\nimport sys\nimport torch\nimport os\nimport time\n\nfrom torch.utils import data\n\nfrom datasets.message_dataset import MessageDataset\nfrom enums.dataset_type import DatasetType\nfrom enums.image_property import ImageProperty\n\nfrom helpers.train_helper import TrainHelper\nfrom helpers.file_helper import FileHelper\nfrom helpers.metrics_helper import MetricsHelper\n\nfrom models.image_receiver import ImageReceiver\nfrom metrics.average_meter import AverageMeter\n\nimport matplotlib.pyplot as plt\nfrom torchvision.utils import make_grid\nfrom sklearn import metrics\n\nheader = ' Time Epoch Iteration Progress (%Epoch) | F1 Score Loss Accuracy | Best'\nlog_template = ' '.join(\n '{:>6.0f},{:>5.0f},{:>9.0f},{:>5.0f}/{:<5.0f} {:>7.0f}%,| {:>8.6f} {:>8.6f} {:>8.6f} | {:>4s}'.split(','))\n\ndef parse_arguments(args):\n # Training settings\n parser = argparse.ArgumentParser(\n description=\"Training Sender/Receiver Agent on a task\"\n )\n parser.add_argument(\n \"--debugging\",\n help=\"Enable debugging mode (default: False)\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"--single-model\",\n help=\"Use a single model (default: False)\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"--dataset-type\",\n type=str,\n default=\"raw\",\n metavar=\"S\",\n help=\"type of input used by dataset pick from raw/features/meta (default features)\",\n )\n parser.add_argument(\n \"--greedy\",\n help=\"Use argmax at prediction time instead of sampling (default: False)\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"--iterations\",\n type=int,\n default=10000,\n metavar=\"N\",\n help=\"number of batch iterations to train (default: 10k)\",\n )\n parser.add_argument(\n \"--log-interval\",\n type=int,\n default=200,\n metavar=\"N\",\n help=\"number of iterations between logs (default: 200)\",\n )\n parser.add_argument(\n \"--seed\", type=int, default=13, metavar=\"S\", help=\"random seed (default: 13)\"\n )\n \n parser.add_argument(\n \"--messages-seed\",\n type=int,\n required=True,\n metavar=\"S\",\n help=\"The seed which was used for sampling messages\"\n )\n parser.add_argument(\n \"--embedding-size\",\n type=int,\n default=64,\n metavar=\"N\",\n help=\"embedding size for embedding layer (default: 64)\",\n )\n parser.add_argument(\n \"--hidden-size\",\n type=int,\n default=64,\n metavar=\"N\",\n help=\"hidden size for hidden layer (default: 64)\",\n )\n parser.add_argument(\n \"--batch-size\",\n type=int,\n default=1024,\n metavar=\"N\",\n help=\"input batch size for training (default: 1024)\",\n )\n parser.add_argument(\n \"--max-length\",\n type=int,\n default=10,\n metavar=\"N\",\n help=\"max sentence length allowed for communication (default: 10)\",\n )\n parser.add_argument(\n \"--k\",\n type=int,\n default=3,\n metavar=\"N\",\n help=\"Number of distractors (default: 3)\",\n )\n parser.add_argument(\n \"--vocab-size\",\n type=int,\n default=25,\n metavar=\"N\",\n help=\"Size of vocabulary (default: 25)\",\n )\n parser.add_argument(\n \"--num-nodes\",\n type=int,\n default=4,\n metavar=\"N\",\n help=\"Size of darts cell to use with random-darts (default: 4)\",\n )\n parser.add_argument(\n \"--lr\",\n type=float,\n default=1e-3,\n metavar=\"N\",\n help=\"Adam learning rate (default: 1e-3)\",\n )\n parser.add_argument(\n \"--device\",\n type=str,\n help=\"Device to be used. Pick from none/cpu/cuda. If default none is used automatic check will be done\")\n parser.add_argument(\n \"--patience\",\n type=int,\n default=30,\n help=\"Amount of epochs to check for not improved validation score before early stopping\",\n )\n parser.add_argument(\n \"--inference\",\n action=\"store_true\",\n help=\"If sender model trained using inference step is used\"\n )\n parser.add_argument(\n \"--step3\",\n help=\"If sender model trained using step3 is used\",\n action=\"store_true\"\n )\n parser.add_argument(\n \"--multi-task\",\n help=\"Run multi-task approach training using both baseline and diagnostic classifiers approaches\",\n action=\"store_true\"\n )\n parser.add_argument(\n \"--multi-task-lambda\",\n type=float,\n default=0.5,\n help=\"Lambda value to be used to distinguish importance between baseline approach and the diagnostic classifiers approach\",\n )\n parser.add_argument(\n \"--test-mode\",\n help=\"Only run the saved model on the test set\",\n action=\"store_true\"\n )\n parser.add_argument(\n \"--disabled-properties\",\n help=\"Disable properties from training\",\n type=lambda index: ImageProperty(int(index)),\n nargs='*',\n required=False\n )\n\n args = parser.parse_args(args)\n\n return args\n\ndef save_image_grid(images, image_size, rows, iteration, appendix, images_path):\n sample_images = images.view(-1, 3, image_size, image_size)\n \n samples_grid = make_grid(sample_images, nrow=rows, normalize=False, pad_value=.5, padding=1).cpu().numpy().transpose(1,2,0)\n \n filepath = os.path.join(images_path, f'{appendix}_{iteration}.png')\n plt.imsave(filepath, samples_grid)\n\ndef perform_iteration(\n model,\n criterion,\n optimizer,\n messages,\n original_targets,\n iteration,\n device,\n images_path,\n generate_images,\n calculate_f1=False):\n\n messages = messages.long().to(device)\n original_targets = original_targets.float().to(device)\n\n if model.training:\n optimizer.zero_grad()\n\n output = model.forward(messages)\n \n original_targets_vector = original_targets.view(original_targets.shape[0], -1)\n loss = criterion.forward(output, original_targets_vector)\n\n if model.training:\n loss.backward()\n optimizer.step()\n\n if generate_images:\n if iteration == 0:\n save_image_grid(original_targets_vector[0:100].detach().cpu(), 30, 10, iteration, 'original', images_path)\n\n save_image_grid(output[0:100].detach().cpu(), 30, 10, iteration, 'predicted', images_path)\n\n acc = torch.mean(torch.mean(((original_targets_vector > .5) == (output > .5)).float(), dim=1))\n\n # precision = metrics.precision_score(\n # original_targets_vector, output)\n # recall = metrics.recall_score(original_targets_vector, output)\n \n targets_list = original_targets_vector.round().long().tolist()\n output_list = output.round().long().tolist()\n f1_score = 0\n\n if calculate_f1:\n for i in range(len(targets_list)):\n f1_score += metrics.f1_score(targets_list[i], output_list[i])\n \n f1_score = f1_score / len(targets_list)\n return loss.item(), acc.item(), f1_score\n\ndef evaluate(model, criterion, dataloader, iteration, device, images_path):\n loss_meter = AverageMeter()\n acc_meter = AverageMeter()\n f1_meter = AverageMeter()\n\n model.eval()\n\n for i, (messages, original_targets) in enumerate(dataloader):\n loss, acc, f1_score = perform_iteration(model, criterion, None, messages, original_targets, iteration, device, images_path, i==0, True)\n loss_meter.update(loss)\n acc_meter.update(acc)\n f1_meter.update(f1_score)\n\n return loss_meter, acc_meter, f1_meter\n\ndef generate_unique_name(length, vocabulary_size, seed, inference, step3, multi_task, multi_task_lambda, disabled_properties):\n result = f'max_len_{length}_vocab_{vocabulary_size}_seed_{seed}'\n if inference:\n result += '_inference'\n \n if step3:\n result += '_step3'\n\n if multi_task:\n result += '_multi'\n if multi_task_lambda:\n result += f'_lambda_{multi_task_lambda}'\n\n if disabled_properties:\n result += \"_disabled\"\n for image_property in disabled_properties:\n result += f'_{int(image_property)}'\n\n return result\n\n\ndef generate_model_name(length, vocabulary_size, messages_seed, training_seed, inference, step3, multi_task, multi_task_lambda, disabled_properties):\n result = f'max_len_{length}_vocab_{vocabulary_size}_msg_seed_{messages_seed}_train_seed_{training_seed}'\n if inference:\n result += '_inference'\n \n if step3:\n result += '_step3'\n\n if multi_task:\n result += '_multi'\n if multi_task_lambda:\n result += f'_lambda_{multi_task_lambda}'\n\n if disabled_properties:\n result += \"_disabled\"\n for image_property in disabled_properties:\n result += f'_{int(image_property)}'\n\n # result += '.p'\n\n return result\n\ndef save_model(path, model, optimizer, iteration=None):\n torch_state = {'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict()\n }\n if iteration:\n torch_state[\"iteration\"] = iteration\n\n torch.save(torch_state, path)\n\ndef load_model(path, model, optimizer):\n if not os.path.exists(path):\n return 0\n \n print('Loading model from checkpoint...')\n\n checkpoint = torch.load(path)\n model.load_state_dict(checkpoint['model_state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n\n iteration = 0\n if checkpoint['iteration']:\n iteration = checkpoint['iteration']\n\n return iteration\n\ndef baseline(args):\n\n args = parse_arguments(args)\n\n if args.device:\n device = torch.device(args.device)\n else:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # file_helper = FileHelper()\n train_helper = TrainHelper(device)\n train_helper.seed_torch(seed=args.seed)\n\n model = ImageReceiver()\n model.to(device)\n\n unique_name = generate_unique_name(\n length=args.max_length,\n vocabulary_size=args.vocab_size,\n seed=args.messages_seed,\n inference=args.inference,\n step3=args.step3,\n multi_task=args.multi_task,\n multi_task_lambda=args.multi_task_lambda,\n disabled_properties=args.disabled_properties)\n \n model_name = generate_model_name(\n length=args.max_length,\n vocabulary_size=args.vocab_size,\n messages_seed=args.messages_seed,\n training_seed=args.seed,\n inference=args.inference,\n step3=args.step3,\n multi_task=args.multi_task,\n multi_task_lambda=args.multi_task_lambda,\n disabled_properties=args.disabled_properties)\n\n if not os.path.exists('results'):\n os.mkdir('results')\n\n reproducing_folder = os.path.join('results', 'reproducing-images')\n if not os.path.exists(reproducing_folder):\n os.mkdir(reproducing_folder)\n\n output_path = os.path.join(reproducing_folder, model_name)\n if not os.path.exists(output_path):\n os.mkdir(output_path)\n\n model_path = os.path.join(output_path, 'messages_receiver.p')\n\n print(f'loading messages using unique name: \"{unique_name}\"')\n\n train_dataset = MessageDataset(unique_name, DatasetType.Train)\n train_dataloader = data.DataLoader(train_dataset, num_workers=1, pin_memory=True, shuffle=True, batch_size=args.batch_size)\n\n validation_dataset = MessageDataset(unique_name, DatasetType.Valid)\n validation_dataloader = data.DataLoader(validation_dataset, num_workers=1, pin_memory=True, shuffle=False, batch_size=args.batch_size)\n\n test_dataset = MessageDataset(unique_name, DatasetType.Test)\n test_dataloader = data.DataLoader(test_dataset, num_workers=1, pin_memory=True, shuffle=False, batch_size=args.batch_size)\n\n pytorch_total_params = sum(p.numel() for p in model.parameters())\n\n # Print info\n print(\"----------------------------------------\")\n # print(\n # \"Model name: {} \\n|V|: {}\\nL: {}\".format(\n # model_name, args.vocab_size, args.max_length\n # )\n # )\n # print(sender)\n # print(visual_module)\n print(model)\n print(\"Total number of parameters: {}\".format(pytorch_total_params))\n\n\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)\n\n epoch = 0\n current_patience = args.patience\n best_f1_score = -1.\n converged = False\n\n start_time = time.time()\n\n criterion = torch.nn.MSELoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)\n\n images_path = os.path.join(output_path, 'samples')\n if not os.path.exists(images_path):\n os.mkdir(images_path)\n\n iteration = load_model(model_path, model, optimizer)\n\n if args.test_mode:\n test_images_path = os.path.join(images_path, 'test')\n if not os.path.exists(test_images_path):\n os.mkdir(test_images_path)\n\n test_loss_meter, test_acc_meter, test_f1_meter = evaluate(model, criterion, test_dataloader, 0, device, test_images_path)\n print(f'TEST results: F1: {test_f1_meter.avg} | loss: {test_loss_meter.avg} | accuracy: {test_acc_meter.avg}')\n return\n\n\n print(header)\n while iteration < args.iterations:\n for (messages, original_targets) in train_dataloader:\n print(f'{iteration}/{args.iterations} \\r', end='')\n\n model.train()\n\n _, _, _ = perform_iteration(model, criterion, optimizer, messages, original_targets, iteration, device, images_path, False)\n\n if iteration % args.log_interval == 0:\n valid_loss_meter, valid_acc_meter, valid_f1_meter = evaluate(model, criterion, validation_dataloader, iteration, device, images_path)\n\n new_best = False\n average_valid_f1_score = valid_f1_meter.avg\n\n if average_valid_f1_score < best_f1_score:\n current_patience -= 1\n\n if current_patience <= 0:\n print('Model has converged. Stopping training...')\n converged = True\n break\n else:\n new_best = True\n best_f1_score = average_valid_f1_score\n current_patience = args.patience\n save_model(model_path, model, optimizer, iteration)\n\n\n print(log_template.format(\n time.time()-start_time,\n epoch,\n iteration,\n 1 + iteration,\n args.iterations,\n 100. * (1+iteration) / args.iterations,\n valid_f1_meter.avg,\n valid_loss_meter.avg,\n valid_acc_meter.avg,\n \"BEST\" if new_best else \"\"))\n\n iteration += 1\n \n epoch += 1\n \n if converged:\n break\n\nif __name__ == \"__main__\":\n baseline(sys.argv[1:])\n" ]
[ [ "matplotlib.pyplot.imsave", "torch.load", "torch.utils.data.DataLoader", "torch.cuda.is_available", "torch.device", "sklearn.metrics.f1_score", "torch.nn.MSELoss", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
GranthamImperial/silicone_examples
[ "f7700a2d73c8d0db2836568ab1572f0ed240ad76" ]
[ "scripts/compare_crunchers.py" ]
[ "from multiprocessing import Pool, cpu_count, freeze_support\n\nimport numpy as np\nimport pandas as pd\nimport pyam\n\nimport silicone.database_crunchers as dc\n\n\n\"\"\"\nThis script measures how accurate the different crunchers are at recreating known data.\nWe remove the data of interest, infill to find it and compare the true and infilled \nvalues. It normalises this difference by the total range of the data. It runs on \nmultiple cores and saves the resulting statistics to disk. It may run for either a list\nof specified cases, or for all possible cases. Optionally it can also \nplot graphs comparing the infilled and original data - this is best done with only a \nsmall number of cases, otherwise a huge number of files will be created. \n\nThe options controlling how it works are listed below.\n\"\"\"\n\n\ndef main():\n freeze_support()\n # __________________________________Input options___________________________________\n # Where is the file stored for data used to fill in the sheet?\n input_data = \"./sr_15_complete.csv\"\n # A list of all crunchers to investigate, here a reference to the actual cruncher\n crunchers_list = [\n # dc.LatestTimeRatio,\n dc.TimeDepRatio,\n dc.QuantileRollingWindows,\n dc.RMSClosest,\n dc.LinearInterpolation,\n dc.EqualQuantileWalk,\n ]\n options_list = [\n # {},\n {\"same_sign\": True},\n {\"use_ratio\": False},\n {},\n {},\n {},\n ]\n # This list must agree with the above list, but is the name of the crunchers\n crunchers_name_list = [\n x.__name__.replace(\"DatabaseCruncher\", \"\") for x in crunchers_list\n ]\n # Leader is a single data class presented as a list.\n leaders = [\"Emissions|CO2\"]\n # Place to save the infilled data as a csv\n save_file = \"../Output/CruncherResults/CruncherComparisonLead_stdv_{}.csv\".format(\n leaders[0].split(\"|\")[-1]\n )\n # Do we want to save plots? If not, leave as None, else the location to save them.\n # Note that these are not filter-dependent and so only the results of the last\n # filter will persist\n save_plots = None # \"../output/CruncherResults/plots/\"\n # Do we want to run this for all possible filters? If so, choose none,\n # otherwise specify the filter here as a list of tuples\n to_compare_filter = None\n \"\"\"[\n (\"AIM/CGE 2.0\", \"SSP1-19\"),\n (\"AIM/CGE 2.1\", \"TERL_15D_NoTransportPolicy\"),\n ]\"\"\"\n years = range(2020, 2101, 10)\n # __________________________________end options_____________________________________\n\n assert len(crunchers_list) == len(crunchers_name_list)\n assert len(options_list) == len(crunchers_name_list)\n\n db_all = pyam.IamDataFrame(input_data).filter(region=\"World\", year=years)\n db_all.filter(variable=\"Emissions|Kyoto Gases*\", keep=False, inplace=True)\n # This is the model/scenario combination to compare.\n if to_compare_filter:\n all_possible_filters = to_compare_filter\n else:\n all_possible_filters = (\n db_all.data[[\"model\", \"scenario\"]]\n .groupby([\"model\", \"scenario\"])\n .size()\n .index.values\n )\n vars_to_crunch = [\n req for req in db_all.filter(level=1).variables() if req not in leaders\n ]\n db_all.filter(variable=vars_to_crunch + leaders, inplace=True)\n # Set up normalisation\n norm_factors = pd.DataFrame(index=years, columns=vars_to_crunch, dtype=float)\n for year in norm_factors.index:\n for var_inst in vars_to_crunch:\n norm_factors[var_inst][year] = np.std(\n db_all.filter(year=year, variable=var_inst).data[\"value\"]\n )\n all_args = [\n (\n filter_instance,\n norm_factors,\n db_all,\n vars_to_crunch,\n crunchers_name_list,\n crunchers_list,\n save_plots,\n leaders,\n options_list,\n )\n for filter_instance in all_possible_filters\n ]\n\n # Perform the loop\n with Pool(cpu_count() - 1) as pool:\n results_db = list(pool.map(_recalc_and_compare_results, all_args))\n\n results_count = sum([result.notnull() for result in list(results_db)])\n overall_results = sum([result.fillna(0) for result in list(results_db)])\n overall_results = overall_results / results_count\n overall_results.to_csv(save_file)\n\n\ndef _recalc_and_compare_results(args):\n (\n one_filter,\n norm_factors,\n db_all,\n vars_to_crunch,\n crunchers_name_list,\n crunchers_list,\n save_plots,\n leaders,\n options_list,\n ) = args\n combo_filter = {\"model\": one_filter[0], \"scenario\": one_filter[1]}\n input_to_fill = db_all.filter(**combo_filter)\n results_db = pd.DataFrame(index=vars_to_crunch, columns=crunchers_name_list)\n if leaders not in input_to_fill.variables(False).values:\n print(\n \"No data for {} in model {}, scen {}\".format(\n leaders, one_filter[0], one_filter[1]\n )\n )\n return results_db\n # Remove all items that overlap directly with this\n db_filter = db_all.filter(**combo_filter, keep=False)\n for cruncher_ind in range(len(crunchers_list)):\n for var_inst in vars_to_crunch:\n originals = input_to_fill.filter(variable=var_inst).data.set_index(\"year\")[\n \"value\"\n ]\n if originals.empty:\n print(\"No data available for {}\".format(var_inst))\n continue\n valid_scenarios = db_filter.filter(variable=var_inst).scenarios()\n db = db_filter.filter(scenario=valid_scenarios)\n # Initialise the object that holds the results\n cruncher_instance = crunchers_list[cruncher_ind](db)\n filler = cruncher_instance.derive_relationship(\n var_inst, leaders, **options_list[cruncher_ind]\n )\n interpolated = filler(input_to_fill)\n interp_values = interpolated.data.set_index(\"year\")[\"value\"]\n if originals.size != interp_values.size:\n print(\n \"Wrong number of values from cruncher {}: {}, not {}\".format(\n crunchers_name_list[cruncher_ind],\n interp_values.size,\n originals.size,\n )\n )\n continue\n assert (\n interpolated[\"year\"].size == interpolated[\"year\"].unique().size\n ), \"The wrong number of years have returned values\"\n\n # Calculate the RMS difference, Normalised by the spread of values\n results_db[crunchers_name_list[cruncher_ind]][var_inst] = (\n np.nanmean(\n (\n (interp_values - originals) / norm_factors[var_inst]\n )\n ** 2\n )\n ) ** 0.5\n print(\"Completed cruncher {}\".format(crunchers_name_list[cruncher_ind]))\n return results_db\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.nanmean", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
TileDB-Inc/pyread7k
[ "354f6dc3bdcf12d887e0924688cd9b7c93d3b55b" ]
[ "pyread7k/_ping.py" ]
[ "\"\"\"\nThis module is an abstraction on top of the low-level 7k records, which allows\nthe user to work in terms of \"pings\" with associated data, instead of thinking\nin the traditional 7k records.\n\nExpected order of records for a ping:\n7000, 7503, 1750, 7002, 7004, 7017, 7006, 7027, 7007, 7008, 7010, 7011, 7012,\n7013, 7018, 7019, 7028, 7029, 7037, 7038, 7039, 7041, 7042, 7048, 7049, 7057,\n7058, 7068, 7070\n\n\"\"\"\nimport bisect\nimport sys\nfrom abc import ABCMeta, abstractmethod\nfrom datetime import datetime, timedelta\nfrom enum import Enum\nfrom itertools import chain\nfrom typing import (\n Any,\n BinaryIO,\n Dict,\n Iterator,\n List,\n Optional,\n Sequence,\n Tuple,\n Union,\n cast,\n)\n\nimport geopy\nimport numpy as np\n\nfrom . import _datarecord, records\nfrom ._utils import cached_property, window\n\n\nclass PingType(Enum):\n \"\"\" Kinds of pings based on what data they have available \"\"\"\n\n BEAMFORMED = 1\n IQ = 2\n ANY = 3\n\n\nclass S7KReader(metaclass=ABCMeta):\n \"\"\"\n Base abstract class of S7K readers\n\n *Note*: The current S7KReader API is considered unstable and may change in the future.\n \"\"\"\n\n @cached_property\n def file_header(self) -> records.FileHeader:\n \"\"\"Return the file header record for this reader\"\"\"\n return cast(records.FileHeader, self._read_record(7200, 0))\n\n @cached_property\n def file_catalog(self) -> records.FileCatalog:\n \"\"\"Return the file catalog record for this reader\"\"\"\n return cast(\n records.FileCatalog,\n self._read_record(7300, self.file_header.catalog_offset),\n )\n\n @cached_property\n def configuration(self) -> records.Configuration:\n \"\"\"Return the configuration record for this reader\"\"\"\n offsets = self._get_offsets(7001)\n assert len(offsets) == 1\n return cast(records.Configuration, self._read_record(7001, offsets[0]))\n\n def iter_pings(self, include: PingType = PingType.ANY) -> Iterator[\"Ping\"]:\n \"\"\"Iterate over Pings. if include argument is not ANY, filter pings by type\"\"\"\n offsets_records = chain(self._iter_offset_records(7000), [None])\n pings = (\n Ping(\n cast(Tuple[int, records.SonarSettings], offset_record),\n cast(Optional[Tuple[int, records.SonarSettings]], next_offset_record),\n reader=self,\n )\n for offset_record, next_offset_record in window(offsets_records, 2)\n )\n if include == PingType.ANY:\n return pings\n if include == PingType.BEAMFORMED:\n return (p for p in pings if p.has_beamformed)\n if include == PingType.IQ:\n return (p for p in pings if p.has_raw_iq)\n raise NotImplementedError(f\"Encountered unknown PingType: {include!r}\")\n\n def get_first_offset(\n self, record_type: int, offset_start: int, offset_end: int\n ) -> Optional[int]:\n \"\"\"\n Get the offset of the first record of type record_type which has a\n file offset between offset_start and offset_end.\n \"\"\"\n offsets = self._get_offsets(record_type)\n i = bisect.bisect_right(offsets, offset_start)\n return offsets[i] if i < len(offsets) and offsets[i] < offset_end else None\n\n def read_first_record(\n self, record_type: int, offset_start: int, offset_end: int\n ) -> Optional[records.BaseRecord]:\n \"\"\"\n Read the first record of type record_type which has a file offset between\n offset_start and offset_end.\n \"\"\"\n offset = self.get_first_offset(record_type, offset_start, offset_end)\n return self._read_record(record_type, offset) if offset is not None else None\n\n def read_records_during_ping(\n self,\n record_type: int,\n ping_start: datetime,\n ping_end: datetime,\n offset_hint: int,\n ) -> List[records.BaseRecord]:\n \"\"\"\n Read all records of record_type which are timestamped in the interval between\n ping_start and ping_end. An offset_hint is given as an initial offset of a record\n close to the interval, to be used if it can make the search more efficient.\n \"\"\"\n # Performs a brute-force search starting around the offset_hint. If the\n # hint is good (which it should usually be), this is pretty efficient.\n #\n # Records of different types are not guaranteed to be chronological, so\n # we cannot know a specific record interval to search.\n read_record = self._read_record\n offsets = self._get_offsets(record_type)\n initial_index = bisect.bisect_left(offsets, offset_hint)\n\n # Search forward in file\n forward_records = []\n searching_backward = True\n for index in range(initial_index, len(offsets)):\n next_record = read_record(record_type, offsets[index])\n next_record_time = next_record.frame.time\n if next_record_time > ping_end:\n # Reached upper end of interval\n break\n elif next_record_time <= ping_start:\n # Did not yet reach interval, backward search is unnecessary\n searching_backward = False\n else:\n forward_records.append(next_record)\n\n if not searching_backward:\n return forward_records\n\n # Search backward in file\n backward_records = []\n for index in range(initial_index - 1, -1, -1):\n next_record = read_record(record_type, offsets[index])\n next_record_time = next_record.frame.time\n if next_record_time < ping_start:\n # Reached lower end of interval\n break\n elif next_record_time >= ping_end:\n # Did not yet reach interval\n pass\n else:\n backward_records.append(next_record)\n\n # Discovered in reverse order, so un-reverse\n backward_records.reverse()\n backward_records.extend(forward_records)\n return backward_records\n\n def _read_record(self, record_type: int, offset: int) -> records.BaseRecord:\n \"\"\"Read a record of record_type at the given offset\"\"\"\n return _datarecord.record(record_type).read(self._get_stream_for_read(offset))\n\n def _iter_offset_records(\n self, record_type: int\n ) -> Iterator[Tuple[int, records.BaseRecord]]:\n \"\"\"Generate all the (offset, record) tuples for the given record type\"\"\"\n read_record = _datarecord.record(record_type).read\n get_stream = self._get_stream_for_read\n for offset in self._get_offsets(record_type):\n yield offset, read_record(get_stream(offset))\n\n def _get_offsets(self, record_type: int) -> Sequence[int]:\n \"\"\"Return all the offsets for the given record type\"\"\"\n try:\n return self.__cached_offsets[record_type]\n except (AttributeError, KeyError) as ex:\n offsets: List[int] = []\n if record_type != 7300:\n catalog = self.file_catalog\n offsets.extend(\n offset\n for offset, rt in zip(catalog.offsets, catalog.record_types)\n if rt == record_type\n )\n else:\n # the file catalog does not contain an entry for the 7300 record\n offsets.append(self.file_header.catalog_offset)\n\n if isinstance(ex, AttributeError):\n self.__cached_offsets: Dict[int, Sequence[int]] = {}\n return self.__cached_offsets.setdefault(record_type, offsets)\n\n @abstractmethod\n def _get_stream_for_read(self, offset: int) -> BinaryIO:\n \"\"\"Return a byte stream for reading a record at the given offset\"\"\"\n\n\nclass S7KFileReader(S7KReader):\n \"\"\"Reader class for s7k files\"\"\"\n\n def __init__(self, filename: str):\n self._filename = filename\n self._fhandle = open(self._filename, \"rb\", buffering=0)\n\n def _get_stream_for_read(self, offset: int) -> BinaryIO:\n self._fhandle.seek(offset)\n return self._fhandle\n\n def __getstate__(self) -> Dict[str, Any]:\n \"\"\" Remove unpicklable file handle from dict before pickling. \"\"\"\n state = self.__dict__.copy()\n del state[\"_fhandle\"]\n return state\n\n def __setstate__(self, state: Dict[str, Any]) -> None:\n \"\"\" Open new file handle after unpickling. \"\"\"\n self.__dict__.update(state)\n self._fhandle = open(self._filename, \"rb\", buffering=0)\n\n def __del__(self) -> None:\n self._fhandle.close()\n\n\nclass Ping:\n \"\"\"\n A sound ping from a sonar, with associated data about settings and conditions.\n Properties of the ping are loaded efficiently on-demand.\n \"\"\"\n\n def __init__(\n self,\n offset_record: Tuple[int, records.SonarSettings],\n next_offset_record: Optional[Tuple[int, records.SonarSettings]],\n reader: S7KReader,\n ):\n self._reader = reader\n self._offset, self.sonar_settings = offset_record\n\n if next_offset_record is not None:\n self._next_offset, next_sonar_settings = next_offset_record\n self._next_ping_start = next_sonar_settings.frame.time\n else:\n self._next_offset = sys.maxsize\n self._next_ping_start = datetime.max\n\n def __str__(self) -> str:\n return f\"<Ping {self.ping_number}>\"\n\n @property\n def ping_number(self) -> int:\n return self.sonar_settings.ping_number\n\n @property\n def configuration(self) -> records.Configuration:\n \"\"\"Return the 7001 record, which is shared for all pings in a file\"\"\"\n return self._reader.configuration\n\n @cached_property\n def position_set(self) -> List[records.Position]:\n \"\"\" Returns all 1003 records timestamped within this ping. \"\"\"\n return cast(List[records.Position], self._read_records(1003))\n\n @cached_property\n def roll_pitch_heave_set(self) -> List[records.RollPitchHeave]:\n \"\"\" Returns all 1012 records timestamped within this ping. \"\"\"\n return cast(List[records.RollPitchHeave], self._read_records(1012))\n\n @cached_property\n def heading_set(self) -> List[records.Heading]:\n \"\"\" Returns all 1013 records timestamped within this ping. \"\"\"\n return cast(List[records.Heading], self._read_records(1013))\n\n @cached_property\n def beam_geometry(self) -> Optional[records.BeamGeometry]:\n \"\"\" Returns 7004 record \"\"\"\n return cast(Optional[records.BeamGeometry], self._read_record(7004))\n\n @cached_property\n def tvg(self) -> Optional[records.TVG]:\n \"\"\" Returns 7010 record \"\"\"\n return cast(Optional[records.TVG], self._read_record(7010))\n\n @cached_property\n def has_beamformed(self) -> bool:\n \"\"\" Checks if the ping has 7018 data without reading it. \"\"\"\n return (\n self._reader.get_first_offset(7018, self._offset, self._next_offset)\n is not None\n )\n\n @cached_property\n def beamformed(self) -> Optional[records.Beamformed]:\n \"\"\" Returns 7018 record \"\"\"\n return cast(Optional[records.Beamformed], self._read_record(7018))\n\n @cached_property\n def has_raw_iq(self) -> bool:\n \"\"\" Checks if the ping has 7038 data without reading it. \"\"\"\n return (\n self._reader.get_first_offset(7038, self._offset, self._next_offset)\n is not None\n )\n\n @cached_property\n def raw_iq(self) -> Optional[records.RawIQ]:\n \"\"\" Returns 7038 record \"\"\"\n return cast(Optional[records.RawIQ], self._read_record(7038))\n\n @cached_property\n def gps_position(self) -> geopy.Point:\n lat = self.position_set[0].latitude * 180 / np.pi\n long = self.position_set[0].longitude * 180 / np.pi\n return geopy.Point(lat, long)\n\n def receiver_motion_for_sample(\n self, sample: int\n ) -> Tuple[records.RollPitchHeave, records.Heading]:\n \"\"\" Find the most appropriate motion data for a sample based on time \"\"\"\n time = self.sonar_settings.frame.time + timedelta(seconds=sample / self.sonar_settings.sample_rate)\n rph_index = min(\n bisect.bisect_left([m.frame.time for m in self.roll_pitch_heave_set], time),\n len(self.roll_pitch_heave_set) - 1,\n )\n heading_index = min(\n bisect.bisect_left([m.frame.time for m in self.heading_set], time),\n len(self.heading_set) - 1,\n )\n return self.roll_pitch_heave_set[rph_index], self.heading_set[heading_index]\n\n def minimize_memory(self) -> None:\n \"\"\"\n Clears all memory-heavy properties.\n Retains offsets for easy reloading.\n \"\"\"\n for key in \"beamformed\", \"tvg\", \"beam_geometry\", \"raw_iq\":\n if key in self.__dict__:\n del self.__dict__[key]\n\n def _read_record(self, record_type: int) -> Optional[records.BaseRecord]:\n record = self._reader.read_first_record(\n record_type, self._offset, self._next_offset\n )\n if record is not None:\n ping_number = self.ping_number\n assert getattr(record, \"ping_number\", ping_number) == ping_number\n return record\n\n def _read_records(self, record_type: int) -> List[records.BaseRecord]:\n return self._reader.read_records_during_ping(\n record_type, self.sonar_settings.frame.time, self._next_ping_start, self._offset\n )\n\n\nclass PingDataset:\n \"\"\"\n Indexable dataset returning Pings from a 7k file.\n\n Provides random access into pings in a file with minimal overhead.\n \"\"\"\n\n def __init__(self, filename: str, include: PingType = PingType.ANY):\n \"\"\"\n if include argument is not ANY, pings will be filtered.\n \"\"\"\n self.pings = list(S7KFileReader(filename).iter_pings(include))\n self.__ping_numbers = [p.ping_number for p in self.pings]\n\n @property\n def ping_numbers(self) -> List[int]:\n return self.__ping_numbers\n\n def minimize_memory(self) -> None:\n for p in self.pings:\n p.minimize_memory()\n\n def __len__(self) -> int:\n return len(self.pings)\n\n def index_of(self, ping_number: int) -> int:\n return self.__ping_numbers.index(ping_number)\n\n def get_by_number(\n self, ping_number: int, default: Optional[Ping] = None\n ) -> Optional[Ping]:\n if not isinstance(ping_number, int):\n raise TypeError(\"Ping number must be an integer\")\n try:\n ping_index = self.ping_numbers.index(ping_number)\n except ValueError:\n return default\n return self.pings[ping_index]\n\n def __getitem__(self, index: Union[int, slice]) -> Union[Ping, List[Ping]]:\n return self.pings[index]\n\n\nclass ConcatDataset:\n \"\"\"\n Dataset concatenation object\n \"\"\"\n\n def __init__(self, datasets):\n self.cum_lengths = np.cumsum([len(d) for d in datasets])\n self.datasets = datasets\n self.__ping_numbers = [pn for ds in datasets for pn in ds.ping_numbers]\n\n def __len__(self) -> int:\n return self.cum_lengths[-1]\n\n @property\n def ping_numbers(self) -> List[int]:\n return self.__ping_numbers\n\n def index_of(self, ping_number: int) -> int:\n return self.ping_numbers.index(ping_number)\n\n def get_by_number(\n self, ping_number: int, default: Optional[int] = None\n ) -> Union[Ping, None]:\n if not isinstance(ping_number, int):\n raise TypeError(\"Ping number must be an integer\")\n for ds in self.datasets:\n if (ping_index := ds.get_by_number(ping_number, default)) is not None:\n return ds[ping_index]\n return default\n\n def __getitem__(self, index: Union[slice, int]) -> Union[Ping, List[Ping]]:\n if not isinstance(index, slice):\n if index < 0:\n if -index > len(self):\n raise ValueError(\"Index out of range\")\n index = len(self) + index\n dataset_index = np.searchsorted(self.cum_lengths, index, side=\"right\")\n if dataset_index == 0:\n sample_index = index\n else:\n sample_index = index - self.cum_lengths[dataset_index - 1]\n return self.datasets[dataset_index][sample_index]\n else:\n return [self[i] for i in range(*index.indices(len(self)))]\n" ]
[ [ "numpy.searchsorted" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lbalicki/pymor
[ "8de5f16499b95a48c6332449677540383548dc3e", "8de5f16499b95a48c6332449677540383548dc3e" ]
[ "src/pymor/grids/tria.py", "src/pymor/algorithms/greedy.py" ]
[ "# This file is part of the pyMOR project (http://www.pymor.org).\n# Copyright 2013-2019 pyMOR developers and contributors. All rights reserved.\n# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\nimport numpy as np\n\nfrom pymor.core.cache import cached\nfrom pymor.grids.interfaces import AffineGridWithOrthogonalCentersInterface\nfrom pymor.grids.referenceelements import triangle\n\n\nclass TriaGrid(AffineGridWithOrthogonalCentersInterface):\n r\"\"\"Basic implementation of a triangular grid on a rectangular domain.\n\n The global face, edge and vertex indices are given as follows ::\n\n 6---------10----------7---------11----------8\n | \\ / | \\ / |\n | 22 10 18 | 23 11 19 |\n | \\ / | \\ / |\n 3 14 11 6 4 15 12 7 5\n | / \\ | / \\ |\n | 14 2 26 | 15 3 27 |\n | / \\ | / \\ |\n 3----------8----------4----------9----------5\n | \\ / | \\ / |\n | 20 8 16 | 21 9 17 |\n | \\ / | \\ / |\n 0 12 9 4 1 13 10 5 2\n | / \\ | / \\ |\n | 12 0 24 | 13 1 25 |\n | / \\ | / \\ |\n 0----------6----------1----------7----------2\n\n Parameters\n ----------\n num_intervals\n Tuple `(n0, n1)` determining a grid with `n0` x `n1` codim-0 entities.\n domain\n Tuple `(ll, ur)` where `ll` defines the lower left and `ur` the upper right\n corner of the domain.\n identify_left_right\n If `True`, the left and right boundaries are identified, i.e. the left-most\n codim-0 entities become neighbors of the right-most codim-0 entities.\n identify_bottom_top\n If `True`, the bottom and top boundaries are identified, i.e. the bottom-most\n codim-0 entities become neighbors of the top-most codim-0 entities.\n \"\"\"\n\n dim = 2\n reference_element = triangle\n\n def __init__(self, num_intervals=(2, 2), domain=([0, 0], [1, 1]),\n identify_left_right=False, identify_bottom_top=False):\n if identify_left_right:\n assert num_intervals[0] > 1\n if identify_bottom_top:\n assert num_intervals[1] > 1\n domain = np.array(domain)\n self.__auto_init(locals())\n\n self.x0_num_intervals = x0_num_intervals = num_intervals[0]\n self.x1_num_intervals = x1_num_intervals = num_intervals[1]\n self.x0_range = self.domain[:, 0]\n self.x1_range = self.domain[:, 1]\n self.x0_width = self.x0_range[1] - self.x0_range[0]\n self.x1_width = self.x1_range[1] - self.x1_range[0]\n self.x0_diameter = self.x0_width / x0_num_intervals\n self.x1_diameter = self.x1_width / x1_num_intervals\n n_elements = x0_num_intervals * x1_num_intervals * 4\n\n # TOPOLOGY\n n_outer_vertices = (x0_num_intervals + 1 - identify_left_right) * (x1_num_intervals + 1 - identify_bottom_top)\n self.__sizes = (n_elements,\n ((x0_num_intervals + 1 - identify_left_right) * x1_num_intervals\n + (x1_num_intervals + 1 - identify_bottom_top) * x0_num_intervals\n + n_elements),\n n_outer_vertices + int(n_elements / 4))\n\n # calculate subentities -- codim-1\n V_EDGE_H_INDICES = np.arange(x0_num_intervals + 1, dtype=np.int32)\n if identify_left_right:\n V_EDGE_H_INDICES[-1] = 0\n V_EDGE_V_INDICES = np.arange(x1_num_intervals, dtype=np.int32) * (x0_num_intervals + 1 - identify_left_right)\n V_EDGE_INDICES = V_EDGE_V_INDICES[:, np.newaxis] + V_EDGE_H_INDICES\n num_v_edges = x1_num_intervals * (x0_num_intervals + 1 - identify_left_right)\n\n H_EDGE_H_INDICES = np.arange(x0_num_intervals, dtype=np.int32)\n H_EDGE_V_INDICES = np.arange(x1_num_intervals + 1, dtype=np.int32)\n if identify_bottom_top:\n H_EDGE_V_INDICES[-1] = 0\n H_EDGE_V_INDICES *= x0_num_intervals\n H_EDGE_INDICES = H_EDGE_V_INDICES[:, np.newaxis] + H_EDGE_H_INDICES + num_v_edges\n num_h_edges = x0_num_intervals * (x1_num_intervals + 1 - identify_bottom_top)\n\n D_EDGE_LL_INDICES = np.arange(n_elements / 4, dtype=np.int32) + (num_v_edges + num_h_edges)\n D_EDGE_UR_INDICES = D_EDGE_LL_INDICES + int(n_elements / 4)\n D_EDGE_UL_INDICES = D_EDGE_UR_INDICES + int(n_elements / 4)\n D_EDGE_LR_INDICES = D_EDGE_UL_INDICES + int(n_elements / 4)\n\n E0 = np.array([H_EDGE_INDICES[:-1, :].ravel(),\n D_EDGE_LR_INDICES,\n D_EDGE_LL_INDICES]).T\n E1 = np.array([V_EDGE_INDICES[:, 1:].ravel(),\n D_EDGE_UR_INDICES,\n D_EDGE_LR_INDICES]).T\n E2 = np.array([H_EDGE_INDICES[1:, :].ravel(),\n D_EDGE_UL_INDICES,\n D_EDGE_UR_INDICES]).T\n E3 = np.array([V_EDGE_INDICES[:, :-1].ravel(),\n D_EDGE_LL_INDICES,\n D_EDGE_UL_INDICES]).T\n\n codim1_subentities = np.vstack((E0, E1, E2, E3))\n\n # calculate subentities -- codim-2\n VERTEX_H_INDICES = np.arange(x0_num_intervals + 1, dtype=np.int32)\n if identify_left_right:\n VERTEX_H_INDICES[-1] = 0\n VERTEX_V_INDICES = np.arange(x1_num_intervals + 1, dtype=np.int32)\n if identify_bottom_top:\n VERTEX_V_INDICES[-1] = 0\n VERTEX_V_INDICES *= x0_num_intervals + 1 - identify_left_right\n VERTEX_NUMERS = VERTEX_V_INDICES[:, np.newaxis] + VERTEX_H_INDICES\n VERTEX_CENTER_NUMBERS = np.arange(x0_num_intervals * x1_num_intervals, dtype=np.int32) + n_outer_vertices\n\n V0 = np.array([VERTEX_CENTER_NUMBERS,\n VERTEX_NUMERS[:-1, :-1].ravel(),\n VERTEX_NUMERS[:-1, 1:].ravel()]).T\n V1 = np.array([VERTEX_CENTER_NUMBERS,\n VERTEX_NUMERS[:-1, 1:].ravel(),\n VERTEX_NUMERS[1:, 1:].ravel()]).T\n V2 = np.array([VERTEX_CENTER_NUMBERS,\n VERTEX_NUMERS[1:, 1:].ravel(),\n VERTEX_NUMERS[1:, :-1].ravel()]).T\n V3 = np.array([VERTEX_CENTER_NUMBERS,\n VERTEX_NUMERS[1:, :-1].ravel(),\n VERTEX_NUMERS[:-1, :-1].ravel()]).T\n\n codim2_subentities = np.vstack((V0, V1, V2, V3))\n self.__subentities = (codim1_subentities, codim2_subentities)\n\n # GEOMETRY\n\n # embeddings\n x0_shifts = np.arange(x0_num_intervals) * self.x0_diameter + (self.x0_range[0] + 0.5 * self.x0_diameter)\n x1_shifts = np.arange(x1_num_intervals) * self.x1_diameter + (self.x1_range[0] + 0.5 * self.x1_diameter)\n B = np.tile(np.array(np.meshgrid(x0_shifts, x1_shifts)).reshape((2, -1)).T,\n (4, 1))\n\n ROT45 = np.array([[1./np.sqrt(2.), -1./np.sqrt(2.)],\n [1./np.sqrt(2.), 1./np.sqrt(2.)]])\n ROT135 = np.array([[-1./np.sqrt(2.), -1./np.sqrt(2.)],\n [1./np.sqrt(2.), -1./np.sqrt(2.)]])\n ROT225 = np.array([[-1./np.sqrt(2.), 1./np.sqrt(2.)],\n [-1./np.sqrt(2.), -1./np.sqrt(2.)]])\n ROT315 = np.array([[1./np.sqrt(2.), 1./np.sqrt(2.)],\n [-1./np.sqrt(2.), 1./np.sqrt(2.)]])\n SCAL = np.diag([self.x0_diameter / np.sqrt(2), self.x1_diameter / np.sqrt(2)])\n A0 = np.tile(SCAL.dot(ROT225), (int(n_elements / 4), 1, 1))\n A1 = np.tile(SCAL.dot(ROT315), (int(n_elements / 4), 1, 1))\n A2 = np.tile(SCAL.dot(ROT45), (int(n_elements / 4), 1, 1))\n A3 = np.tile(SCAL.dot(ROT135), (int(n_elements / 4), 1, 1))\n A = np.vstack((A0, A1, A2, A3))\n self.__embeddings = (A, B)\n\n def __reduce__(self):\n return (TriaGrid,\n (self.num_intervals, self.domain, self.identify_left_right, self.identify_bottom_top))\n\n def __str__(self):\n return (f'Tria-Grid on domain '\n f'[{self.x0_range[0]},{self.x0_range[1]}] x [{self.x1_range[0]},{self.x1_range[1]}]\\n'\n f'x0-intervals: {self.x0_num_intervals}, x1-intervals: {self.x1_num_intervals}\\n'\n f'elements: {self.size(0)}, edges: {self.size(1)}, vertices: {self.size(2)}')\n\n def size(self, codim=0):\n assert 0 <= codim <= 2, 'Invalid codimension'\n return self.__sizes[codim]\n\n def subentities(self, codim, subentity_codim):\n assert 0 <= codim <= 2, 'Invalid codimension'\n assert codim <= subentity_codim <= 2, 'Invalid subentity codimension'\n if codim == 0:\n if subentity_codim == 0:\n return np.arange(self.size(0), dtype='int32')[:, np.newaxis]\n else:\n return self.__subentities[subentity_codim - 1]\n else:\n return super().subentities(codim, subentity_codim)\n\n def embeddings(self, codim=0):\n if codim == 0:\n return self.__embeddings\n else:\n return super().embeddings(codim)\n\n def bounding_box(self):\n return np.array(self.domain)\n\n @cached\n def orthogonal_centers(self):\n embeddings = self.embeddings(0)\n ne4 = len(embeddings[0]) // 4\n if self.x0_diameter > self.x1_diameter:\n x0_fac = (self.x1_diameter / 2) ** 2 / (3 * (self.x0_diameter / 2) ** 2)\n x1_fac = 1./3.\n else:\n x1_fac = (self.x0_diameter / 2) ** 2 / (3 * (self.x1_diameter / 2) ** 2)\n x0_fac = 1./3.\n C0 = embeddings[0][:ne4].dot(np.array([x1_fac, x1_fac])) + embeddings[1][:ne4]\n C1 = embeddings[0][ne4:2*ne4].dot(np.array([x0_fac, x0_fac])) + embeddings[1][ne4:2*ne4]\n C2 = embeddings[0][2*ne4:3*ne4].dot(np.array([x1_fac, x1_fac])) + embeddings[1][2*ne4:3*ne4]\n C3 = embeddings[0][3*ne4:4*ne4].dot(np.array([x0_fac, x0_fac])) + embeddings[1][3*ne4:4*ne4]\n return np.concatenate((C0, C1, C2, C3), axis=0)\n\n def visualize(self, U, codim=2, **kwargs):\n \"\"\"Visualize scalar data associated to the grid as a patch plot.\n\n Parameters\n ----------\n U\n |NumPy array| of the data to visualize. If `U.dim == 2 and len(U) > 1`, the\n data is visualized as a time series of plots. Alternatively, a tuple of\n |Numpy arrays| can be provided, in which case a subplot is created for\n each entry of the tuple. The lengths of all arrays have to agree.\n codim\n The codimension of the entities the data in `U` is attached to (either 0 or 2).\n kwargs\n See :func:`~pymor.gui.qt.visualize_patch`\n \"\"\"\n from pymor.gui.qt import visualize_patch\n from pymor.vectorarrays.interfaces import VectorArrayInterface\n from pymor.vectorarrays.numpy import NumpyVectorSpace, NumpyVectorArray\n if isinstance(U, (np.ndarray, VectorArrayInterface)):\n U = (U,)\n assert all(isinstance(u, (np.ndarray, VectorArrayInterface)) for u in U)\n U = tuple(NumpyVectorSpace.make_array(u) if isinstance(u, np.ndarray) else\n u if isinstance(u, NumpyVectorArray) else\n NumpyVectorSpace.make_array(u.to_numpy())\n for u in U)\n bounding_box = kwargs.pop('bounding_box', self.domain)\n visualize_patch(self, U, codim=codim, bounding_box=bounding_box, **kwargs)\n", "# This file is part of the pyMOR project (http://www.pymor.org).\n# Copyright 2013-2019 pyMOR developers and contributors. All rights reserved.\n# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\nimport time\n\nimport numpy as np\n\nfrom pymor.core.exceptions import ExtensionError\nfrom pymor.core.interfaces import BasicInterface, abstractmethod\nfrom pymor.core.logger import getLogger\nfrom pymor.parallel.dummy import dummy_pool\nfrom pymor.parallel.interfaces import RemoteObjectInterface\nfrom pymor.tools.deprecated import Deprecated\n\n\ndef weak_greedy(surrogate, training_set, atol=None, rtol=None, max_extensions=None, pool=None):\n \"\"\"Weak greedy basis generation algorithm [BCDDPW11]_.\n\n This algorithm generates an approximation basis for a given set of vectors\n associated with a training set of parameters by iteratively evaluating a\n :class:`surrogate <WeakGreedySurrogate>` for the approximation error on\n the training set and adding the worst approximated vector (according to\n the surrogate) to the basis.\n\n The constructed basis is extracted from the surrogate after termination\n of the algorithm.\n\n Parameters\n ----------\n surrogate\n An instance of :class:`WeakGreedySurrogate` representing the surrogate\n for the approximation error.\n training_set\n The set of parameter samples on which to perform the greedy search.\n atol\n If not `None`, stop the algorithm if the maximum (estimated) error\n on the training set drops below this value.\n rtol\n If not `None`, stop the algorithm if the maximum (estimated)\n relative error on the training set drops below this value.\n max_extensions\n If not `None`, stop the algorithm after `max_extensions` extension\n steps.\n pool\n If not `None`, a |WorkerPool| to use for parallelization. Parallelization\n needs to be supported by `surrogate`.\n\n Returns\n -------\n Dict with the following fields:\n\n :max_errs: Sequence of maximum estimated errors during the greedy run.\n :max_err_mus: The parameters corresponding to `max_errs`.\n :extensions: Number of performed basis extensions.\n :time: Total runtime of the algorithm.\n \"\"\"\n logger = getLogger('pymor.algorithms.greedy.weak_greedy')\n training_set = list(training_set)\n logger.info(f'Started greedy search on training set of size {len(training_set)}.')\n\n tic = time.time()\n if not training_set:\n logger.info('There is nothing else to do for an empty training set.')\n return {'max_errs': [], 'max_err_mus': [], 'extensions': 0,\n 'time': time.time() - tic}\n\n if pool is None:\n pool = dummy_pool\n elif pool is not dummy_pool:\n logger.info(f'Using pool of {len(pool)} workers for parallel greedy search.')\n\n # Distribute the training set evenly among the workers.\n if pool:\n training_set = pool.scatter_list(training_set)\n\n extensions = 0\n max_errs = []\n max_err_mus = []\n\n while True:\n with logger.block('Estimating errors ...'):\n max_err, max_err_mu = surrogate.evaluate(training_set)\n max_errs.append(max_err)\n max_err_mus.append(max_err_mu)\n\n logger.info(f'Maximum error after {extensions} extensions: {max_err} (mu = {max_err_mu})')\n\n if atol is not None and max_err <= atol:\n logger.info(f'Absolute error tolerance ({atol}) reached! Stoping extension loop.')\n break\n\n if rtol is not None and max_err / max_errs[0] <= rtol:\n logger.info(f'Relative error tolerance ({rtol}) reached! Stoping extension loop.')\n break\n\n with logger.block(f'Extending surrogate for mu = {max_err_mu} ...'):\n try:\n surrogate.extend(max_err_mu)\n except ExtensionError:\n logger.info('Extension failed. Stopping now.')\n break\n extensions += 1\n\n logger.info('')\n\n if max_extensions is not None and extensions >= max_extensions:\n logger.info(f'Maximum number of {max_extensions} extensions reached.')\n break\n\n tictoc = time.time() - tic\n logger.info(f'Greedy search took {tictoc} seconds')\n return {'max_errs': max_errs, 'max_err_mus': max_err_mus, 'extensions': extensions,\n 'time': tictoc}\n\n\nclass WeakGreedySurrogate(BasicInterface):\n \"\"\"Surrogate for the approximation error in :func:`weak_greedy`.\"\"\"\n\n @abstractmethod\n def evaluate(self, mus, return_all_values=False):\n \"\"\"Evaluate the surrogate for given parameters.\n\n Parameters\n ----------\n mus\n List of parameters for which to estimate the approximation\n error. When parallelization is used, `mus` can be a |RemoteObject|.\n return_all_values\n See below.\n\n Returns\n -------\n If `return_all_values` is `True`, an |array| of the estimated errors.\n If `return_all_values` is `False`, the maximum estimated error as first\n return value and the corresponding parameter as second return value.\n \"\"\"\n pass\n\n @abstractmethod\n def extend(self, mu):\n pass\n\n\ndef rb_greedy(fom, reductor, training_set, use_estimator=True, error_norm=None,\n atol=None, rtol=None, max_extensions=None, extension_params=None, pool=None):\n \"\"\"Weak Greedy basis generation using the RB approximation error as surrogate.\n\n This algorithm generates a reduced basis using the :func:`weak greedy <weak_greedy>`\n algorithm [BCDDPW11]_, where the approximation error is estimated from computing\n solutions of the reduced order model for the current reduced basis and then estimating\n the model reduction error.\n\n Parameters\n ----------\n fom\n The |Model| to reduce.\n reductor\n Reductor for reducing the given |Model|. This has to be\n an object with a `reduce` method, such that `reductor.reduce()`\n yields the reduced model, and an `exted_basis` method,\n such that `reductor.extend_basis(U, copy_U=False, **extension_params)`\n extends the current reduced basis by the vectors contained in `U`.\n For an example see :class:`~pymor.reductors.coercive.CoerciveRBReductor`.\n training_set\n The training set of |Parameters| on which to perform the greedy search.\n use_estimator\n If `False`, exactly compute the model reduction error by also computing\n the solution of `fom` for each training set |Parameter|. This is mainly\n useful when no estimator for the model reduction error is available.\n error_norm\n If `use_estimator` is `False`, use this function to calculate the\n norm of the error. If `None`, the Euclidean norm is used.\n atol\n See :func:`weak_greedy`.\n rtol\n See :func:`weak_greedy`.\n max_extensions\n See :func:`weak_greedy`.\n extension_params\n `dict` of parameters passed to the `reductor.extend_basis` method.\n If `None`, `'gram_schmidt'` basis extension will be used as a default\n for stationary problems (`fom.solve` returns `VectorArrays` of length 1)\n and `'pod'` basis extension (adding a single POD mode) for instationary\n problems.\n pool\n See :func:`weak_greedy`.\n\n Returns\n -------\n Dict with the following fields:\n\n :rom: The reduced |Model| obtained for the\n computed basis.\n :max_errs: Sequence of maximum errors during the greedy run.\n :max_err_mus: The parameters corresponding to `max_errs`.\n :extensions: Number of performed basis extensions.\n :time: Total runtime of the algorithm.\n \"\"\"\n\n surrogate = RBSurrogate(fom, reductor, use_estimator, error_norm, extension_params, pool or dummy_pool)\n\n result = weak_greedy(surrogate, training_set, atol=atol, rtol=rtol, max_extensions=max_extensions, pool=pool)\n result['rom'] = surrogate.rom\n\n return result\n\n\nclass RBSurrogate(WeakGreedySurrogate):\n \"\"\"Surrogate for the :func:`weak_greedy` error used in :func:`rb_greedy`.\n\n Not intended to be used directly.\n \"\"\"\n\n def __init__(self, fom, reductor, use_estimator, error_norm, extension_params, pool):\n self.__auto_init(locals())\n if use_estimator:\n self.remote_fom, self.remote_error_norm, self.remote_reductor = None, None, None\n else:\n self.remote_fom, self.remote_error_norm, self.remote_reductor = \\\n pool.push(fom), pool.push(error_norm), pool.push(reductor)\n self.rom = None\n\n def evaluate(self, mus, return_all_values=False):\n if self.rom is None:\n with self.logger.block('Reducing ...'):\n self.rom = self.reductor.reduce()\n\n if not isinstance(mus, RemoteObjectInterface):\n mus = self.pool.scatter_list(mus)\n\n result = self.pool.apply(_rb_surrogate_evaluate,\n rom=self.rom,\n fom=self.remote_fom,\n reductor=self.remote_reductor,\n mus=mus,\n error_norm=self.remote_error_norm,\n return_all_values=return_all_values)\n if return_all_values:\n return np.hstack(result)\n else:\n errs, max_err_mus = list(zip(*result))\n max_err_ind = np.argmax(errs)\n return errs[max_err_ind], max_err_mus[max_err_ind]\n\n def extend(self, mu):\n with self.logger.block(f'Computing solution snapshot for mu = {mu} ...'):\n U = self.fom.solve(mu)\n with self.logger.block('Extending basis with solution snapshot ...'):\n extension_params = self.extension_params\n if len(U) > 1 and extension_params is None:\n extension_params = {'method': 'pod'}\n self.reductor.extend_basis(U, copy_U=False, **(extension_params or {}))\n if not self.use_estimator:\n self.remote_reductor = self.pool.push(self.reductor)\n with self.logger.block('Reducing ...'):\n self.rom = self.reductor.reduce()\n\n\ndef _rb_surrogate_evaluate(rom=None, fom=None, reductor=None, mus=None, error_norm=None, return_all_values=False):\n if not mus:\n if return_all_values:\n return []\n else:\n return -1., None\n\n if fom is None:\n errors = [rom.estimate(rom.solve(mu), mu) for mu in mus]\n elif error_norm is not None:\n errors = [error_norm(fom.solve(mu) - reductor.reconstruct(rom.solve(mu))) for mu in mus]\n else:\n errors = [(fom.solve(mu) - reductor.reconstruct(rom.solve(mu))).l2_norm() for mu in mus]\n # most error_norms will return an array of length 1 instead of a number, so we extract the numbers\n # if necessary\n errors = [x[0] if hasattr(x, '__len__') else x for x in errors]\n if return_all_values:\n return errors\n else:\n max_err_ind = np.argmax(errors)\n return errors[max_err_ind], mus[max_err_ind]\n\n\n@Deprecated(rb_greedy)\ndef greedy(*args, **kwargs):\n if 'samples' in kwargs:\n training_set = kwargs.pop('samples')\n kwargs['training_set'] = training_set\n return rb_greedy(*args, **kwargs)\n" ]
[ [ "numpy.sqrt", "numpy.meshgrid", "numpy.arange", "numpy.concatenate", "numpy.array", "numpy.vstack" ], [ "numpy.hstack", "numpy.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hamjam/NeMo
[ "b3484d32e1317666151f931bfa39867d88ed8658", "b3484d32e1317666151f931bfa39867d88ed8658", "b3484d32e1317666151f931bfa39867d88ed8658", "b3484d32e1317666151f931bfa39867d88ed8658", "b3484d32e1317666151f931bfa39867d88ed8658", "b3484d32e1317666151f931bfa39867d88ed8658", "b3484d32e1317666151f931bfa39867d88ed8658", "b3484d32e1317666151f931bfa39867d88ed8658", "b3484d32e1317666151f931bfa39867d88ed8658", "b3484d32e1317666151f931bfa39867d88ed8658" ]
[ "nemo/collections/nlp/models/token_classification/punctuation_capitalization_model.py", "nemo/collections/asr/parts/utils/decoder_timestamps_utils.py", "nemo/collections/asr/parts/submodules/tdnn_attention.py", "examples/asr/asr_chunked_inference/rnnt/speech_to_text_buffered_infer_rnnt.py", "nemo/collections/common/tokenizers/tabular_tokenizer.py", "examples/nlp/entity_linking/data/umls_dataset_processing.py", "nemo/collections/nlp/models/information_retrieval/bert_dpr_model.py", "nemo/collections/asr/parts/utils/speaker_utils.py", "nemo/collections/asr/parts/submodules/multi_head_attention.py", "nemo/collections/asr/parts/k2/utils.py" ]
[ "# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. 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 copy\nfrom math import ceil\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nimport numpy as np\nimport torch\nfrom omegaconf import DictConfig, OmegaConf\nfrom pytorch_lightning import Trainer\nfrom pytorch_lightning.utilities.types import EPOCH_OUTPUT\nfrom tqdm import tqdm\n\nfrom nemo.collections.common.losses import AggregatorLoss, CrossEntropyLoss\nfrom nemo.collections.common.metrics import GlobalAverageLossMetric\nfrom nemo.collections.nlp.data.token_classification.punctuation_capitalization_dataset import (\n BertPunctuationCapitalizationDataset,\n PunctuationCapitalizationEvalDataConfig,\n PunctuationCapitalizationTrainDataConfig,\n load_label_ids,\n raise_not_equal_labels_error,\n)\nfrom nemo.collections.nlp.data.token_classification.punctuation_capitalization_infer_dataset import (\n BertPunctuationCapitalizationInferDataset,\n)\nfrom nemo.collections.nlp.data.token_classification.punctuation_capitalization_tarred_dataset import (\n BertPunctuationCapitalizationTarredDataset,\n)\nfrom nemo.collections.nlp.metrics.classification_report import ClassificationReport\nfrom nemo.collections.nlp.models.nlp_model import NLPModel\nfrom nemo.collections.nlp.models.token_classification.punctuation_capitalization_config import (\n is_legacy_model_config,\n legacy_model_config_to_new_model_config,\n)\nfrom nemo.collections.nlp.modules.common import TokenClassifier\nfrom nemo.core.classes.common import PretrainedModelInfo, typecheck\nfrom nemo.core.classes.exportable import Exportable\nfrom nemo.core.neural_types import LogitsType, NeuralType\nfrom nemo.utils import logging\n\n__all__ = ['PunctuationCapitalizationModel']\n\n\nclass PunctuationCapitalizationModel(NLPModel, Exportable):\n \"\"\"\n A model for restoring punctuation and capitalization in text. The model is usually used together with ASR model\n because ASR models often return text without punctuation and capitalization.\n\n The model consists of a language model and two multilayer perceptrons (MLP) on top the language model. The first\n MLP serves for punctuation prediction and the second is for capitalization prediction. You can use only BERT-like\n HuggingFace language models (model ``forward`` method accepts ``input_ids``, ``token_types_ids``,\n ``attention_mask`` arguments). See more about model config options :ref:`here<model-config-label>`.\n\n Use method :meth:`~add_punctuation_capitalization` for model inference.\n\n For training and testing use dataset\n :class:`~nemo.collections.nlp.data.token_classification.punctuation_capitalization_dataset.BertPunctuationCapitalizationDataset`,\n for training on huge amounts of data which cannot be loaded into memory simultaneously use\n :class:`~nemo.collections.nlp.data.token_classification.punctuation_capitalization_tarred_dataset.BertPunctuationCapitalizationTarredDataset`.\n\n Args:\n cfg (:obj:`DictConfig`): a model configuration. It should follow dataclass\n :class:`~nemo.collections.nlp.models.token_classification.punctuation_capitalization_config.PunctuationCapitalizationModelConfig`\n See an example of full config in\n `nemo/examples/nlp/token_classification/conf/punctuation_capitalization_config.yaml\n <https://github.com/NVIDIA/NeMo/blob/main/examples/nlp/token_classification/conf/punctuation_capitalization_config.yaml>`_\n trainer (:obj:`pytorch_lightning.Trainer`): an instance of a PyTorch Lightning trainer\n \"\"\"\n\n @property\n def output_types(self) -> Optional[Dict[str, NeuralType]]:\n \"\"\"Neural types of a :meth:`forward` method output.\"\"\"\n return {\n \"punct_logits\": NeuralType(('B', 'T', 'C'), LogitsType()),\n \"capit_logits\": NeuralType(('B', 'T', 'C'), LogitsType()),\n }\n\n def __init__(self, cfg: DictConfig, trainer: Trainer = None) -> None:\n \"\"\"Initializes BERT Punctuation and Capitalization model.\"\"\"\n if is_legacy_model_config(cfg):\n cfg = legacy_model_config_to_new_model_config(cfg)\n\n # For structure of `self.metrics` attribute see `self._setup_metrics_dictionary` method.\n self.metrics: Optional[torch.nn.ModuleDict] = None\n self.label_ids_are_set: bool = False\n self.punct_label_ids: Optional[Dict[str, int]] = None\n self.capit_label_ids: Optional[Dict[str, int]] = None\n super().__init__(cfg=cfg, trainer=trainer)\n if not self.label_ids_are_set:\n self._set_label_ids()\n\n self.punct_classifier = TokenClassifier(\n hidden_size=self.hidden_size,\n num_classes=len(self.punct_label_ids),\n activation=cfg.punct_head.activation,\n log_softmax=False,\n dropout=cfg.punct_head.fc_dropout,\n num_layers=cfg.punct_head.num_fc_layers,\n use_transformer_init=cfg.punct_head.use_transformer_init,\n )\n\n self.capit_classifier = TokenClassifier(\n hidden_size=self.hidden_size,\n num_classes=len(self.capit_label_ids),\n activation=cfg.capit_head.activation,\n log_softmax=False,\n dropout=cfg.capit_head.fc_dropout,\n num_layers=cfg.capit_head.num_fc_layers,\n use_transformer_init=cfg.capit_head.use_transformer_init,\n )\n\n self.loss = CrossEntropyLoss(logits_ndim=3)\n self.agg_loss = AggregatorLoss(num_inputs=2)\n\n @typecheck()\n def forward(\n self, input_ids: torch.Tensor, attention_mask: torch.Tensor, token_type_ids: Optional[torch.Tensor] = None\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Executes a forward pass through the model. For more details see ``forward`` method of HuggingFace BERT-like\n (models which accept ``input_ids``, ``attention_mask``, ``token_type_ids`` arguments) models.\n\n Args:\n input_ids (:obj:`torch.Tensor`): an integer torch tensor of shape ``[Batch, Time]``. Contains encoded\n source tokens.\n attention_mask (:obj:`torch.Tensor`): a boolean torch tensor of shape ``[Batch, Time]``. Contains an\n attention mask for excluding paddings.\n token_type_ids (:obj:`torch.Tensor`): an integer torch Tensor of shape ``[Batch, Time]``. Contains an index\n of segment to which a token belongs. If ``token_type_ids`` is not ``None``, then it should be a zeros\n tensor.\n\n Returns:\n :obj:`Tuple[torch.Tensor, torch.Tensor]`: a tuple containing\n\n - ``punct_logits`` (:obj:`torch.Tensor`): a float torch tensor of shape\n ``[Batch, Time, NumPunctuationLabels]`` containing punctuation logits\n - ``capit_logits`` (:obj:`torch.Tensor`): a float torch tensor of shape\n ``[Batch, Time, NumCapitalizationLabels]`` containing capitalization logits\n \"\"\"\n hidden_states = self.bert_model(\n input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask\n )\n if isinstance(hidden_states, tuple):\n hidden_states = hidden_states[0]\n\n punct_logits = self.punct_classifier(hidden_states=hidden_states)\n capit_logits = self.capit_classifier(hidden_states=hidden_states)\n return punct_logits, capit_logits\n\n def _make_step(self, batch: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n punct_logits, capit_logits = self(\n input_ids=batch['input_ids'], token_type_ids=batch['segment_ids'], attention_mask=batch['input_mask']\n )\n\n punct_loss = self.loss(logits=punct_logits, labels=batch['punct_labels'], loss_mask=batch['loss_mask'])\n capit_loss = self.loss(logits=capit_logits, labels=batch['capit_labels'], loss_mask=batch['loss_mask'])\n loss = self.agg_loss(loss_1=punct_loss, loss_2=capit_loss)\n return loss, punct_logits, capit_logits\n\n def training_step(self, batch: Dict[str, torch.Tensor], batch_idx: int) -> Dict[str, Union[torch.Tensor, float]]:\n \"\"\"\n Lightning calls this inside the training loop with the data from the training dataloader passed in as\n ``batch``.\n\n Args:\n batch: a dictionary with following\n items:\n\n - ``'input_ids'`` (:obj:`torch.Tensor`): an integer torch tensor of shape ``[Batch, Time]`` containing\n encoded source text\n - ``'segment_ids'`` (:obj:`torch.Tensor`): a zeros integer torch tensor of shape ``[Batch, Time]``\n - ``'input_mask'`` (:obj:`torch.Tensor`): a boolean torch tensor of shape ``[Batch, Time]``. Serves as\n attention mask. should be ``False`` on padding tokens and ``True`` on other tokens.\n - ``'loss_mask'`` (:obj:`torch.Tensor`): a boolean torch tensor of shape ``[Batch, Time]``. Which token\n to compute loss on. See more details in description of parameters ``ignore_start_end`` and\n ``ignore_extra_tokens`` of a class\n :class:`~nemo.collections.nlp.data.token_classification.punctuation_capitalization_dataset.BertPunctuationCapitalizationDataset`\n - ``'punct_labels'`` (:obj:`torch.Tensor`): a ``long`` torch tensor of shape ``[Batch, Time]``.\n Contains encoded punctuation labels\n - ``'capit_labels'`` (:obj:`torch.Tensor`): a ``long`` torch tensor of shape ``[Batch, Time]``.\n Contains encoded capitalization labels\n - ``'subtokens_mask'`` (:obj:`torch.Tensor`): not required for training and can be omitted\n\n batch_idx (:obj:`int`): an index of batch. Mandatory Lightning parameter\n\n Returns:\n :obj:`Dict[str, Union[torch.Tensor, float]]`: a dictionary with 2 items:\n\n - ``'loss'`` (:obj:`torch.Tensor`): torch tensor containing mean aggregated punctuation and\n capitalization loss\n - ``'lr'`` (:obj:`float`): a float containing learning rate\n \"\"\"\n loss, _, _ = self._make_step(batch)\n lr = self._optimizer.param_groups[0]['lr']\n self.log('lr', lr, prog_bar=True)\n self.log('train_loss', loss)\n return {'loss': loss, 'lr': lr}\n\n def eval_step(self, batch: Dict[str, torch.Tensor], mode: str, dataloader_idx: int) -> Dict[str, None]:\n \"\"\"\n A method called by :meth:`validation_step` and :meth:`test_step`. Performs forward pass and updates metrics.\n\n Args:\n batch (:obj:`Dict[str, torch.Tensor]`): a dictionary with following items:\n\n - ``'input_ids'`` (:obj:`torch.Tensor`): an integer torch tensor of shape ``[Batch, Time]`` containing\n encoded source text.\n - ``'subtokens_mask'`` (:obj:`torch.Tensor`): a boolean torch tensor of shape ``[Batch, Time]``. An\n element of this item is ``True`` if corresponding token from ``'input_ids'`` element is the first\n token in some word.\n - ``'segment_ids'`` (:obj:`torch.Tensor`): a zeros integer torch tensor of shape ``[Batch, Time]``.\n - ``'input_mask'`` (:obj:`torch.Tensor`): a boolean torch tensor of shape ``[Batch, Time]``. Serves as\n attention mask. should be ``False`` on padding tokens and ``True`` on other tokens.\n - ``'loss_mask'`` (:obj:`torch.Tensor`): a boolean torch tensor of shape ``[Batch, Time]``. Which token\n to compute loss on. See more details in description of parameters ``ignore_start_end`` and\n ``ignore_extra_tokens`` of class\n :class:`~nemo.collections.nlp.data.token_classification.punctuation_capitalization_dataset.BertPunctuationCapitalizationDataset`.\n - ``'punct_labels'`` (:obj:`torch.Tensor`): a long torch tensor of shape ``[Batch, Time]``. Contains\n encoded punctuation labels.\n - ``'capit_labels'`` (:obj:`torch.Tensor`): a long torch tensor of shape ``[Batch, Time]``. Contains\n encoded capitalization labels.\n mode: either ``'validation'`` or ``'test'`` depending on caller method.\n dataloader_idx: NeMo parameter for multi dataset validation.\n\n Returns:\n :obj:`Dict[str, None]`: a dictionary containing items ``'loss'``, ``'punct_class_report'``,\n ``'capit_class_report'`` which values are ``None``. Values are ``None`` because metrics are computed using\n ``torchmetrics``.\n \"\"\"\n loss, punct_logits, capit_logits = self._make_step(batch)\n subtokens_mask = batch['subtokens_mask']\n punct_preds = torch.argmax(punct_logits, axis=-1)[subtokens_mask]\n punct_labels = batch['punct_labels'][subtokens_mask]\n capit_preds = torch.argmax(capit_logits, axis=-1)[subtokens_mask]\n capit_labels = batch['capit_labels'][subtokens_mask]\n self.metrics[mode]['loss'][dataloader_idx](\n loss=loss, num_measurements=batch['loss_mask'].sum().to(loss.device)\n )\n self.metrics[mode]['punct_class_report'][dataloader_idx](punct_preds, punct_labels)\n self.metrics[mode]['capit_class_report'][dataloader_idx](capit_preds, capit_labels)\n # torchmetrics are used for metrics computation\n return {'loss': None, 'punct_class_report': None, 'capit_class_report': None}\n\n def validation_step(\n self, batch: Dict[str, torch.Tensor], batch_idx: int, dataloader_idx: int = 0\n ) -> Dict[str, None]:\n \"\"\"\n Lightning calls this inside the validation loop with the data from the validation dataloader passed in as\n ``batch``. See more details in :meth:`eval_step`.\n\n Args:\n batch (:obj:`dict`): see :meth:`eval_step` for the ``batch`` parameter explanation\n batch_idx (:obj:`int`): an index of a batch in a dataset. A mandatory Lightning parameter\n dataloader_idx (:obj:`int`): a NeMo parameter for performing testing on multiple datasets\n\n Returns:\n :obj:`Dict[str, None]`: a dictionary containing items ``'loss'``, ``'punct_class_report'``,\n ``'capit_class_report'`` which values are ``None``. Values are ``None`` because metrics are computed using\n ``torchmetrics``.\n \"\"\"\n return self.eval_step(batch, 'val', dataloader_idx)\n\n def test_step(self, batch: Dict[str, torch.Tensor], batch_idx: int, dataloader_idx: int = 0) -> Dict[str, None]:\n \"\"\"\n Lightning calls this inside the test loop with the data from the test dataloader passed in as ``batch``.\n See more details in :meth:`eval_step`.\n\n Args:\n batch (:obj:`dict`): see :meth:`eval_step` for the ``batch`` parameter explanation\n batch_idx (:obj:`int`): an index of a batch in a dataset. A mandatory Lightning parameter\n dataloader_idx (:obj:`int`): a NeMo parameter for performing testing on multiple datasets\n\n Returns:\n :obj:`Dict[str, None]`: a dictionary containing items ``'loss'``, ``'punct_class_report'``,\n ``'capit_class_report'`` which values are ``None``. Values are ``None`` because metrics are computed using\n ``torchmetrics``.\n \"\"\"\n return self.eval_step(batch, 'test', dataloader_idx)\n\n def training_epoch_end(self, outputs: EPOCH_OUTPUT) -> None:\n \"\"\"\n Called at the end of training epoch. This method properly shuffles\n :class:`~nemo.collections.nlp.data.token_classification.punctuation_capitalization_dataset.BertPunctuationCapitalizationDataset`.\n Regular data loader shuffling only permutes batches.\n\n Args:\n outputs (:obj:`pytorch_lightning.utilities.types.EPOCH_OUTPUT`): an output of all training steps. It is a\n mandatory PyTorch Lightning parameter and it is not used in this method\n \"\"\"\n shuffle = self._cfg.train_ds.get('shuffle')\n if shuffle is None: # Encountered legacy config\n shuffle = not self.cfg.train_ds.get('use_tarred_dataset', False)\n if shuffle:\n if isinstance(self.train_dataloader().dataset, BertPunctuationCapitalizationDataset):\n self.train_dataloader().dataset.repack_batches_with_shuffle()\n\n def _multi_eval_epoch_end(self, mode: str, dataloader_idx: int) -> Dict[str, Dict[str, torch.Tensor]]:\n loss = self.metrics[mode]['loss'][dataloader_idx].compute()\n self.metrics[mode]['loss'][dataloader_idx].reset()\n\n punct_res = self.metrics[mode]['punct_class_report'][dataloader_idx].compute()\n punct_precision, punct_recall, punct_f1, punct_report = punct_res\n self.metrics[mode]['punct_class_report'][dataloader_idx].reset()\n\n capit_res = self.metrics[mode]['capit_class_report'][dataloader_idx].compute()\n capit_precision, capit_recall, capit_f1, capit_report = capit_res\n self.metrics[mode]['capit_class_report'][dataloader_idx].reset()\n log_dict = {\n 'log': {\n f'{mode}_loss': loss,\n f'{mode}_punct_precision': punct_precision,\n f'{mode}_punct_f1': punct_f1,\n f'{mode}_punct_recall': punct_recall,\n f'{mode}_capit_precision': capit_precision,\n f'{mode}_capit_f1': capit_f1,\n f'{mode}_capit_recall': capit_recall,\n }\n }\n logging.info(f'Punctuation report: {punct_report}')\n logging.info(f'Capitalization report: {capit_report}')\n return log_dict\n\n def multi_validation_epoch_end(self, outputs: Any, dataloader_idx: int = 0) -> Dict[str, Dict[str, torch.Tensor]]:\n \"\"\"\n Called at the end of validation to compute and log metrics.\n \"\"\"\n return self._multi_eval_epoch_end('val', dataloader_idx)\n\n def multi_test_epoch_end(self, outputs: Any, dataloader_idx: int = 0) -> Dict[str, Dict[str, torch.Tensor]]:\n \"\"\"\n Called at the end of model testing to compute and log metrics.\n \"\"\"\n return self._multi_eval_epoch_end('test', dataloader_idx)\n\n def update_config_after_restoring_from_checkpoint(self, **kwargs) -> None:\n \"\"\"\n Set new values for some sections of config. Useful after restoring from checkpoint for fine tuning\n and testing if config parameters of a restored checkpoint are not suitable.\n\n For ``class_labels``, ``common_dataset_parameters``, ``train_ds``, ``validation_ds``, ``test_ds``, there is\n no need to provide values for all items in an updated config section. If an item is omitted in this method\n parameter, then corresponding item in model config does not change.\n\n If the entire updated section is missing in the model config, then omitted items from this method parameters\n are set according to default values listed\n :ref:`here <run-config-label>`.\n\n .. warning::\n Parameter ``optim`` is processed in a special way. ``optim`` contents are used not for updating of\n model config, but for replacement of entire config section.\n\n If one of parameters ``train_ds``, ``validation_ds``, ``test_ds``, is provided but its value is\n ``None``, then corresponding section is replaced with ``None``.\n\n .. warning::\n You may change values of parameters related to label ids:\n\n - ``common_dataset_parameters.punct_label_ids``,\n - ``common_dataset_parameters.capit_label_ids``,\n - ``common_dataset_parameters.label_vocab_dir``,\n - ``class_labels.punct_labels_file``,\n - ``class_labels.capit_labels_file``,\n\n yet label ids in these parameters must be equal to label ids loaded from checkpoint. Otherwise,\n an error will be raised.\n\n Keyword Args:\n class_labels (:obj:`Union[DictConfig, Dict[str, str]]`): names of label id files used as label\n id dictionaries. See more in :ref:`class labels config<class-labels-config-label>`.\n common_dataset_parameters (:obj:`Union[DictConfig, Dict[str, Any]]`, `optional`): see more in\n :ref:`common dataset parameters config<common-dataset-parameters-config-label>`.\n train_ds (:obj:`Union[DictConfig, Dict[str, Any]]`, `optional`): configuration of training dataset. See\n possible options in :ref:`data config<data-config-label>`.\n validation_ds (:obj:`Union[DictConfig, Dict[str, Any]]`, `optional`): configuration of validation\n dataset. See possible options in :ref:`data config<data-config-label>`.\n test_ds (:obj:`Union[DictConfig, Dict[str, Any]]`, `optional`): configuration of test dataset. See\n possible options in :ref:`data config<data-config-label>`.\n optim (:obj:`Union[DictConfig, Dict[str, Any]]`, `optional`): optimization configuration. See possible\n options in :ref:`optimization<optimization-label>` and in `primer\n <https://github.com/NVIDIA/NeMo/blob/main/tutorials/00_NeMo_Primer.ipynb>`_ tutorial.\n \"\"\"\n allowed_keys = {'class_labels', 'common_dataset_parameters', 'train_ds', 'validation_ds', 'test_ds', 'optim'}\n unexpected_keys = set(kwargs) - allowed_keys\n if unexpected_keys:\n raise ValueError(\n f\"Found unexpected keyword arguments: {unexpected_keys}. You can use only {allowed_keys}.\"\n )\n if 'class_labels' in kwargs:\n if kwargs['class_labels'] is None:\n raise ValueError(\n f\"'class_labels' parameters is `None`, whereas you cannot remove section 'class_labels' from model \"\n f\"config.\"\n )\n self._cfg.class_labels = OmegaConf.merge(self._cfg.class_labels, OmegaConf.create(kwargs['class_labels']))\n if 'common_dataset_parameters' in kwargs:\n if kwargs['common_dataset_parameters'] is None:\n raise ValueError(\n f\"'common_dataset_parameters' item is `None`, whereas you cannot remove section\"\n f\"'common_dataset_parameters' from model config.\"\n )\n self._cfg.common_dataset_parameters = OmegaConf.merge(\n self._cfg.common_dataset_parameters, OmegaConf.create(kwargs['common_dataset_parameters'])\n )\n self._check_label_config_parameters()\n if 'train_ds' in kwargs:\n if kwargs['train_ds'] is None:\n self._cfg.train_ds = None\n else:\n if 'train_ds' in self._cfg and self._cfg.train_ds is not None:\n base = self._cfg.train_ds\n else:\n base = OmegaConf.structured(PunctuationCapitalizationTrainDataConfig)\n self._cfg.train_ds = OmegaConf.merge(base, OmegaConf.create(kwargs['train_ds']))\n if 'validation_ds' in kwargs:\n if kwargs['validation_ds'] is None:\n self._cfg.validation_ds = None\n else:\n if 'validation_ds' in self._cfg and self._cfg.validation_ds is not None:\n base = self._cfg.validation_ds\n else:\n base = OmegaConf.structured(PunctuationCapitalizationEvalDataConfig)\n self._cfg.validation_ds = OmegaConf.merge(base, OmegaConf.create(kwargs['validation_ds']))\n if 'test_ds' in kwargs:\n if kwargs['test_ds'] is None:\n self._cfg.test_ds = None\n else:\n if 'test_ds' in self._cfg and self._cfg.test_ds is not None:\n base = self._cfg.test_ds\n else:\n base = OmegaConf.structured(PunctuationCapitalizationEvalDataConfig)\n self._cfg.test_ds = OmegaConf.merge(base, OmegaConf.create(kwargs['test_ds']))\n if 'optim' in kwargs:\n self._cfg.optim = kwargs['optim']\n\n def setup_training_data(self, train_data_config: Optional[Union[Dict[str, Any], DictConfig]] = None) -> None:\n \"\"\"\n Sets up training data: creates dataset and sets data loader. If parameter ``train_data_config`` is not\n provided, then :ref:`config<model-config-label>` section ``train_ds`` will be used.\n\n Args:\n train_data_config (:obj:`Union[Dict[str, Any], DictConfig]`, `optional`): a dictionary that should contain\n only fields present in :ref:`data config<data-config-label>`.\n If some of the fields are missing, then they will be set according to\n :ref:`data config<data-config-label>` defaults. If ``train_data_config`` parameter is not set, then\n ``train_ds`` item of model config is used. Here model config is a configuration used for model\n instantiation.\n \"\"\"\n if train_data_config is not None:\n train_data_config = OmegaConf.create(train_data_config)\n train_data_config = OmegaConf.merge(\n OmegaConf.structured(PunctuationCapitalizationTrainDataConfig), train_data_config\n )\n if train_data_config is None:\n train_data_config = self._cfg.train_ds\n\n self._train_dl = self._setup_dataloader_from_config(cfg=train_data_config, train=True)\n self.punct_label_ids = self._train_dl.dataset.punct_label_ids.copy()\n self.capit_label_ids = self._train_dl.dataset.capit_label_ids.copy()\n self.label_ids_are_set = True\n if not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0:\n label_vocab_dir = self._cfg.common_dataset_parameters.label_vocab_dir\n if label_vocab_dir is None:\n punct_label_ids_file, capit_label_ids_file = self._train_dl.dataset.save_labels_and_get_file_paths(\n self._cfg.class_labels.punct_labels_file, self._cfg.class_labels.capit_labels_file\n )\n else:\n punct_label_ids_file = Path(label_vocab_dir).expanduser() / self._cfg.class_labels.punct_labels_file\n capit_label_ids_file = Path(label_vocab_dir).expanduser() / self._cfg.class_labels.capit_labels_file\n self.register_artifact('class_labels.punct_labels_file', str(punct_label_ids_file))\n self.register_artifact('class_labels.capit_labels_file', str(capit_label_ids_file))\n\n def _get_eval_metrics_kwargs(\n self,\n ) -> Tuple[\n Dict[str, bool],\n Dict[str, Union[bool, str, int, Dict[str, int]]],\n Dict[str, Union[bool, str, int, Dict[str, int]]],\n ]:\n loss_kw = {'dist_sync_on_step': False, 'take_avg_loss': True}\n punct_kw = {\n 'num_classes': len(self.punct_label_ids),\n 'label_ids': self.punct_label_ids,\n 'mode': 'macro',\n 'dist_sync_on_step': False,\n }\n capit_kw = {\n 'num_classes': len(self.capit_label_ids),\n 'label_ids': self.capit_label_ids,\n 'mode': 'macro',\n 'dist_sync_on_step': False,\n }\n return loss_kw, punct_kw, capit_kw\n\n def _setup_metrics_dictionary(self) -> None:\n eval_metrics = torch.nn.ModuleDict(\n {\n \"loss\": torch.nn.ModuleList([]),\n \"punct_class_report\": torch.nn.ModuleList([]),\n \"capit_class_report\": torch.nn.ModuleList([]),\n }\n )\n self.metrics = torch.nn.ModuleDict({\"val\": eval_metrics, \"test\": copy.deepcopy(eval_metrics)})\n\n def setup_validation_data(self, val_data_config: Optional[Union[Dict[str, Any], DictConfig]] = None) -> None:\n \"\"\"\n Sets up validation data: creates dataset and sets data loader. If parameter ``val_data_config`` is not\n provided, then ``validation_ds`` :ref:`config <model-config-label>` section will be used. Here model config is\n a configuration used for model instantiation.\n\n Args:\n val_data_config (:obj:`Union[Dict[str, Any], DictConfig]`, `optional`): a dictionary that should contain\n only fields present in data config :ref:`description<data-config-label>`.\n If some of the fields are missing, then they will be set according to data config\n :ref:`description<data-config-label>` defaults. If ``val_data_config`` parameter is not set, then\n ``validation_ds`` item of model config is used. Here model config is a configuration used for model\n instantiation.\n \"\"\"\n if val_data_config is not None:\n val_data_config = OmegaConf.create(val_data_config)\n val_data_config = OmegaConf.merge(\n OmegaConf.structured(PunctuationCapitalizationEvalDataConfig), val_data_config\n )\n if self.metrics is None:\n self._setup_metrics_dictionary()\n if val_data_config is None:\n val_data_config = self._cfg.validation_ds\n\n self._validation_dl = self._setup_dataloader_from_config(cfg=val_data_config, train=False)\n loss_kw, punct_kw, capit_kw = self._get_eval_metrics_kwargs()\n self.metrics['val']['loss'].append(GlobalAverageLossMetric(**loss_kw))\n self.metrics['val']['punct_class_report'].append(ClassificationReport(**punct_kw))\n self.metrics['val']['capit_class_report'].append(ClassificationReport(**capit_kw))\n\n def setup_test_data(self, test_data_config: Optional[Union[Dict[str, Any], DictConfig]] = None) -> None:\n \"\"\"\n Sets up test data: creates dataset and sets data loader. If parameter ``test_data_config`` is not\n provided, then ``test_ds`` config section will be used. See more about in data config\n :ref:`description <data-config-label>` and model config :ref:`description<model-config-label>`.\n\n Args:\n test_data_config (:obj:`Union[Dict[str, Any], DictConfig]`, `optional`): a dictionary that should contain\n only fields present in data config :ref:`description<data-config-label>`.\n If some of the fields are missing, then they will be set according to data config\n :ref:`description <data-config-label>` defaults. If ``test_data_config`` parameter is not set, then\n ``test_ds`` item of :ref:`model config <model-config-label>` is used. Here model config is a\n configuration used for model instantiation.\n \"\"\"\n if test_data_config is not None:\n test_data_config = OmegaConf.create(test_data_config)\n test_data_config = OmegaConf.merge(\n OmegaConf.structured(PunctuationCapitalizationEvalDataConfig), test_data_config\n )\n if self.metrics is None:\n self._setup_metrics_dictionary()\n if test_data_config is None:\n test_data_config = self._cfg.test_ds\n self._test_dl = self._setup_dataloader_from_config(cfg=test_data_config, train=False)\n loss_kw, punct_kw, capit_kw = self._get_eval_metrics_kwargs()\n self.metrics['test']['loss'].append(GlobalAverageLossMetric(**loss_kw))\n self.metrics['test']['punct_class_report'].append(ClassificationReport(**punct_kw))\n self.metrics['test']['capit_class_report'].append(ClassificationReport(**capit_kw))\n\n def _check_label_config_parameters(self) -> None:\n \"\"\"\n Checks that config items ``common_dataset_parameters.punct_label_ids`` and\n ``common_dataset_parameters.punct_label_vocab_file``,\n ``common_dataset_parameters.capit_label_ids`` and ``common_dataset_parameters.capit_label_vocab_file`` contain\n identical label ids. Of course, if any of these parameters is ``None``, then check is not performed.\n\n In addition, this method checks that ``common_dataset_parameters.pad_label`` has id ``0`` in punctuation and\n capitalization label ids.\n \"\"\"\n pli = self._cfg.common_dataset_parameters.punct_label_ids\n cli = self._cfg.common_dataset_parameters.capit_label_ids\n pad_label = self._cfg.common_dataset_parameters.pad_label\n plvf, clvf = self._extract_label_vocab_files_from_config()\n for label_ids, label_vocab_file, already_set_label_ids, label_ids_name, label_vocab_name in [\n (pli, plvf, self.punct_label_ids, 'punct_label_ids', 'punct_label_vocab_file'),\n (cli, clvf, self.capit_label_ids, 'capit_label_ids', 'capit_label_vocab_file'),\n ]:\n if label_vocab_file is not None:\n file_label_ids = load_label_ids(label_vocab_file)\n if label_ids is not None and label_vocab_file is not None:\n if label_ids != file_label_ids:\n raise_not_equal_labels_error(\n first_labels=label_ids,\n second_labels=file_label_ids,\n first_labels_desc=f\"Labels passed in config parameter \"\n f\"`model.common_dataset_parameters.{label_ids_name}`\",\n second_labels_desc=f\"Labels loaded from file {plvf} passed in config \"\n f\"parameter `model.common_dataset_parameters.{label_vocab_name}\",\n )\n if already_set_label_ids is not None:\n config_label_ids = label_ids if label_vocab_file is None else file_label_ids\n if config_label_ids is not None:\n if label_vocab_file is None:\n config_label_ids_source = (\n f\"Labels passed in config parameter `model.common_dataset_parameters.{label_ids_name}`\"\n )\n else:\n config_label_ids_source = (\n f\"Labels loaded from file {plvf} passed in config parameter \"\n f\"`model.common_dataset_parameters.{label_vocab_name}`\"\n )\n if already_set_label_ids != config_label_ids:\n raise_not_equal_labels_error(\n first_labels=config_label_ids,\n second_labels=already_set_label_ids,\n first_labels_desc=config_label_ids_source,\n second_labels_desc=f\"Labels which are already set in an attribute \"\n f\"`PunctuationCapitalizationModel.{label_ids_name}`\",\n )\n if plvf is not None:\n pli = load_label_ids(plvf)\n if clvf is not None:\n cli = load_label_ids(clvf)\n for label_ids, parameter_name in [\n (pli, 'punct_label_vocab_file' if pli is None else 'punct_label_ids'),\n (cli, 'capit_label_vocab_file' if cli is None else 'capit_label_ids'),\n ]:\n if label_ids is not None and label_ids[pad_label] != 0:\n raise ValueError(\n f\"Pad label '{pad_label}' has non zero id {label_ids[pad_label]} in \"\n f\"`model.common_dataset_parameters.{parameter_name}`.\"\n )\n\n def _extract_label_vocab_files_from_config(self) -> Tuple[Optional[Path], Optional[Path]]:\n if self._cfg.common_dataset_parameters.label_vocab_dir is None:\n if self._is_model_being_restored():\n punct_label_vocab_file = self._cfg.class_labels.punct_labels_file\n capit_label_vocab_file = self._cfg.class_labels.capit_labels_file\n else:\n punct_label_vocab_file, capit_label_vocab_file = None, None\n else:\n label_vocab_dir = Path(self._cfg.common_dataset_parameters.label_vocab_dir).expanduser()\n punct_label_vocab_file = label_vocab_dir / self._cfg.class_labels.punct_labels_file\n capit_label_vocab_file = label_vocab_dir / self._cfg.class_labels.capit_labels_file\n return punct_label_vocab_file, capit_label_vocab_file\n\n def _set_label_ids(self) -> None:\n \"\"\"\n Set model attributes ``punct_label_ids`` and ``capit_label_ids`` based on label ids passed in config\n item ``common_dataset_parameters``.\n\n This method also registers artifacts ``class_labels.punct_labels_file`` and ``class_labels.capit_labels_file``.\n\n This method is called if do not plan to infer label ids from training file with labels. If training file\n with labels is going to be used, then calling :meth:`~setup_training_data` is enough to set\n ``punct_label_ids`` and ``capit_label_ids`` and register label artifacts.\n \"\"\"\n punct_label_vocab_file, capit_label_vocab_file = self._extract_label_vocab_files_from_config()\n if punct_label_vocab_file is not None:\n punct_labels_file = self.register_artifact('class_labels.punct_labels_file', str(punct_label_vocab_file))\n if punct_labels_file is None:\n logging.warning(\n f\"The artifact `class_labels.punct_labels_file` was not found in checkpoint. Will rely on \"\n f\"`punct_label_ids` parameter\"\n )\n self.punct_label_ids = OmegaConf.to_container(self._cfg.common_dataset_parameters.punct_label_ids)\n else:\n self.punct_label_ids = load_label_ids(\n self.register_artifact('class_labels.punct_labels_file', str(punct_label_vocab_file))\n )\n elif self._cfg.common_dataset_parameters.punct_label_ids is not None:\n self.punct_label_ids = OmegaConf.to_container(self._cfg.common_dataset_parameters.punct_label_ids)\n else:\n raise ValueError(\n f\"Could not set attribute `punct_label_ids`. Config parameters \"\n f\"`model.common_dataset_parameters.punct_label_ids`, \"\n f\"`model.common_dataset_parameters.punct_label_vocab_file` are not set. Another way to set \"\n f\"`punct_label_ids` is calling method `setup_training_data`. That way punctuation label ids will be \"\n f\"inferred from training set.\"\n )\n if capit_label_vocab_file is not None:\n capit_labels_file = self.register_artifact('class_labels.capit_labels_file', str(capit_label_vocab_file))\n if capit_labels_file is None:\n logging.warning(\n f\"The artifact `class_labels.capit_labels_file` was not found in checkpoint. Will rely on \"\n f\"`capit_label_ids` parameter\"\n )\n self.capit_label_ids = OmegaConf.to_container(self._cfg.common_dataset_parameters.capit_label_ids)\n else:\n self.capit_label_ids = load_label_ids(\n self.register_artifact('class_labels.capit_labels_file', str(capit_label_vocab_file))\n )\n elif self._cfg.common_dataset_parameters.capit_label_ids is not None:\n self.capit_label_ids = OmegaConf.to_container(self._cfg.common_dataset_parameters.capit_label_ids)\n else:\n raise ValueError(\n f\"Could not set attribute `capit_label_ids`. Config parameters \"\n f\"`model.common_dataset_parameters.capit_label_ids`, \"\n f\"`model.common_dataset_parameters.capit_label_vocab_file` are not set. Another way to set \"\n f\"`capit_label_ids` is calling method `setup_training_data`. That way capitalization label ids will \"\n f\"be inferred from training set.\"\n )\n self.label_ids_are_set = True\n\n def _setup_dataloader_from_config(self, cfg: DictConfig, train: bool) -> torch.utils.data.DataLoader:\n \"\"\"\n Creates dataset and data loader according to config ``cfg``. If ``train=False`` and attributes\n ``punct_label_ids`` and ``capit_label_ids`` are not set, then this method sets the attributes and registers\n label artifacts.\n\n Args:\n cfg (:obj:`DictConfig`): a config which follows dataclass\n :class:`~nemo.collections.nlp.data.token_classification.punctuation_capitalization_dataset.PunctuationCapitalizationEvalDataConfig`\n Note that list ``ds_item`` is not supported because list ``ds_item`` is unpacked by NeMo core\n instruments\n train (:obj:`bool`): whether train data is set. If ``True``, then label ids are not set in this function\n \"\"\"\n self._check_label_config_parameters()\n if not self.label_ids_are_set and not train:\n self._set_label_ids()\n if cfg.use_tarred_dataset:\n if cfg.tar_metadata_file is None:\n raise ValueError(\n f\"If parameter `use_tarred_dataset` is `True`, then a field `tar_metadata_file` has to be a path \"\n f\"to tarred dataset metadata file, whereas `None` is given.\"\n )\n tar_metadata_file = Path(cfg.ds_item) / cfg.tar_metadata_file\n dataset = BertPunctuationCapitalizationTarredDataset(\n metadata_file=tar_metadata_file,\n tokenizer=self.tokenizer,\n pad_label=self._cfg.common_dataset_parameters.pad_label,\n ignore_extra_tokens=self._cfg.common_dataset_parameters.ignore_extra_tokens,\n ignore_start_end=self._cfg.common_dataset_parameters.ignore_start_end,\n world_size=self.world_size,\n global_rank=self.global_rank,\n shuffle_n=cfg.tar_shuffle_n,\n label_info_save_dir=cfg.label_info_save_dir,\n )\n dataset.check_for_label_consistency_with_model_config(\n self.punct_label_ids,\n self.capit_label_ids,\n self._cfg.class_labels,\n self._cfg.common_dataset_parameters,\n )\n else:\n if cfg.text_file is None or cfg.labels_file is None:\n raise ValueError(\n f\"If parameter `use_tarred_dataset` is `False`, then fields `text_file` and `labels_file` in \"\n f\"dataset config must not be `None`. Whereas `text_file={cfg.text_file}` and \"\n f\"`label_file={cfg.labels_file}`.\"\n )\n if cfg.tokens_in_batch is None:\n raise ValueError(\n f\"If `use_tarred_dataset` is `False`, then you need to provide `tokens_in_batch` parameter.\"\n )\n text_file, labels_file = Path(cfg.ds_item) / cfg.text_file, Path(cfg.ds_item) / cfg.labels_file\n if self.label_ids_are_set:\n label_kwargs = {'punct_label_ids': self.punct_label_ids, 'capit_label_ids': self.capit_label_ids}\n else:\n punct_label_vocab_file, capit_label_vocab_file = self._extract_label_vocab_files_from_config()\n label_kwargs = {\n 'punct_label_ids': self._cfg.common_dataset_parameters.punct_label_ids,\n 'capit_label_ids': self._cfg.common_dataset_parameters.capit_label_ids,\n 'punct_label_vocab_file': punct_label_vocab_file,\n 'capit_label_vocab_file': capit_label_vocab_file,\n }\n dataset = BertPunctuationCapitalizationDataset(\n tokenizer=self.tokenizer,\n text_file=text_file,\n labels_file=labels_file,\n pad_label=self._cfg.common_dataset_parameters.pad_label,\n **label_kwargs,\n max_seq_length=cfg.max_seq_length,\n ignore_extra_tokens=self._cfg.common_dataset_parameters.ignore_extra_tokens,\n ignore_start_end=self._cfg.common_dataset_parameters.ignore_start_end,\n use_cache=cfg.use_cache,\n num_samples=cfg.num_samples,\n tokens_in_batch=cfg.tokens_in_batch,\n n_jobs=cfg.n_jobs,\n verbose=cfg.verbose,\n get_label_frequencies=cfg.get_label_frequences,\n cache_dir=cfg.cache_dir,\n label_info_save_dir=cfg.label_info_save_dir,\n )\n if cfg.shuffle and cfg.use_tarred_dataset:\n logging.warning(f\"Shuffling in dataloader is not supported for tarred dataset.\")\n shuffle = False\n else:\n shuffle = cfg.shuffle\n return torch.utils.data.DataLoader(\n dataset=dataset,\n collate_fn=dataset.collate_fn,\n batch_size=1,\n shuffle=shuffle,\n num_workers=cfg.num_workers,\n pin_memory=cfg.pin_memory,\n drop_last=cfg.drop_last,\n persistent_workers=cfg.persistent_workers,\n )\n\n def _setup_infer_dataloader(\n self,\n queries: List[str],\n batch_size: int,\n max_seq_length: int,\n step: int,\n margin: int,\n dataloader_kwargs: Optional[Dict[str, Any]],\n ) -> torch.utils.data.DataLoader:\n \"\"\"\n Setup function for a infer data loader.\n\n Args:\n queries (:obj:`List[str]`): lower cased text without punctuation\n batch_size (:obj:`int`): batch size to use during inference\n max_seq_length (:obj:`int`): length of segments into which queries are split. ``max_seq_length`` includes\n ``[CLS]`` and ``[SEP]`` so every segment contains at most ``max_seq_length-2`` tokens from input a\n query.\n step (:obj:`int`): number of tokens by which a segment is offset to a previous segment. Parameter ``step``\n cannot be greater than ``max_seq_length-2``.\n margin (:obj:`int`): number of tokens near the edge of a segment which label probabilities are not used in\n final prediction computation.\n Returns:\n :obj:`torch.utils.data.DataLoader`: inference data loader\n \"\"\"\n if dataloader_kwargs is None:\n dataloader_kwargs = {}\n dataset = BertPunctuationCapitalizationInferDataset(\n tokenizer=self.tokenizer, queries=queries, max_seq_length=max_seq_length, step=step, margin=margin\n )\n return torch.utils.data.DataLoader(\n dataset=dataset,\n collate_fn=dataset.collate_fn,\n batch_size=batch_size,\n shuffle=False,\n drop_last=False,\n **dataloader_kwargs,\n )\n\n @staticmethod\n def _remove_margins(tensor: torch.Tensor, margin_size: int, keep_left: bool, keep_right: bool) -> torch.Tensor:\n tensor = tensor.detach().clone()\n if not keep_left:\n tensor = tensor[margin_size + 1 :] # remove left margin and CLS token\n if not keep_right:\n tensor = tensor[: tensor.shape[0] - margin_size - 1] # remove right margin and SEP token\n return tensor\n\n def _transform_logit_to_prob_and_remove_margins_and_extract_word_probs(\n self,\n punct_logits: torch.Tensor,\n capit_logits: torch.Tensor,\n subtokens_mask: torch.Tensor,\n start_word_ids: Tuple[int],\n margin: int,\n is_first: Tuple[bool],\n is_last: Tuple[bool],\n ) -> Tuple[List[np.ndarray], List[np.ndarray], List[int]]:\n \"\"\"\n Applies softmax to get punctuation and capitalization probabilities, applies ``subtokens_mask`` to extract\n probabilities for words from probabilities for tokens, removes ``margin`` probabilities near edges of a segment.\n Left margin of the first segment in a query and right margin of the last segment in a query are not removed.\n Calculates new ``start_word_ids`` taking into the account the margins. If the left margin of a segment is\n removed corresponding start word index is increased by number of words (number of nonzero values in\n corresponding ``subtokens_mask``) in the margin.\n\n Args:\n punct_logits: a float tensor of shape ``[batch_size, segment_length, number_of_punctuation_labels]``\n capit_logits: a float tensor of shape ``[batch_size, segment_length, number_of_capitalization_labels]``\n subtokens_mask: a float tensor of shape ``[batch_size, segment_length]``\n start_word_ids: indices of segment first words in a query\n margin: number of tokens near edges of a segment which probabilities are discarded\n is_first: is segment the first segment in a query\n is_last: is segment the last segment in a query\n Returns:\n b_punct_probs: list containing ``batch_size`` numpy arrays. The numpy arrays have shapes\n ``[number_of_word_in_this_segment, number_of_punctuation_labels]``. Word punctuation probabilities for\n segments in the batch.\n b_capit_probs: list containing ``batch_size`` numpy arrays. The numpy arrays have shapes\n ``[number_of_word_in_this_segment, number_of_capitalization_labels]``. Word capitalization\n probabilities for segments in the batch.\n new_start_word_ids: indices of segment first words in a query after margin removal\n \"\"\"\n new_start_word_ids = list(start_word_ids)\n subtokens_mask = subtokens_mask > 0.5\n b_punct_probs, b_capit_probs = [], []\n for i, (first, last, pl, cl, stm) in enumerate(\n zip(is_first, is_last, punct_logits, capit_logits, subtokens_mask)\n ):\n if not first:\n new_start_word_ids[i] += torch.count_nonzero(stm[: margin + 1]).numpy() # + 1 is for [CLS] token\n stm = self._remove_margins(stm, margin, keep_left=first, keep_right=last)\n for b_probs, logits in [(b_punct_probs, pl), (b_capit_probs, cl)]:\n p = torch.nn.functional.softmax(\n self._remove_margins(logits, margin, keep_left=first, keep_right=last)[stm], dim=-1,\n )\n b_probs.append(p.detach().cpu().numpy())\n return b_punct_probs, b_capit_probs, new_start_word_ids\n\n @staticmethod\n def _move_acc_probs_to_token_preds(\n pred: List[int], acc_prob: np.ndarray, number_of_probs_to_move: int\n ) -> Tuple[List[int], np.ndarray]:\n \"\"\"\n ``number_of_probs_to_move`` rows in the beginning are removed from ``acc_prob``. From every remove row the label\n with the largest probability is selected and appended to ``pred``.\n Args:\n pred: list with ready label indices for a query\n acc_prob: numpy array of shape ``[number_of_words_for_which_probabilities_are_accumulated, number_of_labels]``\n number_of_probs_to_move: int\n Returns:\n pred: list with ready label indices for a query\n acc_prob: numpy array of shape\n ``[number_of_words_for_which_probabilities_are_accumulated - number_of_probs_to_move, number_of_labels]``\n \"\"\"\n if number_of_probs_to_move > acc_prob.shape[0]:\n raise ValueError(\n f\"Not enough accumulated probabilities. Number_of_probs_to_move={number_of_probs_to_move} \"\n f\"acc_prob.shape={acc_prob.shape}\"\n )\n if number_of_probs_to_move > 0:\n pred = pred + list(np.argmax(acc_prob[:number_of_probs_to_move], axis=-1))\n acc_prob = acc_prob[number_of_probs_to_move:]\n return pred, acc_prob\n\n @staticmethod\n def _update_accumulated_probabilities(acc_prob: np.ndarray, update: np.ndarray) -> np.ndarray:\n \"\"\"\n Args:\n acc_prob: numpy array of shape ``[A, L]``\n update: numpy array of shape ``[A + N, L]``\n Returns:\n numpy array of shape ``[A + N, L]``\n \"\"\"\n acc_prob = np.concatenate([acc_prob * update[: acc_prob.shape[0]], update[acc_prob.shape[0] :]], axis=0)\n return acc_prob\n\n def _apply_punct_capit_predictions(self, query: str, punct_preds: List[int], capit_preds: List[int]) -> str:\n \"\"\"\n Restores punctuation and capitalization in ``query``.\n Args:\n query: a string without punctuation and capitalization\n punct_preds: ids of predicted punctuation labels\n capit_preds: ids of predicted capitalization labels\n Returns:\n a query with restored punctuation and capitalization\n \"\"\"\n query = query.strip().split()\n assert len(query) == len(\n punct_preds\n ), f\"len(query)={len(query)} len(punct_preds)={len(punct_preds)}, query[:30]={query[:30]}\"\n assert len(query) == len(\n capit_preds\n ), f\"len(query)={len(query)} len(capit_preds)={len(capit_preds)}, query[:30]={query[:30]}\"\n punct_ids_to_labels = {v: k for k, v in self.punct_label_ids.items()}\n capit_ids_to_labels = {v: k for k, v in self.capit_label_ids.items()}\n query_with_punct_and_capit = ''\n for j, word in enumerate(query):\n punct_label = punct_ids_to_labels[punct_preds[j]]\n capit_label = capit_ids_to_labels[capit_preds[j]]\n\n if capit_label != self._cfg.common_dataset_parameters.pad_label:\n word = word.capitalize()\n query_with_punct_and_capit += word\n if punct_label != self._cfg.common_dataset_parameters.pad_label:\n query_with_punct_and_capit += punct_label\n query_with_punct_and_capit += ' '\n return query_with_punct_and_capit[:-1]\n\n def _get_labels(self, punct_preds: List[int], capit_preds: List[int]) -> str:\n \"\"\"\n Returns punctuation and capitalization labels in NeMo format for encoded punctuation ``punct_preds``\n and ``capit_preds`` labels (see https://docs.nvidia.com/deeplearning/nemo/\n user-guide/docs/en/main/nlp/punctuation_and_capitalization.html#nemo-data-format).\n Args:\n punct_preds: ids of predicted punctuation labels\n capit_preds: ids of predicted capitalization labels\n Returns:\n labels in NeMo format\n \"\"\"\n assert len(capit_preds) == len(\n punct_preds\n ), f\"len(capit_preds)={len(capit_preds)} len(punct_preds)={len(punct_preds)}\"\n punct_ids_to_labels = {v: k for k, v in self.punct_label_ids.items()}\n capit_ids_to_labels = {v: k for k, v in self.capit_label_ids.items()}\n result = ''\n for capit_label, punct_label in zip(capit_preds, punct_preds):\n punct_label = punct_ids_to_labels[punct_label]\n capit_label = capit_ids_to_labels[capit_label]\n result += punct_label + capit_label + ' '\n return result[:-1]\n\n def add_punctuation_capitalization(\n self,\n queries: List[str],\n batch_size: int = None,\n max_seq_length: int = 64,\n step: int = 8,\n margin: int = 16,\n return_labels: bool = False,\n dataloader_kwargs: Dict[str, Any] = None,\n ) -> List[str]:\n \"\"\"\n Adds punctuation and capitalization to the queries. Use this method for inference.\n\n Parameters ``max_seq_length``, ``step``, ``margin`` are for controlling the way queries are split into segments\n which are processed by the model. Parameter ``max_seq_length`` is a length of a segment after tokenization\n including special tokens [CLS] in the beginning and [SEP] in the end of a segment. Parameter ``step`` is a\n shift between consequent segments. Parameter ``margin`` is used to exclude negative effect of subtokens near\n borders of segments which have only one side context.\n\n If segments overlap, probabilities of overlapping predictions are multiplied and then the label with\n corresponding to the maximum probability is selected.\n\n Args:\n queries (:obj:`List[str]`): lower cased text without punctuation.\n batch_size (:obj:`List[str]`, `optional`): batch size to use during inference. If ``batch_size`` parameter\n is not provided, then it will be equal to length of ``queries`` list.\n max_seq_length (:obj:`int`, `optional`, defaults to :obj:`64`): maximum sequence length of a segment after\n tokenization including :code:`[CLS]` and :code:`[SEP]` tokens.\n step (:obj:`int`, `optional`, defaults to :obj:`8`): relative shift of consequent segments into which long\n queries are split. Long queries are split into segments which can overlap. Parameter ``step`` controls\n such overlapping. Imagine that queries are tokenized into characters, ``max_seq_length=5``, and\n ``step=2``. In such case, query ``\"hello\"`` is tokenized into segments\n ``[['[CLS]', 'h', 'e', 'l', '[SEP]'], ['[CLS]', 'l', 'l', 'o', '[SEP]']]``.\n margin (:obj:`int`, `optional`, defaults to :obj:`16`): number of subtokens in the beginning and the end of\n segments which are not used for prediction computation. The first segment does not have left margin and\n the last segment does not have right margin. For example, if an input sequence is tokenized into\n characters, ``max_seq_length=5``, ``step=1``, and ``margin=1``, then query ``\"hello\"`` will be\n tokenized into segments ``[['[CLS]', 'h', 'e', 'l', '[SEP]'], ['[CLS]', 'e', 'l', 'l', '[SEP]'],\n ['[CLS]', 'l', 'l', 'o', '[SEP]']]``. These segments are passed to the model. Before final predictions\n computation, margins are removed. In the next list, subtokens which logits are not used for final\n predictions computation are marked with asterisk: ``[['[CLS]'*, 'h', 'e', 'l'*, '[SEP]'*],\n ['[CLS]'*, 'e'*, 'l', 'l'*, '[SEP]'*], ['[CLS]'*, 'l'*, 'l', 'o', '[SEP]'*]]``.\n return_labels (:obj:`bool`, `optional`, defaults to :obj:`False`): whether to return labels in NeMo format\n (see :ref:`nlp/punctuation_and_capitalization/NeMo Data Format`) instead of queries with restored\n punctuation and capitalization.\n dataloader_kwargs (:obj:`Dict[str, Any]`, `optional`): an optional dictionary with parameters of PyTorch\n data loader. May include keys: ``'num_workers'``, ``'pin_memory'``, ``'worker_init_fn'``,\n ``'prefetch_factor'``, ``'persistent_workers'``.\n Returns:\n :obj:`List[str]`: a list of queries with restored capitalization and punctuation if\n ``return_labels=False``, else a list of punctuation and capitalization labels strings for all queries\n \"\"\"\n if len(queries) == 0:\n return []\n if batch_size is None:\n batch_size = len(queries)\n logging.info(f'Using batch size {batch_size} for inference')\n result: List[str] = []\n mode = self.training\n try:\n self.eval()\n infer_datalayer = self._setup_infer_dataloader(\n queries, batch_size, max_seq_length, step, margin, dataloader_kwargs\n )\n # Predicted labels for queries. List of labels for every query\n all_punct_preds: List[List[int]] = [[] for _ in queries]\n all_capit_preds: List[List[int]] = [[] for _ in queries]\n # Accumulated probabilities (or product of probabilities acquired from different segments) of punctuation\n # and capitalization. Probabilities for words in a query are extracted using `subtokens_mask`. Probabilities\n # for newly processed words are appended to the accumulated probabilities. If probabilities for a word are\n # already present in `acc_probs`, old probabilities are replaced with a product of old probabilities\n # and probabilities acquired from new segment. Segments are processed in an order they appear in an\n # input query. When all segments with a word are processed, a label with the highest probability\n # (or product of probabilities) is chosen and appended to an appropriate list in `all_preds`. After adding\n # prediction to `all_preds`, probabilities for a word are removed from `acc_probs`.\n acc_punct_probs: List[Optional[np.ndarray]] = [None for _ in queries]\n acc_capit_probs: List[Optional[np.ndarray]] = [None for _ in queries]\n d = self.device\n for batch_i, batch in tqdm(\n enumerate(infer_datalayer), total=ceil(len(infer_datalayer.dataset) / batch_size), unit=\"batch\"\n ):\n inp_ids, inp_type_ids, inp_mask, subtokens_mask, start_word_ids, query_ids, is_first, is_last = batch\n punct_logits, capit_logits = self.forward(\n input_ids=inp_ids.to(d), token_type_ids=inp_type_ids.to(d), attention_mask=inp_mask.to(d),\n )\n _res = self._transform_logit_to_prob_and_remove_margins_and_extract_word_probs(\n punct_logits, capit_logits, subtokens_mask, start_word_ids, margin, is_first, is_last\n )\n punct_probs, capit_probs, start_word_ids = _res\n for i, (q_i, start_word_id, bpp_i, bcp_i) in enumerate(\n zip(query_ids, start_word_ids, punct_probs, capit_probs)\n ):\n for all_preds, acc_probs, b_probs_i in [\n (all_punct_preds, acc_punct_probs, bpp_i),\n (all_capit_preds, acc_capit_probs, bcp_i),\n ]:\n if acc_probs[q_i] is None:\n acc_probs[q_i] = b_probs_i\n else:\n all_preds[q_i], acc_probs[q_i] = self._move_acc_probs_to_token_preds(\n all_preds[q_i], acc_probs[q_i], start_word_id - len(all_preds[q_i]),\n )\n acc_probs[q_i] = self._update_accumulated_probabilities(acc_probs[q_i], b_probs_i)\n for all_preds, acc_probs in [(all_punct_preds, acc_punct_probs), (all_capit_preds, acc_capit_probs)]:\n for q_i, (pred, prob) in enumerate(zip(all_preds, acc_probs)):\n if prob is not None:\n all_preds[q_i], acc_probs[q_i] = self._move_acc_probs_to_token_preds(pred, prob, len(prob))\n for i, query in enumerate(queries):\n result.append(\n self._get_labels(all_punct_preds[i], all_capit_preds[i])\n if return_labels\n else self._apply_punct_capit_predictions(query, all_punct_preds[i], all_capit_preds[i])\n )\n finally:\n # set mode back to its original value\n self.train(mode=mode)\n return result\n\n @classmethod\n def list_available_models(cls) -> List[PretrainedModelInfo]:\n \"\"\"\n This method returns a list of pre-trained models which can be instantiated directly from NVIDIA's NGC cloud.\n\n Returns:\n :obj:`List[PretrainedModelInfo]`: a list of available pre-trained models.\n \"\"\"\n result = [\n PretrainedModelInfo(\n pretrained_model_name=\"punctuation_en_bert\",\n location=\"https://api.ngc.nvidia.com/v2/models/nvidia/nemo/punctuation_en_bert/versions/1.0.0rc1/\"\n \"files/punctuation_en_bert.nemo\",\n description=\"The model was trained with NeMo BERT base uncased checkpoint on a subset of data from \"\n \"the following sources: Tatoeba sentences, books from Project Gutenberg, Fisher transcripts.\",\n ),\n PretrainedModelInfo(\n pretrained_model_name=\"punctuation_en_distilbert\",\n location=\"https://api.ngc.nvidia.com/v2/models/nvidia/nemo/punctuation_en_distilbert/versions/\"\n \"1.0.0rc1/files/punctuation_en_distilbert.nemo\",\n description=\"The model was trained with DiltilBERT base uncased checkpoint from HuggingFace on a \"\n \"subset of data from the following sources: Tatoeba sentences, books from Project Gutenberg, \"\n \"Fisher transcripts.\",\n ),\n ]\n return result\n\n @property\n def output_module(self):\n return self\n", "# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport copy\nimport math\nfrom typing import Dict, List, Tuple, Type, Union\n\nimport librosa\nimport numpy as np\nimport soundfile as sf\nimport torch\nfrom omegaconf import OmegaConf\n\nimport nemo.collections.asr as nemo_asr\nfrom nemo.collections.asr.metrics.wer import WER\nfrom nemo.collections.asr.metrics.wer_bpe import WERBPE\nfrom nemo.collections.asr.models import EncDecCTCModel, EncDecCTCModelBPE\nfrom nemo.collections.asr.parts.utils.speaker_utils import audio_rttm_map, get_uniqname_from_filepath\nfrom nemo.collections.asr.parts.utils.streaming_utils import AudioFeatureIterator, FrameBatchASR\nfrom nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec\nfrom nemo.utils import logging\n\n__all__ = ['ASR_TIMESTAMPS']\n\ntry:\n from pyctcdecode import build_ctcdecoder\n\n PYCTCDECODE = True\nexcept ImportError:\n PYCTCDECODE = False\n\n\ndef if_none_get_default(param, default_value):\n return (param, default_value)[param is None]\n\n\nclass WERBPE_TS(WERBPE):\n \"\"\"\n This is WERBPE_TS class that is modified for generating word_timestamps with logits.\n The functions in WER class is modified to save the word_timestamps whenever BPE token\n is being saved into a list.\n This class is designed to support ASR models based on CTC and BPE.\n Please refer to the definition of WERBPE class for more information.\n \"\"\"\n\n def __init__(\n self,\n tokenizer: TokenizerSpec,\n batch_dim_index=0,\n use_cer=False,\n ctc_decode=True,\n log_prediction=True,\n dist_sync_on_step=False,\n ):\n\n super().__init__(tokenizer, batch_dim_index, use_cer, ctc_decode, log_prediction, dist_sync_on_step)\n\n def ctc_decoder_predictions_tensor_with_ts(\n self, time_stride, predictions: torch.Tensor, predictions_len: torch.Tensor = None\n ) -> List[str]:\n hypotheses, timestamps, word_timestamps = [], [], []\n # '⁇' string should be removed since it causes error during string split.\n unk = '⁇'\n prediction_cpu_tensor = predictions.long().cpu()\n # iterate over batch\n self.time_stride = time_stride\n for ind in range(prediction_cpu_tensor.shape[self.batch_dim_index]):\n prediction = prediction_cpu_tensor[ind].detach().numpy().tolist()\n if predictions_len is not None:\n prediction = prediction[: predictions_len[ind]]\n # CTC decoding procedure\n decoded_prediction, char_ts, timestamp_list = [], [], []\n previous = self.blank_id\n for pdx, p in enumerate(prediction):\n if (p != previous or previous == self.blank_id) and p != self.blank_id:\n decoded_prediction.append(p)\n char_ts.append(round(pdx * self.time_stride, 2))\n timestamp_list.append(round(pdx * self.time_stride, 2))\n\n previous = p\n\n hypothesis = self.decode_tokens_to_str_with_ts(decoded_prediction)\n hypothesis = hypothesis.replace(unk, '')\n word_ts = self.get_ts_from_decoded_prediction(decoded_prediction, hypothesis, char_ts)\n\n hypotheses.append(hypothesis)\n timestamps.append(timestamp_list)\n word_timestamps.append(word_ts)\n return hypotheses, timestamps, word_timestamps\n\n def decode_tokens_to_str_with_ts(self, tokens: List[int]) -> str:\n hypothesis = self.tokenizer.ids_to_text(tokens)\n return hypothesis\n\n def decode_ids_to_tokens_with_ts(self, tokens: List[int]) -> List[str]:\n token_list = self.tokenizer.ids_to_tokens(tokens)\n return token_list\n\n def get_ts_from_decoded_prediction(self, decoded_prediction: List[str], hypothesis: List[str], char_ts: List[str]):\n decoded_char_list = self.tokenizer.ids_to_tokens(decoded_prediction)\n stt_idx, end_idx = 0, len(decoded_char_list) - 1\n stt_ch_idx, end_ch_idx = 0, 0\n space = '▁'\n word_ts, word_seq = [], []\n word_open_flag = False\n for idx, ch in enumerate(decoded_char_list):\n if idx != end_idx and (space == ch and space in decoded_char_list[idx + 1]):\n continue\n\n if (idx == stt_idx or space == decoded_char_list[idx - 1] or (space in ch and len(ch) > 1)) and (\n ch != space\n ):\n _stt = char_ts[idx]\n stt_ch_idx = idx\n word_open_flag = True\n\n if word_open_flag and ch != space and (idx == end_idx or space in decoded_char_list[idx + 1]):\n _end = round(char_ts[idx] + self.time_stride, 2)\n end_ch_idx = idx\n word_open_flag = False\n word_ts.append([_stt, _end])\n stitched_word = ''.join(decoded_char_list[stt_ch_idx : end_ch_idx + 1]).replace(space, '')\n word_seq.append(stitched_word)\n assert len(word_ts) == len(hypothesis.split()), \"Hypothesis does not match word time stamp.\"\n return word_ts\n\n\nclass WER_TS(WER):\n \"\"\"\n This is WER class that is modified for generating timestamps with logits.\n The functions in WER class is modified to save the timestamps whenever character\n is being saved into a list.\n This class is designed to support ASR models based on CTC and Character-level tokens.\n Please refer to the definition of WER class for more information.\n \"\"\"\n\n def __init__(\n self,\n vocabulary,\n batch_dim_index=0,\n use_cer=False,\n ctc_decode=True,\n log_prediction=True,\n dist_sync_on_step=False,\n ):\n super().__init__(vocabulary, batch_dim_index, use_cer, ctc_decode, log_prediction, dist_sync_on_step)\n\n def decode_tokens_to_str_with_ts(self, tokens: List[int], timestamps: List[int]) -> str:\n \"\"\"\n Take frame-level tokens and timestamp list and collect the timestamps for\n start and end of each word.\n \"\"\"\n token_list, timestamp_list = self.decode_ids_to_tokens_with_ts(tokens, timestamps)\n hypothesis = ''.join(self.decode_ids_to_tokens(tokens))\n return hypothesis, timestamp_list\n\n def decode_ids_to_tokens_with_ts(self, tokens: List[int], timestamps: List[int]) -> List[str]:\n token_list, timestamp_list = [], []\n for i, c in enumerate(tokens):\n if c != self.blank_id:\n token_list.append(self.labels_map[c])\n timestamp_list.append(timestamps[i])\n return token_list, timestamp_list\n\n def ctc_decoder_predictions_tensor_with_ts(\n self, predictions: torch.Tensor, predictions_len: torch.Tensor = None,\n ) -> List[str]:\n \"\"\"\n A shortened version of the original function ctc_decoder_predictions_tensor().\n Replaced decode_tokens_to_str() function with decode_tokens_to_str_with_ts().\n \"\"\"\n hypotheses, timestamps = [], []\n prediction_cpu_tensor = predictions.long().cpu()\n for ind in range(prediction_cpu_tensor.shape[self.batch_dim_index]):\n prediction = prediction_cpu_tensor[ind].detach().numpy().tolist()\n if predictions_len is not None:\n prediction = prediction[: predictions_len[ind]]\n\n # CTC decoding procedure with timestamps\n decoded_prediction, decoded_timing_list = [], []\n previous = self.blank_id\n for pdx, p in enumerate(prediction):\n if (p != previous or previous == self.blank_id) and p != self.blank_id:\n decoded_prediction.append(p)\n decoded_timing_list.append(pdx)\n previous = p\n\n text, timestamp_list = self.decode_tokens_to_str_with_ts(decoded_prediction, decoded_timing_list)\n hypotheses.append(text)\n timestamps.append(timestamp_list)\n\n return hypotheses, timestamps\n\n\ndef get_wer_feat_logit(audio_file_path, asr, frame_len, tokens_per_chunk, delay, model_stride_in_secs):\n \"\"\"\n Create a preprocessor to convert audio samples into raw features,\n Normalization will be done per buffer in frame_bufferer.\n \"\"\"\n asr.reset()\n asr.read_audio_file_and_return(audio_file_path, delay, model_stride_in_secs)\n hyp, tokens, log_prob = asr.transcribe_with_ts(tokens_per_chunk, delay)\n return hyp, tokens, log_prob\n\n\ndef get_samples(audio_file, target_sr=16000):\n \"\"\"\n Read the samples from the given audio_file path.\n \"\"\"\n with sf.SoundFile(audio_file, 'r') as f:\n dtype = 'int16'\n sample_rate = f.samplerate\n samples = f.read(dtype=dtype)\n if sample_rate != target_sr:\n samples = librosa.core.resample(samples, sample_rate, target_sr)\n samples = samples.astype('float32') / 32768\n samples = samples.transpose()\n del f\n return samples\n\n\nclass FrameBatchASR_Logits(FrameBatchASR):\n \"\"\"\n A class for streaming frame-based ASR.\n Inherits from FrameBatchASR and adds new capability of returning the logit output.\n Please refer to FrameBatchASR for more detailed information.\n \"\"\"\n\n def __init__(\n self,\n asr_model: Type[EncDecCTCModelBPE],\n frame_len: float = 1.6,\n total_buffer: float = 4.0,\n batch_size: int = 4,\n ):\n super().__init__(asr_model, frame_len, total_buffer, batch_size)\n self.all_logprobs = []\n\n def clear_buffer(self):\n self.all_logprobs = []\n self.all_preds = []\n\n def read_audio_file_and_return(self, audio_filepath: str, delay: float, model_stride_in_secs: float):\n samples = get_samples(audio_filepath)\n samples = np.pad(samples, (0, int(delay * model_stride_in_secs * self.asr_model._cfg.sample_rate)))\n frame_reader = AudioFeatureIterator(samples, self.frame_len, self.raw_preprocessor, self.asr_model.device)\n self.set_frame_reader(frame_reader)\n\n @torch.no_grad()\n def _get_batch_preds(self):\n device = self.asr_model.device\n for batch in iter(self.data_loader):\n\n feat_signal, feat_signal_len = batch\n feat_signal, feat_signal_len = feat_signal.to(device), feat_signal_len.to(device)\n log_probs, encoded_len, predictions = self.asr_model(\n processed_signal=feat_signal, processed_signal_length=feat_signal_len\n )\n preds = torch.unbind(predictions)\n for pred in preds:\n self.all_preds.append(pred.cpu().numpy())\n log_probs_tup = torch.unbind(log_probs)\n for log_prob in log_probs_tup:\n self.all_logprobs.append(log_prob)\n del encoded_len\n del predictions\n\n def transcribe_with_ts(\n self, tokens_per_chunk: int, delay: int,\n ):\n self.infer_logits()\n self.unmerged = []\n self.part_logprobs = []\n for idx, pred in enumerate(self.all_preds):\n decoded = pred.tolist()\n _stt, _end = len(decoded) - 1 - delay, len(decoded) - 1 - delay + tokens_per_chunk\n self.unmerged += decoded[len(decoded) - 1 - delay : len(decoded) - 1 - delay + tokens_per_chunk]\n self.part_logprobs.append(self.all_logprobs[idx][_stt:_end, :])\n self.unmerged_logprobs = torch.cat(self.part_logprobs, 0)\n assert (\n len(self.unmerged) == self.unmerged_logprobs.shape[0]\n ), \"Unmerged decoded result and log prob lengths are different.\"\n return self.greedy_merge(self.unmerged), self.unmerged, self.unmerged_logprobs\n\n\nclass ASR_TIMESTAMPS:\n \"\"\"\n A class designed for extracting word timestamps while the ASR decoding process.\n This class contains a few setups for a slew of NeMo ASR models such as QuartzNet, CitriNet and ConformerCTC models.\n \"\"\"\n\n def __init__(self, **cfg_diarizer):\n self.manifest_filepath = cfg_diarizer['manifest_filepath']\n self.params = cfg_diarizer['asr']['parameters']\n self.ctc_decoder_params = cfg_diarizer['asr']['ctc_decoder_parameters']\n self.ASR_model_name = cfg_diarizer['asr']['model_path']\n self.nonspeech_threshold = self.params['asr_based_vad_threshold']\n self.root_path = None\n self.run_ASR = None\n self.encdec_class = None\n self.AUDIO_RTTM_MAP = audio_rttm_map(self.manifest_filepath)\n self.audio_file_list = [value['audio_filepath'] for _, value in self.AUDIO_RTTM_MAP.items()]\n\n def set_asr_model(self):\n \"\"\"\n Initialize the parameters for the given ASR model.\n Currently, the following NGC models are supported:\n\n stt_en_quartznet15x5,\n stt_en_citrinet*,\n stt_en_conformer_ctc*\n\n To assign a proper decoding function for generating timestamp output,\n the name of .nemo file should include the architecture name such as:\n 'quartznet', 'conformer', and 'citrinet'.\n\n decoder_delay_in_sec is the amount of delay that is compensated during the word timestamp extraction.\n word_ts_anchor_offset is the reference point for a word and used for matching the word with diarization labels.\n Each ASR model has a different optimal decoder delay and word timestamp anchor offset.\n To obtain an optimized diarization result with ASR, decoder_delay_in_sec and word_ts_anchor_offset\n need to be searched on a development set.\n \"\"\"\n if 'quartznet' in self.ASR_model_name.lower():\n self.run_ASR = self.run_ASR_QuartzNet_CTC\n self.encdec_class = EncDecCTCModel\n self.decoder_delay_in_sec = if_none_get_default(self.params['decoder_delay_in_sec'], 0.04)\n self.word_ts_anchor_offset = if_none_get_default(self.params['word_ts_anchor_offset'], 0.12)\n self.asr_batch_size = if_none_get_default(self.params['asr_batch_size'], 4)\n self.model_stride_in_secs = 0.02\n\n elif 'conformer' in self.ASR_model_name.lower():\n self.run_ASR = self.run_ASR_BPE_CTC\n self.encdec_class = EncDecCTCModelBPE\n self.decoder_delay_in_sec = if_none_get_default(self.params['decoder_delay_in_sec'], 0.08)\n self.word_ts_anchor_offset = if_none_get_default(self.params['word_ts_anchor_offset'], 0.12)\n self.asr_batch_size = if_none_get_default(self.params['asr_batch_size'], 16)\n self.model_stride_in_secs = 0.04\n\n # Conformer requires buffered inference and the parameters for buffered processing.\n self.chunk_len_in_sec = 5\n self.total_buffer_in_secs = 25\n\n elif 'citrinet' in self.ASR_model_name.lower():\n self.run_ASR = self.run_ASR_CitriNet_CTC\n self.encdec_class = EncDecCTCModelBPE\n self.decoder_delay_in_sec = if_none_get_default(self.params['decoder_delay_in_sec'], 0.16)\n self.word_ts_anchor_offset = if_none_get_default(self.params['word_ts_anchor_offset'], 0.2)\n self.asr_batch_size = if_none_get_default(self.params['asr_batch_size'], 4)\n self.model_stride_in_secs = 0.08\n\n else:\n raise ValueError(f\"Cannot find the ASR model class for: {self.params['self.ASR_model_name']}\")\n\n if self.ASR_model_name.endswith('.nemo'):\n asr_model = self.encdec_class.restore_from(restore_path=self.ASR_model_name)\n else:\n asr_model = self.encdec_class.from_pretrained(model_name=self.ASR_model_name, strict=False)\n\n if self.ctc_decoder_params['pretrained_language_model']:\n if not PYCTCDECODE:\n raise ImportError(\n 'LM for beam search decoding is provided but pyctcdecode is not installed. Install pyctcdecode using PyPI: pip install pyctcdecode'\n )\n self.beam_search_decoder = self.load_LM_for_CTC_decoder(asr_model)\n else:\n self.beam_search_decoder = None\n\n asr_model.eval()\n return asr_model\n\n def load_LM_for_CTC_decoder(self, asr_model: Type[Union[EncDecCTCModel, EncDecCTCModelBPE]]):\n \"\"\"\n Load a language model for CTC decoder (pyctcdecode).\n Note that only EncDecCTCModel and EncDecCTCModelBPE models can use pyctcdecode.\n \"\"\"\n kenlm_model = self.ctc_decoder_params['pretrained_language_model']\n logging.info(f\"Loading language model : {self.ctc_decoder_params['pretrained_language_model']}\")\n\n if 'EncDecCTCModel' in str(type(asr_model)):\n labels = asr_model.decoder.vocabulary\n elif 'EncDecCTCModelBPE' in str(type(asr_model)):\n vocab = asr_model.tokenizer.tokenizer.get_vocab()\n labels = list(vocab.keys())\n labels[0] = \"<unk>\"\n else:\n raise ValueError(f\"Cannot find a vocabulary or tokenizer for: {self.params['self.ASR_model_name']}\")\n\n decoder = build_ctcdecoder(\n labels, kenlm_model, alpha=self.ctc_decoder_params['alpha'], beta=self.ctc_decoder_params['beta']\n )\n return decoder\n\n def run_ASR_QuartzNet_CTC(self, asr_model: Type[EncDecCTCModel]) -> Tuple[Dict, Dict]:\n \"\"\"\n Launch QuartzNet ASR model and collect logit, timestamps and text output.\n\n Args:\n asr_model (class):\n The loaded NeMo ASR model.\n\n Returns:\n words_dict (dict):\n Dictionary of the sequence of words from hypothesis.\n word_ts_dict (dict):\n Dictionary of the time-stamps of words.\n \"\"\"\n words_dict, word_ts_dict = {}, {}\n\n wer_ts = WER_TS(\n vocabulary=asr_model.decoder.vocabulary,\n batch_dim_index=0,\n use_cer=asr_model._cfg.get('use_cer', False),\n ctc_decode=True,\n dist_sync_on_step=True,\n log_prediction=asr_model._cfg.get(\"log_prediction\", False),\n )\n\n with torch.cuda.amp.autocast():\n transcript_logits_list = asr_model.transcribe(\n self.audio_file_list, batch_size=self.asr_batch_size, logprobs=True\n )\n for idx, logit_np in enumerate(transcript_logits_list):\n uniq_id = get_uniqname_from_filepath(self.audio_file_list[idx])\n if self.beam_search_decoder:\n logging.info(\n f\"Running beam-search decoder on {uniq_id} with LM {self.ctc_decoder_params['pretrained_language_model']}\"\n )\n hyp_words, word_ts = self.run_pyctcdecode(logit_np)\n else:\n log_prob = torch.from_numpy(logit_np)\n logits_len = torch.from_numpy(np.array([log_prob.shape[0]]))\n greedy_predictions = log_prob.argmax(dim=-1, keepdim=False).unsqueeze(0)\n text, char_ts = wer_ts.ctc_decoder_predictions_tensor_with_ts(\n greedy_predictions, predictions_len=logits_len\n )\n trans, char_ts_in_feature_frame_idx = self.clean_trans_and_TS(text[0], char_ts[0])\n spaces_in_sec, hyp_words = self._get_spaces(\n trans, char_ts_in_feature_frame_idx, self.model_stride_in_secs\n )\n word_ts = self.get_word_ts_from_spaces(\n char_ts_in_feature_frame_idx, spaces_in_sec, end_stamp=logit_np.shape[0]\n )\n word_ts = self.align_decoder_delay(word_ts, self.decoder_delay_in_sec)\n assert len(hyp_words) == len(word_ts), \"Words and word timestamp list length does not match.\"\n words_dict[uniq_id] = hyp_words\n word_ts_dict[uniq_id] = word_ts\n\n return words_dict, word_ts_dict\n\n @staticmethod\n def clean_trans_and_TS(trans: str, char_ts: List[str]) -> Tuple[str, List[str]]:\n \"\"\"\n Remove the spaces in the beginning and the end.\n The char_ts need to be changed and synced accordingly.\n\n Args:\n trans (list):\n List of character output (str).\n char_ts (list):\n List of timestamps (int) for each character.\n\n Returns:\n trans (list):\n List of the cleaned character output.\n char_ts (list):\n List of the cleaned timestamps for each character.\n \"\"\"\n assert (len(trans) > 0) and (len(char_ts) > 0)\n assert len(trans) == len(char_ts)\n\n trans = trans.lstrip()\n diff_L = len(char_ts) - len(trans)\n char_ts = char_ts[diff_L:]\n\n trans = trans.rstrip()\n diff_R = len(char_ts) - len(trans)\n if diff_R > 0:\n char_ts = char_ts[: -1 * diff_R]\n return trans, char_ts\n\n def _get_spaces(self, trans: str, char_ts: List[str], time_stride: float) -> Tuple[float, List[str]]:\n \"\"\"\n Collect the space symbols with a list of words.\n\n Args:\n trans (list):\n List of character output (str).\n char_ts (list):\n List of timestamps of the characters.\n time_stride (float):\n The size of stride of the model in second.\n\n Returns:\n spaces_in_sec (list):\n List of the ranges of spaces\n word_list (list):\n List of the words from ASR inference.\n \"\"\"\n assert (len(trans) > 0) and (len(char_ts) > 0), \"Transcript and char_ts length should not be 0.\"\n assert len(trans) == len(char_ts), \"Transcript and timestamp lengths do not match.\"\n\n spaces_in_sec, word_list = [], []\n stt_idx = 0\n for k, s in enumerate(trans):\n if s == ' ':\n spaces_in_sec.append(\n [round(char_ts[k] * time_stride, 2), round((char_ts[k + 1] - 1) * time_stride, 2)]\n )\n word_list.append(trans[stt_idx:k])\n stt_idx = k + 1\n if len(trans) > stt_idx and trans[stt_idx] != ' ':\n word_list.append(trans[stt_idx:])\n\n return spaces_in_sec, word_list\n\n def run_ASR_CitriNet_CTC(self, asr_model: Type[EncDecCTCModelBPE]) -> Tuple[Dict, Dict]:\n \"\"\"\n Launch CitriNet ASR model and collect logit, timestamps and text output.\n\n Args:\n asr_model (class):\n The loaded NeMo ASR model.\n\n Returns:\n words_dict (dict):\n Dictionary of the sequence of words from hypothesis.\n word_ts_dict (dict):\n Dictionary of the timestamps of hypothesis words.\n \"\"\"\n words_dict, word_ts_dict = {}, {}\n\n werbpe_ts = WERBPE_TS(\n tokenizer=asr_model.tokenizer,\n batch_dim_index=0,\n use_cer=asr_model._cfg.get('use_cer', False),\n ctc_decode=True,\n dist_sync_on_step=True,\n log_prediction=asr_model._cfg.get(\"log_prediction\", False),\n )\n\n with torch.cuda.amp.autocast():\n transcript_logits_list = asr_model.transcribe(\n self.audio_file_list, batch_size=self.asr_batch_size, logprobs=True\n )\n for idx, logit_np in enumerate(transcript_logits_list):\n uniq_id = get_uniqname_from_filepath(self.audio_file_list[idx])\n if self.beam_search_decoder:\n logging.info(\n f\"Running beam-search decoder with LM {self.ctc_decoder_params['pretrained_language_model']}\"\n )\n hyp_words, word_ts = self.run_pyctcdecode(logit_np)\n else:\n log_prob = torch.from_numpy(logit_np)\n greedy_predictions = log_prob.argmax(dim=-1, keepdim=False).unsqueeze(0)\n logits_len = torch.from_numpy(np.array([log_prob.shape[0]]))\n text, char_ts, word_ts = werbpe_ts.ctc_decoder_predictions_tensor_with_ts(\n self.model_stride_in_secs, greedy_predictions, predictions_len=logits_len\n )\n hyp_words, word_ts = text[0].split(), word_ts[0]\n word_ts = self.align_decoder_delay(word_ts, self.decoder_delay_in_sec)\n assert len(hyp_words) == len(word_ts), \"Words and word timestamp list length does not match.\"\n words_dict[uniq_id] = hyp_words\n word_ts_dict[uniq_id] = word_ts\n\n return words_dict, word_ts_dict\n\n def set_buffered_infer_params(self, asr_model: Type[EncDecCTCModelBPE]) -> Tuple[float, float, float]:\n \"\"\"\n Prepare the parameters for the buffered inference.\n \"\"\"\n cfg = copy.deepcopy(asr_model._cfg)\n OmegaConf.set_struct(cfg.preprocessor, False)\n\n # some changes for streaming scenario\n cfg.preprocessor.dither = 0.0\n cfg.preprocessor.pad_to = 0\n cfg.preprocessor.normalize = \"None\"\n\n preprocessor = nemo_asr.models.EncDecCTCModelBPE.from_config_dict(cfg.preprocessor)\n preprocessor.to(asr_model.device)\n\n if cfg.preprocessor.normalize != \"per_feature\":\n logging.error(\n \"Only EncDecCTCModelBPE models trained with per_feature normalization are supported currently\"\n )\n\n # Disable config overwriting\n OmegaConf.set_struct(cfg.preprocessor, True)\n\n onset_delay = (\n math.ceil(((self.total_buffer_in_secs - self.chunk_len_in_sec) / 2) / self.model_stride_in_secs) + 1\n )\n mid_delay = math.ceil(\n (self.chunk_len_in_sec + (self.total_buffer_in_secs - self.chunk_len_in_sec) / 2)\n / self.model_stride_in_secs\n )\n tokens_per_chunk = math.ceil(self.chunk_len_in_sec / self.model_stride_in_secs)\n\n return onset_delay, mid_delay, tokens_per_chunk\n\n def run_ASR_BPE_CTC(self, asr_model: Type[EncDecCTCModelBPE]) -> Tuple[Dict, Dict]:\n \"\"\"\n Launch CTC-BPE based ASR model and collect logit, timestamps and text output.\n\n Args:\n asr_model (class):\n The loaded NeMo ASR model.\n\n Returns:\n words_dict (dict):\n Dictionary of the sequence of words from hypothesis.\n word_ts_dict (dict):\n Dictionary of the time-stamps of words.\n \"\"\"\n torch.manual_seed(0)\n torch.set_grad_enabled(False)\n words_dict, word_ts_dict = {}, {}\n\n werbpe_ts = WERBPE_TS(\n tokenizer=asr_model.tokenizer,\n batch_dim_index=0,\n use_cer=asr_model._cfg.get('use_cer', False),\n ctc_decode=True,\n dist_sync_on_step=True,\n log_prediction=asr_model._cfg.get(\"log_prediction\", False),\n )\n\n frame_asr = FrameBatchASR_Logits(\n asr_model=asr_model,\n frame_len=self.chunk_len_in_sec,\n total_buffer=self.total_buffer_in_secs,\n batch_size=self.asr_batch_size,\n )\n\n onset_delay, mid_delay, tokens_per_chunk = self.set_buffered_infer_params(asr_model)\n onset_delay_in_sec = round(onset_delay * self.model_stride_in_secs, 2)\n\n with torch.cuda.amp.autocast():\n logging.info(f\"Running ASR model {self.ASR_model_name}\")\n\n for idx, audio_file_path in enumerate(self.audio_file_list):\n uniq_id = get_uniqname_from_filepath(audio_file_path)\n logging.info(f\"[{idx+1}/{len(self.audio_file_list)}] FrameBatchASR: {audio_file_path}\")\n frame_asr.clear_buffer()\n\n hyp, greedy_predictions_list, log_prob = get_wer_feat_logit(\n audio_file_path,\n frame_asr,\n self.chunk_len_in_sec,\n tokens_per_chunk,\n mid_delay,\n self.model_stride_in_secs,\n )\n if self.beam_search_decoder:\n logging.info(\n f\"Running beam-search decoder with LM {self.ctc_decoder_params['pretrained_language_model']}\"\n )\n log_prob = log_prob.unsqueeze(0).cpu().numpy()[0]\n hyp_words, word_ts = self.run_pyctcdecode(log_prob, onset_delay_in_sec=onset_delay_in_sec)\n else:\n logits_len = torch.from_numpy(np.array([len(greedy_predictions_list)]))\n greedy_predictions_list = greedy_predictions_list[onset_delay:-mid_delay]\n greedy_predictions = torch.from_numpy(np.array(greedy_predictions_list)).unsqueeze(0)\n text, char_ts, word_ts = werbpe_ts.ctc_decoder_predictions_tensor_with_ts(\n self.model_stride_in_secs, greedy_predictions, predictions_len=logits_len\n )\n hyp_words, word_ts = text[0].split(), word_ts[0]\n\n word_ts = self.align_decoder_delay(word_ts, self.decoder_delay_in_sec)\n assert len(hyp_words) == len(word_ts), \"Words and word timestamp list length does not match.\"\n words_dict[uniq_id] = hyp_words\n word_ts_dict[uniq_id] = word_ts\n\n return words_dict, word_ts_dict\n\n def get_word_ts_from_spaces(self, char_ts: List[float], spaces_in_sec: List[float], end_stamp: float) -> List[str]:\n \"\"\"\n Take word timestamps from the spaces from the decoded prediction.\n\n Args:\n char_ts (list):\n List containing the timestamp for each character.\n spaces_in_sec (list):\n List containing the start and the end time of each space token.\n end_stamp (float):\n The end time of the session in sec.\n\n Returns:\n word_timestamps (list):\n List of the timestamps for the resulting words.\n \"\"\"\n start_stamp_in_sec = round(char_ts[0] * self.model_stride_in_secs, 2)\n end_stamp_in_sec = round(end_stamp * self.model_stride_in_secs, 2)\n word_timetamps_middle = [\n [round(spaces_in_sec[k][1], 2), round(spaces_in_sec[k + 1][0], 2),] for k in range(len(spaces_in_sec) - 1)\n ]\n word_timestamps = (\n [[start_stamp_in_sec, round(spaces_in_sec[0][0], 2)]]\n + word_timetamps_middle\n + [[round(spaces_in_sec[-1][1], 2), end_stamp_in_sec]]\n )\n return word_timestamps\n\n def run_pyctcdecode(\n self, logprob: np.ndarray, onset_delay_in_sec: float = 0, beam_width: int = 32\n ) -> Tuple[List[str], List[str]]:\n \"\"\"\n Launch pyctcdecode with the loaded pretrained language model.\n\n Args:\n logprob (np.ndarray):\n The log probability from the ASR model inference in numpy array format.\n onset_delay_in_sec (float):\n The amount of delay that needs to be compensated for the timestamp outputs froM pyctcdecode.\n beam_width (int):\n The beam width parameter for beam search decodring.\n Returns:\n hyp_words (list):\n List of words in the hypothesis.\n word_ts (list):\n List of word timestamps from the decoder.\n \"\"\"\n beams = self.beam_search_decoder.decode_beams(logprob, beam_width=self.ctc_decoder_params['beam_width'])\n word_ts_beam, words_beam = [], []\n for idx, (word, _) in enumerate(beams[0][2]):\n ts = self.get_word_ts_from_wordframes(idx, beams[0][2], self.model_stride_in_secs, onset_delay_in_sec)\n word_ts_beam.append(ts)\n words_beam.append(word)\n hyp_words, word_ts = words_beam, word_ts_beam\n return hyp_words, word_ts\n\n @staticmethod\n def get_word_ts_from_wordframes(idx, word_frames: List[List[float]], frame_duration: float, onset_delay: float):\n \"\"\"\n Extract word timestamps from word frames generated from pyctcdecode.\n \"\"\"\n offset = -1 * 2.25 * frame_duration - onset_delay\n frame_begin = word_frames[idx][1][0]\n if frame_begin == -1:\n frame_begin = word_frames[idx - 1][1][1] if idx != 0 else 0\n frame_end = word_frames[idx][1][1]\n return [\n round(max(frame_begin * frame_duration + offset, 0), 2),\n round(max(frame_end * frame_duration + offset, 0), 2),\n ]\n\n @staticmethod\n def align_decoder_delay(word_ts, decoder_delay_in_sec: float):\n \"\"\"\n Subtract decoder_delay_in_sec from the word timestamp output.\n \"\"\"\n for k in range(len(word_ts)):\n word_ts[k] = [\n round(word_ts[k][0] - decoder_delay_in_sec, 2),\n round(word_ts[k][1] - decoder_delay_in_sec, 2),\n ]\n return word_ts\n", "# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom typing import List\n\nimport torch\nfrom numpy import inf\nfrom torch import nn as nn\nfrom torch.nn import functional as F\n\nfrom nemo.collections.asr.parts.submodules.jasper import get_same_padding, init_weights\n\n\nclass StatsPoolLayer(nn.Module):\n \"\"\"\n Statistics and time average pooling (TAP) layer\n This computes mean and variance statistics across time dimension (dim=-1)\n input:\n feat_in: input channel feature length\n pool_mode: type of pool mode\n supported modes are xvector (mean and variance),\n tap (mean)\n output:\n pooled: statistics of feature input\n \"\"\"\n\n def __init__(self, feat_in: int, pool_mode: str = 'xvector'):\n super().__init__()\n self.pool_mode = pool_mode\n self.feat_in = feat_in\n if self.pool_mode == 'xvector':\n self.feat_in += feat_in\n elif self.pool_mode == 'tap':\n self.feat_in = feat_in\n else:\n raise ValueError(\"pool mode for stats must be either tap or xvector based\")\n\n def forward(self, encoder_output, length=None):\n mean = encoder_output.mean(dim=-1) # Time Axis\n if self.pool_mode == 'xvector':\n std = encoder_output.std(dim=-1)\n pooled = torch.cat([mean, std], dim=-1)\n else:\n pooled = mean\n return pooled\n\n\ndef lens_to_mask(lens: List[int], max_len: int, device: str = None):\n \"\"\"\n outputs masking labels for list of lengths of audio features, with max length of any \n mask as max_len\n input:\n lens: list of lens\n max_len: max length of any audio feature\n output:\n mask: masked labels\n num_values: sum of mask values for each feature (useful for computing statistics later)\n \"\"\"\n lens_mat = torch.arange(max_len).to(device)\n mask = lens_mat[:max_len].unsqueeze(0) < lens.unsqueeze(1)\n mask = mask.unsqueeze(1)\n num_values = torch.sum(mask, dim=2, keepdim=True)\n return mask, num_values\n\n\ndef get_statistics_with_mask(x: torch.Tensor, m: torch.Tensor, dim: int = 2, eps: float = 1e-10):\n \"\"\"\n compute mean and standard deviation of input(x) provided with its masking labels (m)\n input:\n x: feature input \n m: averaged mask labels \n output:\n mean: mean of input features\n std: stadard deviation of input features\n \"\"\"\n mean = torch.sum((m * x), dim=dim)\n std = torch.sqrt((m * (x - mean.unsqueeze(dim)).pow(2)).sum(dim).clamp(eps))\n return mean, std\n\n\nclass TDNNModule(nn.Module):\n \"\"\"\n Time Delayed Neural Module (TDNN) - 1D\n input:\n inp_filters: input filter channels for conv layer\n out_filters: output filter channels for conv layer\n kernel_size: kernel weight size for conv layer\n dilation: dilation for conv layer\n stride: stride for conv layer\n padding: padding for conv layer (default None: chooses padding value such that input and output feature shape matches)\n output:\n tdnn layer output \n \"\"\"\n\n def __init__(\n self,\n inp_filters: int,\n out_filters: int,\n kernel_size: int = 1,\n dilation: int = 1,\n stride: int = 1,\n padding: int = None,\n ):\n super().__init__()\n if padding is None:\n padding = get_same_padding(kernel_size, stride=stride, dilation=dilation)\n\n self.conv_layer = nn.Conv1d(\n in_channels=inp_filters,\n out_channels=out_filters,\n kernel_size=kernel_size,\n dilation=dilation,\n padding=padding,\n )\n\n self.activation = nn.ReLU()\n self.bn = nn.BatchNorm1d(out_filters)\n\n def forward(self, x, length=None):\n x = self.conv_layer(x)\n x = self.activation(x)\n return self.bn(x)\n\n\nclass MaskedSEModule(nn.Module):\n \"\"\"\n Squeeze and Excite module implementation with conv1d layers\n input:\n inp_filters: input filter channel size \n se_filters: intermediate squeeze and excite channel output and input size\n out_filters: output filter channel size\n kernel_size: kernel_size for both conv1d layers\n dilation: dilation size for both conv1d layers\n\n output:\n squeeze and excite layer output\n \"\"\"\n\n def __init__(self, inp_filters: int, se_filters: int, out_filters: int, kernel_size: int = 1, dilation: int = 1):\n super().__init__()\n self.se_layer = nn.Sequential(\n nn.Conv1d(inp_filters, se_filters, kernel_size=kernel_size, dilation=dilation,),\n nn.ReLU(),\n nn.BatchNorm1d(se_filters),\n nn.Conv1d(se_filters, out_filters, kernel_size=kernel_size, dilation=dilation,),\n nn.Sigmoid(),\n )\n\n def forward(self, input, length=None):\n if length is None:\n x = torch.mean(input, dim=2, keep_dim=True)\n else:\n max_len = input.size(2)\n mask, num_values = lens_to_mask(length, max_len=max_len, device=input.device)\n x = torch.sum((input * mask), dim=2, keepdim=True) / (num_values)\n\n out = self.se_layer(x)\n return out * input\n\n\nclass TDNNSEModule(nn.Module):\n \"\"\"\n Modified building SE_TDNN group module block from ECAPA implementation for faster training and inference\n Reference: ECAPA-TDNN Embeddings for Speaker Diarization (https://arxiv.org/pdf/2104.01466.pdf)\n inputs:\n inp_filters: input filter channel size \n out_filters: output filter channel size\n group_scale: scale value to group wider conv channels (deafult:8)\n se_channels: squeeze and excite output channel size (deafult: 1024/8= 128)\n kernel_size: kernel_size for group conv1d layers (default: 1)\n dilation: dilation size for group conv1d layers (default: 1)\n \"\"\"\n\n def __init__(\n self,\n inp_filters: int,\n out_filters: int,\n group_scale: int = 8,\n se_channels: int = 128,\n kernel_size: int = 1,\n dilation: int = 1,\n init_mode: str = 'xavier_uniform',\n ):\n super().__init__()\n self.out_filters = out_filters\n padding_val = get_same_padding(kernel_size=kernel_size, dilation=dilation, stride=1)\n\n group_conv = nn.Conv1d(\n out_filters,\n out_filters,\n kernel_size=kernel_size,\n dilation=dilation,\n padding=padding_val,\n groups=group_scale,\n )\n self.group_tdnn_block = nn.Sequential(\n TDNNModule(inp_filters, out_filters, kernel_size=1, dilation=1),\n group_conv,\n nn.ReLU(),\n nn.BatchNorm1d(out_filters),\n TDNNModule(out_filters, out_filters, kernel_size=1, dilation=1),\n )\n\n self.se_layer = MaskedSEModule(out_filters, se_channels, out_filters)\n\n self.apply(lambda x: init_weights(x, mode=init_mode))\n\n def forward(self, input, length=None):\n x = self.group_tdnn_block(input)\n x = self.se_layer(x, length)\n return x + input\n\n\nclass AttentivePoolLayer(nn.Module):\n \"\"\"\n Attention pooling layer for pooling speaker embeddings\n Reference: ECAPA-TDNN Embeddings for Speaker Diarization (https://arxiv.org/pdf/2104.01466.pdf)\n inputs:\n inp_filters: input feature channel length from encoder\n attention_channels: intermediate attention channel size\n kernel_size: kernel_size for TDNN and attention conv1d layers (default: 1)\n dilation: dilation size for TDNN and attention conv1d layers (default: 1) \n \"\"\"\n\n def __init__(\n self,\n inp_filters: int,\n attention_channels: int = 128,\n kernel_size: int = 1,\n dilation: int = 1,\n eps: float = 1e-10,\n ):\n super().__init__()\n\n self.feat_in = 2 * inp_filters\n\n self.attention_layer = nn.Sequential(\n TDNNModule(inp_filters * 3, attention_channels, kernel_size=kernel_size, dilation=dilation),\n nn.Tanh(),\n nn.Conv1d(\n in_channels=attention_channels, out_channels=inp_filters, kernel_size=kernel_size, dilation=dilation,\n ),\n )\n self.eps = eps\n\n def forward(self, x, length=None):\n max_len = x.size(2)\n\n if length is None:\n length = torch.ones(x.shape[0], device=x.device)\n\n mask, num_values = lens_to_mask(length, max_len=max_len, device=x.device)\n\n # encoder statistics\n mean, std = get_statistics_with_mask(x, mask / num_values)\n mean = mean.unsqueeze(2).repeat(1, 1, max_len)\n std = std.unsqueeze(2).repeat(1, 1, max_len)\n attn = torch.cat([x, mean, std], dim=1)\n\n # attention statistics\n attn = self.attention_layer(attn) # attention pass\n attn = attn.masked_fill(mask == 0, -inf)\n alpha = F.softmax(attn, dim=2) # attention values, α\n mu, sg = get_statistics_with_mask(x, alpha) # µ and ∑\n\n # gather\n return torch.cat((mu, sg), dim=1).unsqueeze(2)\n", "# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nScript to perform buffered inference using RNNT models.\n\nBuffered inference is the primary form of audio transcription when the audio segment is longer than 20-30 seconds.\nThis is especially useful for models such as Conformers, which have quadratic time and memory scaling with\naudio duration.\n\nThe difference between streaming and buffered inference is the chunk size (or the latency of inference).\nBuffered inference will use large chunk sizes (5-10 seconds) + some additional buffer for context.\nStreaming inference will use small chunk sizes (0.1 to 0.25 seconds) + some additional buffer for context.\n\n# Middle Token merge algorithm\n\npython speech_to_text_buffered_infer_rnnt.py \\\n --asr_model=\"<Path to a nemo model>\" \\\n --test_manifest=\"<Path to a JSON manifest>\" \\\n --model_stride=4 \\\n --output_path=\".\" \\\n --total_buffer_in_secs=10.0 \\\n --chunk_len_in_secs=8.0 \\\n --device=\"cuda:0\" \\\n --batch_size=128\n\n# Longer Common Subsequence (LCS) Merge algorithm\n\npython speech_to_text_buffered_infer_rnnt.py \\\n --asr_model=\"<Path to a nemo model>\" \\\n --test_manifest=\"<Path to a JSON manifest>\" \\\n --model_stride=4 \\\n --output_path=\".\" \\\n --merge_algo=\"lcs\" \\\n --lcs_alignment_dir=<OPTIONAL: Some path to store the LCS alignments> \\\n --total_buffer_in_secs=10.0 \\\n --chunk_len_in_secs=8.0 \\\n --device=\"cuda:0\" \\\n --batch_size=128\n\n# NOTE:\n\n You can use `DEBUG=1 python speech_to_text_buffered_infer_rnnt.py ...` to print out the\n ground truth text and predictions of the model.\n\n\"\"\"\n\nimport copy\nimport json\nimport math\nimport os\nfrom argparse import ArgumentParser\n\nimport torch\nimport tqdm\nfrom omegaconf import OmegaConf, open_dict\n\nimport nemo.collections.asr as nemo_asr\nfrom nemo.collections.asr.metrics.wer import word_error_rate\nfrom nemo.collections.asr.parts.utils.streaming_utils import (\n BatchedFrameASRRNNT,\n LongestCommonSubsequenceBatchedFrameASRRNNT,\n)\nfrom nemo.utils import logging\n\ncan_gpu = torch.cuda.is_available()\n\n# Common Arguments\nparser = ArgumentParser()\nparser.add_argument(\n \"--asr_model\", type=str, required=True, help=\"Path to asr model .nemo file\",\n)\nparser.add_argument(\"--test_manifest\", type=str, required=True, help=\"path to evaluation data\")\nparser.add_argument(\"--batch_size\", type=int, default=32)\nparser.add_argument(\n \"--total_buffer_in_secs\",\n type=float,\n default=4.0,\n help=\"Length of buffer (chunk + left and right padding) in seconds \",\n)\nparser.add_argument(\"--chunk_len_in_secs\", type=float, default=1.6, help=\"Chunk length in seconds\")\nparser.add_argument(\"--output_path\", type=str, help=\"path to output file\", default=None)\nparser.add_argument(\n \"--model_stride\",\n type=int,\n default=8,\n help=\"Model downsampling factor, 8 for Citrinet models and 4 for Conformer models\",\n)\nparser.add_argument(\n '--max_steps_per_timestep', type=int, default=5, help='Maximum number of tokens decoded per acoustic timestepB'\n)\nparser.add_argument('--stateful_decoding', action='store_true', help='Whether to perform stateful decoding')\nparser.add_argument('--device', default=None, type=str, required=False)\n\n# Merge algorithm for transducers\nparser.add_argument(\n '--merge_algo',\n default='middle',\n type=str,\n required=False,\n choices=['middle', 'lcs'],\n help='Choice of algorithm to apply during inference.',\n)\n\n# LCS Merge Algorithm\nparser.add_argument(\n '--lcs_alignment_dir', type=str, default=None, help='Path to a directory to store LCS algo alignments'\n)\n\n\ndef get_wer_feat(mfst, asr, tokens_per_chunk, delay, model_stride_in_secs, batch_size):\n hyps = []\n refs = []\n audio_filepaths = []\n\n with open(mfst, \"r\") as mfst_f:\n print(\"Parsing manifest files...\")\n for l in mfst_f:\n row = json.loads(l.strip())\n audio_filepaths.append(row['audio_filepath'])\n refs.append(row['text'])\n\n with torch.inference_mode():\n with torch.cuda.amp.autocast():\n batch = []\n asr.sample_offset = 0\n for idx in tqdm.tqdm(range(len(audio_filepaths)), desc='Sample:', total=len(audio_filepaths)):\n batch.append((audio_filepaths[idx], refs[idx]))\n\n if len(batch) == batch_size:\n audio_files = [sample[0] for sample in batch]\n\n asr.reset()\n asr.read_audio_file(audio_files, delay, model_stride_in_secs)\n hyp_list = asr.transcribe(tokens_per_chunk, delay)\n hyps.extend(hyp_list)\n\n batch.clear()\n asr.sample_offset += batch_size\n\n if len(batch) > 0:\n asr.batch_size = len(batch)\n asr.frame_bufferer.batch_size = len(batch)\n asr.reset()\n\n audio_files = [sample[0] for sample in batch]\n asr.read_audio_file(audio_files, delay, model_stride_in_secs)\n hyp_list = asr.transcribe(tokens_per_chunk, delay)\n hyps.extend(hyp_list)\n\n batch.clear()\n asr.sample_offset += len(batch)\n\n if os.environ.get('DEBUG', '0') in ('1', 'y', 't'):\n for hyp, ref in zip(hyps, refs):\n print(\"hyp:\", hyp)\n print(\"ref:\", ref)\n\n wer = word_error_rate(hypotheses=hyps, references=refs)\n return hyps, refs, wer\n\n\ndef main(args):\n torch.set_grad_enabled(False)\n if args.asr_model.endswith('.nemo'):\n logging.info(f\"Using local ASR model from {args.asr_model}\")\n asr_model = nemo_asr.models.EncDecCTCModelBPE.restore_from(restore_path=args.asr_model)\n else:\n logging.info(f\"Using NGC cloud ASR model {args.asr_model}\")\n asr_model = nemo_asr.models.EncDecCTCModelBPE.from_pretrained(model_name=args.asr_model)\n\n cfg = copy.deepcopy(asr_model._cfg)\n OmegaConf.set_struct(cfg.preprocessor, False)\n\n # some changes for streaming scenario\n cfg.preprocessor.dither = 0.0\n cfg.preprocessor.pad_to = 0\n\n if cfg.preprocessor.normalize != \"per_feature\":\n logging.error(\"Only EncDecRNNTBPEModel models trained with per_feature normalization are supported currently\")\n\n device = args.device\n if device is None:\n if torch.cuda.is_available():\n device = 'cuda'\n else:\n device = 'cpu'\n\n logging.info(f\"Inference will be done on device : {device}\")\n\n # Disable config overwriting\n OmegaConf.set_struct(cfg.preprocessor, True)\n asr_model.freeze()\n asr_model = asr_model.to(device)\n\n # Change Decoding Config\n decoding_cfg = asr_model.cfg.decoding\n with open_dict(decoding_cfg):\n if args.stateful_decoding:\n decoding_cfg.strategy = \"greedy\"\n else:\n decoding_cfg.strategy = \"greedy_batch\"\n\n decoding_cfg.preserve_alignments = True # required to compute the middle token for transducers.\n decoding_cfg.fused_batch_size = -1 # temporarily stop fused batch during inference.\n\n asr_model.change_decoding_strategy(decoding_cfg)\n\n feature_stride = cfg.preprocessor['window_stride']\n model_stride_in_secs = feature_stride * args.model_stride\n total_buffer = args.total_buffer_in_secs\n\n chunk_len = float(args.chunk_len_in_secs)\n\n tokens_per_chunk = math.ceil(chunk_len / model_stride_in_secs)\n mid_delay = math.ceil((chunk_len + (total_buffer - chunk_len) / 2) / model_stride_in_secs)\n print(\"Tokens per chunk :\", tokens_per_chunk, \"Min Delay :\", mid_delay)\n\n if args.merge_algo == 'middle':\n frame_asr = BatchedFrameASRRNNT(\n asr_model=asr_model,\n frame_len=chunk_len,\n total_buffer=args.total_buffer_in_secs,\n batch_size=args.batch_size,\n max_steps_per_timestep=args.max_steps_per_timestep,\n stateful_decoding=args.stateful_decoding,\n )\n\n elif args.merge_algo == 'lcs':\n frame_asr = LongestCommonSubsequenceBatchedFrameASRRNNT(\n asr_model=asr_model,\n frame_len=chunk_len,\n total_buffer=args.total_buffer_in_secs,\n batch_size=args.batch_size,\n max_steps_per_timestep=args.max_steps_per_timestep,\n stateful_decoding=args.stateful_decoding,\n alignment_basepath=args.lcs_alignment_dir,\n )\n # Set the LCS algorithm delay.\n frame_asr.lcs_delay = math.floor(((total_buffer - chunk_len)) / model_stride_in_secs)\n\n else:\n raise ValueError(\"Invalid choice of merge algorithm for transducer buffered inference.\")\n\n hyps, refs, wer = get_wer_feat(\n mfst=args.test_manifest,\n asr=frame_asr,\n tokens_per_chunk=tokens_per_chunk,\n delay=mid_delay,\n model_stride_in_secs=model_stride_in_secs,\n batch_size=args.batch_size,\n )\n logging.info(f\"WER is {round(wer, 4)} when decoded with a delay of {round(mid_delay*model_stride_in_secs, 2)}s\")\n\n if args.output_path is not None:\n\n fname = (\n os.path.splitext(os.path.basename(args.asr_model))[0]\n + \"_\"\n + os.path.splitext(os.path.basename(args.test_manifest))[0]\n + \"_\"\n + str(args.chunk_len_in_secs)\n + \"_\"\n + str(int(total_buffer * 1000))\n + \"_\"\n + args.merge_algo\n + \".json\"\n )\n\n hyp_json = os.path.join(args.output_path, fname)\n os.makedirs(args.output_path, exist_ok=True)\n with open(hyp_json, \"w\") as out_f:\n for i, hyp in enumerate(hyps):\n record = {\n \"pred_text\": hyp,\n \"text\": refs[i],\n \"wer\": round(word_error_rate(hypotheses=[hyp], references=[refs[i]]) * 100, 2),\n }\n out_f.write(json.dumps(record) + '\\n')\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n main(args) # noqa pylint: disable=no-value-for-parameter\n", "# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport pickle\nfrom typing import List\n\nimport numpy\n\nfrom nemo.collections.common.tokenizers.column_coder import ColumnCodes\nfrom nemo.collections.common.tokenizers.tokenizer_spec import TokenizerSpec\n\n__all__ = ['TabularTokenizer']\n\nEND_OF_TEXT = '<|endoftext|>'\nNEW_LINE = '\\n'\n\n\ndef find_index_of(list_input, item):\n output = -1\n try:\n output = list_input.index(item)\n except ValueError:\n pass\n return output\n\n\nclass TabularTokenizer(TokenizerSpec):\n def __init__(self, coder, special_tokens=[END_OF_TEXT, NEW_LINE], delimiter=','):\n if isinstance(coder, ColumnCodes):\n self.code_column: ColumnCodes = coder\n else:\n with open(coder, 'rb') as handle:\n self.code_column: ColumnCodes = pickle.load(handle)\n self.num_columns = len(self.code_column.columns)\n self.special_tokens = {}\n self.special_tokens_decoder = {}\n self.add_special_tokens(special_tokens)\n self.delimiter = delimiter\n self.eod_id = self.special_tokens[END_OF_TEXT]\n self.eos_id = self.eod_id\n\n def __len__(self):\n return self.vocab_size\n\n @property\n def vocab_size(self):\n return max(self.special_tokens_decoder.keys()) + 1\n\n def text_to_ids(self, text):\n return self.encode(text)\n\n def ids_to_text(self, token_ids):\n return self.decode(token_ids)\n\n @property\n def eod(self):\n return self.eod_id\n\n @property\n def eor(self):\n return self.special_tokens[NEW_LINE]\n\n def add_special_tokens(self, special_tokens):\n \"\"\" Add a list of additional tokens to the encoder.\n The additional tokens are indexed starting from the last\n index of the\n current vocabulary in the order of the `special_tokens` list.\n \"\"\"\n if not special_tokens:\n self.special_tokens = {}\n self.special_tokens_decoder = {}\n return\n new = dict(\n (tok, self.code_column.vocab_size + i)\n for i, tok in enumerate(special_tokens)\n if tok not in self.special_tokens\n )\n self.special_tokens.update(new)\n self.special_tokens_decoder = {v: k for k, v in self.special_tokens.items()}\n\n def text_to_tokens(self, text):\n \"\"\" Tokenize a string. \"\"\"\n tokens = []\n rows = text.split(NEW_LINE)\n num_rows = len(rows)\n for row_id in range(num_rows):\n row = rows[row_id]\n if row == '':\n continue\n fields = row.split(self.delimiter)\n for f in fields:\n splits = f.split(END_OF_TEXT)\n if len(splits) == 1:\n tokens.append(f.strip())\n elif len(splits) == 2:\n if splits[0] != '':\n tokens.append(splits[0].strip())\n tokens.append(END_OF_TEXT)\n if splits[1] != '':\n tokens.append(splits[1].strip())\n else:\n raise ValueError(\"delimiter error\")\n if row_id != num_rows - 1:\n tokens.append(NEW_LINE)\n return tokens\n\n def tokens_to_ids(self, tokens: List[str]):\n \"\"\" Converts a sequence of tokens into ids using the vocab. \"\"\"\n ids = []\n cindex = 0\n if NEW_LINE in tokens:\n idd = tokens.index(NEW_LINE)\n cindex = (self.num_columns - idd) % self.num_columns\n for token in tokens:\n\n if token in self.special_tokens:\n ids.append(self.special_tokens[token])\n else:\n index = cindex % self.num_columns\n column = self.code_column.columns[index]\n ids.extend(self.code_column.encode(column, token))\n cindex += 1\n return ids\n\n def ids_to_tokens(self, ids, skip_special_tokens=False):\n \"\"\"Converts a sequence of ids in Tabular tokens using the vocab.\"\"\"\n tokens = []\n sizes = self.code_column.sizes\n ids_size = sum(sizes)\n cindex = 0\n eor_pos = find_index_of(ids, self.eor)\n eod_pos = find_index_of(ids, self.eod)\n if eor_pos >= 0 and eod_pos >= 0:\n idd = min(eor_pos, eod_pos)\n cindex = (ids_size - idd) % ids_size\n elif eor_pos >= 0 and eod_pos < 0:\n idd = eor_pos\n cindex = (ids_size - idd) % ids_size\n elif eod_pos >= 0 and eor_pos < 0:\n idd = eod_pos\n cindex = (ids_size - idd) % ids_size\n cum_sizes = numpy.cumsum(sizes)\n old_column_index = -1\n token_ids = []\n for i in ids:\n if i in self.special_tokens_decoder:\n if not skip_special_tokens:\n tokens.append(self.special_tokens_decoder[i])\n else:\n index = cindex % ids_size\n column_index = numpy.where(index < cum_sizes)[0][0]\n column = self.code_column.columns[column_index]\n if old_column_index != column_index:\n token_ids = [i]\n old_column_index = column_index\n else:\n token_ids.append(i)\n if len(token_ids) == sizes[column_index]:\n tokens.append(self.code_column.decode(column, token_ids))\n cindex += 1\n return tokens\n\n def encode(self, text):\n return self.tokens_to_ids(self.text_to_tokens(text))\n\n def decode(self, token_ids):\n tokens = self.ids_to_tokens(token_ids, skip_special_tokens=False)\n return self.tokens_to_text(tokens)\n\n def tokens_to_text(self, tokens):\n all_lines = []\n line = []\n for token in tokens:\n if token == END_OF_TEXT or token == NEW_LINE:\n if len(line) != 0:\n line_text = self.delimiter.join(line)\n all_lines.append(line_text)\n all_lines.append(token)\n line = []\n else:\n line.append(token)\n if len(line) != 0:\n # remaining items\n line_text = self.delimiter.join(line)\n all_lines.append(line_text)\n text = \"\".join(all_lines)\n return text\n", "# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport itertools\nimport pickle as pkl\nimport random\nfrom argparse import ArgumentParser\n\nimport pandas as pd\nfrom omegaconf import OmegaConf\nfrom tqdm import tqdm\n\n# Info on these headers can be found here on the UMLS website https://www.ncbi.nlm.nih.gov/books/NBK9685/\n# section 3.3.4 Table 1\nHEADERS = [\n 'CUI',\n 'LAT',\n 'TS',\n 'LUI',\n 'STT',\n 'SUI',\n 'ISPREF',\n 'AUI',\n 'SAUI',\n 'SCUI',\n 'SDUI',\n 'SAB',\n 'TTY',\n 'CODE',\n 'STR',\n 'SRL',\n 'SUPPRESS',\n 'CVF',\n]\n\n\ndef process_umls_training_dataset(data_path, train_save_name, val_save_name, max_pairs, train_split, headers):\n \"\"\"\n Generates and saves UMLS self alignment pretraining train and validation data. Takes the raw .RRF UMLS \n data file and creates different pair combinations for entities with the same CUI. Each row in the output\n will be formatted as 'CUI EntitySynonym1 EntitySynonym2' with each item in a row separated by tabs.\n Saves two .tsv output files, one for the train split and one for the validation split.\n Only data marked as English is added to the train and val splits. \n\n Arguments:\n data_path (str): path to MRCONSO.RRF UMLS data file\n train_save_name (str): path to where training data will be saved\n val_save_name (str): path to where validation data will be saved\n max_pairs (int): max number of pairs for any one CUI added to the train \n or validation splits\n train_split (float): precentage of raw data to be added to train set split\n headers (list): column lables within MRCONSO.RRF\n \"\"\"\n\n print(\"Loading training data file...\")\n df = pd.read_table(data_path, names=headers, index_col=False, delimiter='|')\n train_file = open(train_save_name, 'w')\n val_file = open(val_save_name, 'w')\n\n cui = df[\"CUI\"].iloc[0]\n names = []\n random.seed(2021)\n\n for idx in tqdm(range(len(df))):\n # Address incorrectly formatted data\n if type(df[\"STR\"].iloc[idx]) != str or \"|\" in df[\"STR\"].iloc[idx]:\n continue\n\n # Collect all english concept strings matching the current CUI\n if df[\"CUI\"].iloc[idx] == cui and df[\"LAT\"].iloc[idx] == \"ENG\":\n concept_string = df[\"STR\"].iloc[idx]\n names.append(concept_string)\n\n else:\n # Pair off concept synonyms to make training and val sets\n pairs = list(itertools.combinations(names, 2))\n\n if len(pairs) == 0:\n # Not enough concepts gathered to make a pair\n cui = df[\"CUI\"].iloc[idx]\n names = [df[\"STR\"].iloc[idx]]\n continue\n\n # Removing leading C to convert label string to int\n cui = int(cui[1:])\n random.shuffle(pairs)\n\n # Keep up to max pairs number pairs for any one concept\n for pair in pairs[:max_pairs]:\n\n # Want concepts in train and val splits to be randomly selected and mutually exclusive\n add_to_train = random.random()\n\n if add_to_train <= train_split:\n train_file.write(f'{cui}\\t{pair[0]}\\t{pair[1]}\\n')\n else:\n val_file.write(f'{cui}\\t{pair[0]}\\t{pair[1]}\\n')\n\n # Switch to next concept\n cui = df[\"CUI\"].iloc[idx]\n names = [df[\"STR\"].iloc[idx]]\n\n train_file.close()\n val_file.close()\n print(\"Finished making training and validation data\")\n\n\ndef process_umls_index_dataset(data_path, data_savename, id2string_savename, headers):\n \"\"\"\n Generates data file needed to build a UMLS index and a hash table mapping each\n CUI to one canonical concept string. Takes the raw .RRF data file and saves \n a .tsv indec concept file as well as the a .pkl file of cui to concept string \n mappings. Only data marked as English is added to the index data file. \n\n Arguments:\n data_path (str): path to MRCONSO.RRF UMLS data file\n data_savename (str): path to where .tsv index data will be saved\n id2string_savename (str): path to where .pkl cui to string mapping will\n be saved\n headers (list): column lables within MRCONSO.RRF\n \"\"\"\n\n print(\"Loading index data file...\")\n df = pd.read_table(data_path, names=headers, index_col=False, delimiter='|')\n id2string = {}\n\n with open(data_savename, \"w\") as outfile:\n for idx, row in tqdm(df.iterrows(), total=df.shape[0]):\n # Address incorrectly formatted data\n if type(row[\"STR\"]) != str or \"|\" in row[\"STR\"]:\n continue\n\n cui = row[\"CUI\"]\n sent = row[\"STR\"]\n\n # Removing leading C to convert label string to int\n cui = int(cui[1:])\n\n # Only keeping english concepts\n if row[\"LAT\"] == \"ENG\":\n outfile.write(f'{cui}\\t{sent}\\n')\n\n # Matching each cui to one canonical string represention\n if cui not in id2string and \":\" not in sent:\n id2string[cui] = sent\n\n outfile.close()\n pkl.dump(id2string, open(id2string_savename, \"wb\"))\n print(\"Finished saving index data and id to concept mapping\")\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument(\"--index\", action=\"store_true\", help=\"Whether to process data for building an index\")\n parser.add_argument(\"--project_dir\", required=False, type=str, default=\".\")\n parser.add_argument(\"--cfg\", required=False, type=str, default=\"conf/umls_medical_entity_linking_config.yaml\")\n parser.add_argument(\n \"--max_pairs\", required=False, type=int, default=50, help=\"Max number of train pairs for a single concepts\"\n )\n parser.add_argument(\n \"--train_split\", required=False, type=float, default=0.99, help=\"Precentage of data to add to train set\"\n )\n\n args = parser.parse_args()\n cfg = OmegaConf.load(args.cfg)\n cfg.project_dir = args.project_dir\n\n if args.index:\n process_umls_index_dataset(cfg.index.raw_data, cfg.index.index_ds.data_file, cfg.index.id_to_string, HEADERS)\n else:\n process_umls_training_dataset(\n cfg.model.raw_data,\n cfg.model.train_ds.data_file,\n cfg.model.validation_ds.data_file,\n args.max_pairs,\n args.train_split,\n HEADERS,\n )\n", "# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Dict, Optional\n\nimport torch\nfrom omegaconf import DictConfig\nfrom pytorch_lightning import Trainer\n\nfrom nemo.collections.common.losses import SmoothedCrossEntropyLoss\nfrom nemo.collections.nlp.data import BertInformationRetrievalDataset\nfrom nemo.collections.nlp.models.information_retrieval.base_ir_model import BaseIRModel\nfrom nemo.collections.nlp.modules.common.tokenizer_utils import get_tokenizer\nfrom nemo.core.classes.common import typecheck\nfrom nemo.core.neural_types import ChannelType, LogitsType, MaskType, NeuralType\n\n__all__ = [\"BertDPRModel\"]\n\n\nclass BertDPRModel(BaseIRModel):\n \"\"\"\n Information retrieval model which encodes query and passage separately\n with two different BERT encoders and computes their similarity score\n as a dot-product between corresponding [CLS] token representations.\n \"\"\"\n\n @property\n def input_types(self) -> Optional[Dict[str, NeuralType]]:\n return {\n \"q_input_ids\": NeuralType((\"B\", \"T\"), ChannelType()),\n \"q_attention_mask\": NeuralType((\"B\", \"T\"), MaskType()),\n \"q_token_type_ids\": NeuralType((\"B\", \"T\"), ChannelType()),\n \"p_input_ids\": NeuralType((\"B\", \"T\"), ChannelType()),\n \"p_attention_mask\": NeuralType((\"B\", \"T\"), MaskType()),\n \"p_token_type_ids\": NeuralType((\"B\", \"T\"), ChannelType()),\n }\n\n @property\n def output_types(self) -> Optional[Dict[str, NeuralType]]:\n return {\"logits\": NeuralType((\"B\", \"D\"), LogitsType())}\n\n def __init__(self, cfg: DictConfig, trainer: Trainer = None):\n\n model_name = cfg.language_model.pretrained_model_name\n self.tokenizer = get_tokenizer(tokenizer_name=model_name)\n\n super().__init__(cfg=cfg, trainer=trainer)\n\n self.q_encoder = self.get_lm_model_with_padded_embedding(cfg)\n self.p_encoder = self.get_lm_model_with_padded_embedding(cfg)\n self.loss = SmoothedCrossEntropyLoss(pad_id=self.tokenizer.pad_id)\n\n @typecheck()\n def forward(\n self, q_input_ids, q_token_type_ids, q_attention_mask, p_input_ids, p_token_type_ids, p_attention_mask,\n ):\n\n q_vectors = self.q_encoder(\n input_ids=q_input_ids, token_type_ids=q_token_type_ids, attention_mask=q_attention_mask,\n )\n q_vectors = q_vectors[:, 0]\n batch_size, hidden_size = q_vectors.size()\n\n p_vectors = self.p_encoder(\n input_ids=p_input_ids, token_type_ids=p_token_type_ids, attention_mask=p_attention_mask,\n )\n num_passages = p_vectors.shape[0] // batch_size\n p_vectors = p_vectors[:, 0].view(-1, num_passages, hidden_size)\n p_positives, p_negatives = p_vectors[:, 0], p_vectors[:, 1:]\n scores = torch.cat(\n (torch.matmul(q_vectors, p_positives.T), torch.einsum(\"ij,ipj->ip\", q_vectors, p_negatives),), dim=1,\n )\n\n return scores\n\n def compute_scores_and_loss(self, inputs):\n (q_input_ids, q_input_mask, q_input_type_ids, p_input_ids, p_input_mask, p_input_type_ids,) = inputs\n batch_size, num_passages, p_seq_length = p_input_ids.size()\n q_seq_length = q_input_ids.size()[-1]\n\n scores = self(\n q_input_ids=q_input_ids.view(-1, q_seq_length),\n q_token_type_ids=q_input_type_ids.view(-1, q_seq_length),\n q_attention_mask=q_input_mask.view(-1, q_seq_length),\n p_input_ids=p_input_ids.view(-1, p_seq_length),\n p_token_type_ids=p_input_type_ids.view(-1, p_seq_length),\n p_attention_mask=p_input_mask.view(-1, p_seq_length),\n ).view(batch_size, 1, batch_size + num_passages - 1)\n normalized_scores = torch.log_softmax(scores, dim=-1)\n\n labels = torch.arange(batch_size)[:, None].long().to(normalized_scores.device)\n loss = self.loss(log_probs=normalized_scores, labels=labels, output_mask=torch.ones_like(labels),)\n\n scores = scores[:, 0]\n scores = torch.cat((torch.diag(scores)[:, None], scores[:, batch_size:]), dim=1,)\n\n return scores, loss\n\n def _setup_dataloader_from_config(self, cfg: DictConfig):\n\n dataset = BertInformationRetrievalDataset(\n tokenizer=self.tokenizer,\n passages=cfg.passages,\n queries=cfg.queries,\n query_to_passages=cfg.query_to_passages,\n num_negatives=cfg.num_negatives,\n psg_cache_format=cfg.get(\"psg_cache_format\", \"pkl\"),\n max_query_length=cfg.get(\"max_query_length\", 31),\n max_passage_length=cfg.get(\"max_passage_length\", 190),\n preprocess_fn=\"preprocess_dpr\",\n )\n\n return torch.utils.data.DataLoader(\n dataset=dataset,\n batch_size=cfg.batch_size,\n shuffle=cfg.shuffle,\n num_workers=cfg.get(\"num_workers\", 2),\n pin_memory=cfg.get(\"pin_memory\", False),\n drop_last=cfg.get(\"drop_last\", False),\n )\n", "# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport json\nimport math\nimport os\nfrom copy import deepcopy\n\nimport numpy as np\nimport omegaconf\nimport soundfile as sf\nimport torch\nfrom pyannote.core import Annotation, Segment, Timeline\nfrom pyannote.metrics.diarization import DiarizationErrorRate\nfrom tqdm import tqdm\n\nfrom nemo.collections.asr.parts.utils.nmesc_clustering import COSclustering\nfrom nemo.utils import logging\n\n\n\"\"\"\nThis file contains all the utility functions required for speaker embeddings part in diarization scripts\n\"\"\"\n\n\ndef get_uniqname_from_filepath(filepath):\n \"return base name from provided filepath\"\n if type(filepath) is str:\n basename = os.path.basename(filepath).rsplit('.', 1)[0]\n return basename\n else:\n raise TypeError(\"input must be filepath string\")\n\n\ndef audio_rttm_map(manifest):\n \"\"\"\n This function creates AUDIO_RTTM_MAP which is used by all diarization components to extract embeddings,\n cluster and unify time stamps\n input: manifest file that contains keys audio_filepath, rttm_filepath if exists, text, num_speakers if known and uem_filepath if exists\n\n returns:\n AUDIO_RTTM_MAP (dict) : A dictionary with keys of uniq id, which is being used to map audio files and corresponding rttm files\n \"\"\"\n\n AUDIO_RTTM_MAP = {}\n with open(manifest, 'r') as inp_file:\n lines = inp_file.readlines()\n logging.info(\"Number of files to diarize: {}\".format(len(lines)))\n for line in lines:\n line = line.strip()\n dic = json.loads(line)\n\n meta = {\n 'audio_filepath': dic['audio_filepath'],\n 'rttm_filepath': dic.get('rttm_filepath', None),\n 'duration': dic.get('duration', None),\n 'text': dic.get('text', None),\n 'num_speakers': dic.get('num_speakers', None),\n 'uem_filepath': dic.get('uem_filepath', None),\n 'ctm_filepath': dic.get('ctm_filepath', None),\n }\n\n uniqname = get_uniqname_from_filepath(filepath=meta['audio_filepath'])\n\n if uniqname not in AUDIO_RTTM_MAP:\n AUDIO_RTTM_MAP[uniqname] = meta\n else:\n raise KeyError(\n \"file {} is already part AUDIO_RTTM_Map, it might be duplicated\".format(meta['audio_filepath'])\n )\n\n return AUDIO_RTTM_MAP\n\n\ndef parse_scale_configs(window_lengths_in_sec, shift_lengths_in_sec, multiscale_weights):\n \"\"\"\n Check whether multiscale parameters are provided correctly. window_lengths_in_sec, shift_lengfhs_in_sec and\n multiscale_weights should be all provided in omegaconf.listconfig.ListConfig type. In addition, the scales\n should be provided in descending order, from the longest scale to the base scale (the shortest).\n\n Example:\n Single-scale setting:\n parameters.window_length_in_sec=1.5\n parameters.shift_length_in_sec=0.75\n parameters.multiscale_weights=null\n\n Multiscale setting (base scale - window_length 0.5 s and shift_length 0.25):\n parameters.window_length_in_sec=[1.5,1.0,0.5]\n parameters.shift_length_in_sec=[0.75,0.5,0.25]\n parameters.multiscale_weights=[0.33,0.33,0.33]\n \"\"\"\n checkFloatConfig = [type(var) == float for var in (window_lengths_in_sec, shift_lengths_in_sec)]\n checkListConfig = [\n type(var) == type(omegaconf.listconfig.ListConfig([]))\n for var in (window_lengths_in_sec, shift_lengths_in_sec, multiscale_weights)\n ]\n if all(checkListConfig) or all(checkFloatConfig):\n\n # If bare floating numbers are provided, convert them to list format.\n if all(checkFloatConfig):\n window_lengths, shift_lengths, multiscale_weights = (\n [window_lengths_in_sec],\n [shift_lengths_in_sec],\n [1.0],\n )\n else:\n window_lengths, shift_lengths, multiscale_weights = (\n window_lengths_in_sec,\n shift_lengths_in_sec,\n multiscale_weights,\n )\n\n length_check = (\n len(set([len(window_lengths), len(shift_lengths), len(multiscale_weights)])) == 1\n and len(multiscale_weights) > 0\n )\n scale_order_check = (\n window_lengths == sorted(window_lengths)[::-1] and shift_lengths == sorted(shift_lengths)[::-1]\n )\n\n # Check whether window lengths are longer than shift lengths\n if len(window_lengths) > 1:\n shift_length_check = all([w > s for w, s in zip(window_lengths, shift_lengths)]) == True\n else:\n shift_length_check = window_lengths[0] > shift_lengths[0]\n\n multiscale_args_dict = {}\n if all([length_check, scale_order_check, shift_length_check]) == True:\n if len(window_lengths) > 1:\n multiscale_args_dict['scale_dict'] = {\n k: (w, s) for k, (w, s) in enumerate(zip(window_lengths, shift_lengths))\n }\n else:\n multiscale_args_dict['scale_dict'] = {0: (window_lengths[0], shift_lengths[0])}\n multiscale_args_dict['multiscale_weights'] = multiscale_weights\n return multiscale_args_dict\n else:\n raise ValueError('Multiscale parameters are not properly setup.')\n\n elif any(checkListConfig):\n raise ValueError(\n 'You must provide list config for all three parameters: window, shift and multiscale weights.'\n )\n else:\n return None\n\n\ndef get_embs_and_timestamps(multiscale_embeddings_and_timestamps, multiscale_args_dict):\n \"\"\"\n The embeddings and timestamps in multiscale_embeddings_and_timestamps dictionary are\n indexed by scale index. This function rearranges the extracted speaker embedding and\n timestamps by unique ID to make the further processing more convenient.\n\n Args:\n multiscale_embeddings_and_timestamps (dict):\n Dictionary of embeddings and timestamps for each scale.\n multiscale_args_dict (dict):\n Dictionary of scale information: window, shift and multiscale weights.\n\n Returns:\n embs_and_timestamps (dict)\n A dictionary containing embeddings and timestamps of each scale, indexed by unique ID.\n \"\"\"\n embs_and_timestamps = {\n uniq_id: {'multiscale_weights': [], 'scale_dict': {}}\n for uniq_id in multiscale_embeddings_and_timestamps[0][0].keys()\n }\n for scale_idx in sorted(multiscale_args_dict['scale_dict'].keys()):\n embeddings, time_stamps = multiscale_embeddings_and_timestamps[scale_idx]\n for uniq_id in embeddings.keys():\n embs_and_timestamps[uniq_id]['multiscale_weights'] = multiscale_args_dict['multiscale_weights']\n assert len(embeddings[uniq_id]) == len(time_stamps[uniq_id])\n embs_and_timestamps[uniq_id]['scale_dict'][scale_idx] = {\n 'embeddings': embeddings[uniq_id],\n 'time_stamps': time_stamps[uniq_id],\n }\n\n return embs_and_timestamps\n\n\ndef get_contiguous_stamps(stamps):\n \"\"\"\n Return contiguous time stamps\n \"\"\"\n lines = deepcopy(stamps)\n contiguous_stamps = []\n for i in range(len(lines) - 1):\n start, end, speaker = lines[i].split()\n next_start, next_end, next_speaker = lines[i + 1].split()\n if float(end) > float(next_start):\n avg = str((float(next_start) + float(end)) / 2.0)\n lines[i + 1] = ' '.join([avg, next_end, next_speaker])\n contiguous_stamps.append(start + \" \" + avg + \" \" + speaker)\n else:\n contiguous_stamps.append(start + \" \" + end + \" \" + speaker)\n start, end, speaker = lines[-1].split()\n contiguous_stamps.append(start + \" \" + end + \" \" + speaker)\n return contiguous_stamps\n\n\ndef merge_stamps(lines):\n \"\"\"\n merge time stamps of same speaker\n \"\"\"\n stamps = deepcopy(lines)\n overlap_stamps = []\n for i in range(len(stamps) - 1):\n start, end, speaker = stamps[i].split()\n next_start, next_end, next_speaker = stamps[i + 1].split()\n if float(end) == float(next_start) and speaker == next_speaker:\n stamps[i + 1] = ' '.join([start, next_end, next_speaker])\n else:\n overlap_stamps.append(start + \" \" + end + \" \" + speaker)\n\n start, end, speaker = stamps[-1].split()\n overlap_stamps.append(start + \" \" + end + \" \" + speaker)\n\n return overlap_stamps\n\n\ndef labels_to_pyannote_object(labels, uniq_name=''):\n \"\"\"\n converts labels to pyannote object to calculate DER and for visualization\n \"\"\"\n annotation = Annotation(uri=uniq_name)\n for label in labels:\n start, end, speaker = label.strip().split()\n start, end = float(start), float(end)\n annotation[Segment(start, end)] = speaker\n\n return annotation\n\n\ndef uem_timeline_from_file(uem_file, uniq_name=''):\n \"\"\"\n outputs pyannote timeline segments for uem file\n\n <UEM> file format\n UNIQ_SPEAKER_ID CHANNEL START_TIME END_TIME\n \"\"\"\n timeline = Timeline(uri=uniq_name)\n with open(uem_file, 'r') as f:\n lines = f.readlines()\n for line in lines:\n line = line.strip()\n speaker_id, channel, start_time, end_time = line.split()\n timeline.add(Segment(float(start_time), float(end_time)))\n\n return timeline\n\n\ndef labels_to_rttmfile(labels, uniq_id, out_rttm_dir):\n \"\"\"\n write rttm file with uniq_id name in out_rttm_dir with time_stamps in labels\n \"\"\"\n filename = os.path.join(out_rttm_dir, uniq_id + '.rttm')\n with open(filename, 'w') as f:\n for line in labels:\n line = line.strip()\n start, end, speaker = line.split()\n duration = float(end) - float(start)\n start = float(start)\n log = 'SPEAKER {} 1 {:.3f} {:.3f} <NA> <NA> {} <NA> <NA>\\n'.format(uniq_id, start, duration, speaker)\n f.write(log)\n\n return filename\n\n\ndef rttm_to_labels(rttm_filename):\n \"\"\"\n prepares time stamps label list from rttm file\n \"\"\"\n labels = []\n with open(rttm_filename, 'r') as f:\n for line in f.readlines():\n rttm = line.strip().split()\n start, end, speaker = float(rttm[3]), float(rttm[4]) + float(rttm[3]), rttm[7]\n labels.append('{} {} {}'.format(start, end, speaker))\n return labels\n\n\ndef write_cluster_labels(base_scale_idx, lines_cluster_labels, out_rttm_dir):\n \"\"\"\n\n Write cluster labels that are generated from clustering into a file.\n Args:\n base_scale_idx (int): The base scale index which is the highest scale index.\n lines_cluster_labels (list): The start and end time-stamps of each segment with the predicted cluster label.\n out_rttm_dir (str): The path where output rttm files are saved.\n \"\"\"\n out_label_name = os.path.join(\n out_rttm_dir, '../speaker_outputs', f'subsegments_scale{base_scale_idx}_cluster.label'\n )\n with open(out_label_name, 'w') as f:\n for clus_label_line in lines_cluster_labels:\n f.write(clus_label_line)\n\n\ndef perform_clustering(embs_and_timestamps, AUDIO_RTTM_MAP, out_rttm_dir, clustering_params):\n \"\"\"\n performs spectral clustering on embeddings with time stamps generated from VAD output\n\n Args:\n embs_and_timestamps (dict): This dictionary contains the following items indexed by unique IDs.\n 'embeddings' : Embeddings with key as unique_id\n 'time_stamps' : Time stamps list for each audio recording\n AUDIO_RTTM_MAP (dict): AUDIO_RTTM_MAP for mapping unique id with audio file path and rttm path\n out_rttm_dir (str): Path to write predicted rttms\n clustering_params (dict): clustering parameters provided through config that contains max_num_speakers (int),\n oracle_num_speakers (bool), max_rp_threshold(float), sparse_search_volume(int) and enhance_count_threshold (int)\n\n Returns:\n all_reference (list[uniq_name,Annotation]): reference annotations for score calculation\n all_hypothesis (list[uniq_name,Annotation]): hypothesis annotations for score calculation\n\n \"\"\"\n all_hypothesis = []\n all_reference = []\n no_references = False\n max_num_speakers = clustering_params['max_num_speakers']\n lines_cluster_labels = []\n\n cuda = True\n if not torch.cuda.is_available():\n logging.warning(\"cuda=False, using CPU for Eigen decompostion. This might slow down the clustering process.\")\n cuda = False\n\n for uniq_id, value in tqdm(AUDIO_RTTM_MAP.items()):\n if clustering_params.oracle_num_speakers:\n num_speakers = value.get('num_speakers', None)\n if num_speakers is None:\n raise ValueError(\"Provided option as oracle num of speakers but num_speakers in manifest is null\")\n else:\n num_speakers = None\n\n cluster_labels = COSclustering(\n uniq_embs_and_timestamps=embs_and_timestamps[uniq_id],\n oracle_num_speakers=num_speakers,\n max_num_speaker=max_num_speakers,\n enhanced_count_thres=clustering_params.enhanced_count_thres,\n max_rp_threshold=clustering_params.max_rp_threshold,\n sparse_search_volume=clustering_params.sparse_search_volume,\n cuda=cuda,\n )\n\n base_scale_idx = max(embs_and_timestamps[uniq_id]['scale_dict'].keys())\n lines = embs_and_timestamps[uniq_id]['scale_dict'][base_scale_idx]['time_stamps']\n assert len(cluster_labels) == len(lines)\n for idx, label in enumerate(cluster_labels):\n tag = 'speaker_' + str(label)\n lines[idx] += tag\n\n a = get_contiguous_stamps(lines)\n labels = merge_stamps(a)\n if out_rttm_dir:\n labels_to_rttmfile(labels, uniq_id, out_rttm_dir)\n lines_cluster_labels.extend([f'{uniq_id} {seg_line}\\n' for seg_line in lines])\n hypothesis = labels_to_pyannote_object(labels, uniq_name=uniq_id)\n all_hypothesis.append([uniq_id, hypothesis])\n\n rttm_file = value.get('rttm_filepath', None)\n if rttm_file is not None and os.path.exists(rttm_file) and not no_references:\n ref_labels = rttm_to_labels(rttm_file)\n reference = labels_to_pyannote_object(ref_labels, uniq_name=uniq_id)\n all_reference.append([uniq_id, reference])\n else:\n no_references = True\n all_reference = []\n\n if out_rttm_dir:\n write_cluster_labels(base_scale_idx, lines_cluster_labels, out_rttm_dir)\n\n return all_reference, all_hypothesis\n\n\ndef score_labels(AUDIO_RTTM_MAP, all_reference, all_hypothesis, collar=0.25, ignore_overlap=True):\n \"\"\"\n calculates DER, CER, FA and MISS\n\n Args:\n AUDIO_RTTM_MAP : Dictionary containing information provided from manifestpath\n all_reference (list[uniq_name,Annotation]): reference annotations for score calculation\n all_hypothesis (list[uniq_name,Annotation]): hypothesis annotations for score calculation\n\n Returns:\n metric (pyannote.DiarizationErrorRate): Pyannote Diarization Error Rate metric object. This object contains detailed scores of each audiofile.\n mapping (dict): Mapping dict containing the mapping speaker label for each audio input\n\n < Caveat >\n Unlike md-eval.pl, \"no score\" collar in pyannote.metrics is the maximum length of\n \"no score\" collar from left to right. Therefore, if 0.25s is applied for \"no score\"\n collar in md-eval.pl, 0.5s should be applied for pyannote.metrics.\n\n \"\"\"\n metric = None\n if len(all_reference) == len(all_hypothesis):\n metric = DiarizationErrorRate(collar=2 * collar, skip_overlap=ignore_overlap)\n\n mapping_dict = {}\n for (reference, hypothesis) in zip(all_reference, all_hypothesis):\n ref_key, ref_labels = reference\n _, hyp_labels = hypothesis\n uem = AUDIO_RTTM_MAP[ref_key].get('uem_filepath', None)\n if uem is not None:\n uem = uem_timeline_from_file(uem_file=uem, uniq_name=ref_key)\n metric(ref_labels, hyp_labels, uem=uem, detailed=True)\n mapping_dict[ref_key] = metric.optimal_mapping(ref_labels, hyp_labels)\n\n DER = abs(metric)\n CER = metric['confusion'] / metric['total']\n FA = metric['false alarm'] / metric['total']\n MISS = metric['missed detection'] / metric['total']\n\n logging.info(\n \"Cumulative Results for collar {} sec and ignore_overlap {}: \\n FA: {:.4f}\\t MISS {:.4f}\\t \\\n Diarization ER: {:.4f}\\t, Confusion ER:{:.4f}\".format(\n collar, ignore_overlap, FA, MISS, DER, CER\n )\n )\n\n return metric, mapping_dict\n else:\n logging.warning(\n \"check if each ground truth RTTMs were present in provided manifest file. Skipping calculation of Diariazation Error Rate\"\n )\n\n return None\n\n\ndef write_rttm2manifest(AUDIO_RTTM_MAP, manifest_file):\n \"\"\"\n writes manifest file based on rttm files (or vad table out files). This manifest file would be used by \n speaker diarizer to compute embeddings and cluster them. This function also takes care of overlap time stamps\n\n Args:\n AUDIO_RTTM_MAP: dict containing keys to uniqnames, that contains audio filepath and rttm_filepath as its contents,\n these are used to extract oracle vad timestamps.\n manifest (str): path to write manifest file\n\n Returns:\n manifest (str): path to write manifest file\n \"\"\"\n\n with open(manifest_file, 'w') as outfile:\n for key in AUDIO_RTTM_MAP:\n rttm_filename = AUDIO_RTTM_MAP[key]['rttm_filepath']\n if rttm_filename and os.path.exists(rttm_filename):\n f = open(rttm_filename, 'r')\n else:\n raise FileNotFoundError(\n \"Requested to construct manifest from rttm with oracle VAD option or from NeMo VAD but received filename as {}\".format(\n rttm_filename\n )\n )\n\n audio_path = AUDIO_RTTM_MAP[key]['audio_filepath']\n if AUDIO_RTTM_MAP[key].get('duration', None):\n max_duration = AUDIO_RTTM_MAP[key]['duration']\n else:\n sound = sf.SoundFile(audio_path)\n max_duration = sound.frames / sound.samplerate\n\n lines = f.readlines()\n time_tup = (-1, -1)\n for line in lines:\n vad_out = line.strip().split()\n if len(vad_out) > 3:\n start, dur, _ = float(vad_out[3]), float(vad_out[4]), vad_out[7]\n else:\n start, dur, _ = float(vad_out[0]), float(vad_out[1]), vad_out[2]\n start, dur = float(\"{:.3f}\".format(start)), float(\"{:.3f}\".format(dur))\n\n if start == 0 and dur == 0: # No speech segments\n continue\n else:\n\n if time_tup[0] >= 0 and start > time_tup[1]:\n dur2 = float(\"{:.3f}\".format(time_tup[1] - time_tup[0]))\n if time_tup[0] < max_duration and dur2 > 0:\n meta = {\n \"audio_filepath\": audio_path,\n \"offset\": time_tup[0],\n \"duration\": dur2,\n \"label\": 'UNK',\n }\n json.dump(meta, outfile)\n outfile.write(\"\\n\")\n else:\n logging.warning(\n \"RTTM label has been truncated since start is greater than duration of audio file\"\n )\n time_tup = (start, start + dur)\n else:\n if time_tup[0] == -1:\n end_time = start + dur\n if end_time > max_duration:\n end_time = max_duration\n time_tup = (start, end_time)\n else:\n end_time = max(time_tup[1], start + dur)\n if end_time > max_duration:\n end_time = max_duration\n time_tup = (min(time_tup[0], start), end_time)\n dur2 = float(\"{:.3f}\".format(time_tup[1] - time_tup[0]))\n if time_tup[0] < max_duration and dur2 > 0:\n meta = {\"audio_filepath\": audio_path, \"offset\": time_tup[0], \"duration\": dur2, \"label\": 'UNK'}\n json.dump(meta, outfile)\n outfile.write(\"\\n\")\n else:\n logging.warning(\"RTTM label has been truncated since start is greater than duration of audio file\")\n f.close()\n return manifest_file\n\n\ndef segments_manifest_to_subsegments_manifest(\n segments_manifest_file: str,\n subsegments_manifest_file: str = None,\n window: float = 1.5,\n shift: float = 0.75,\n min_subsegment_duration: float = 0.05,\n):\n \"\"\"\n Generate subsegments manifest from segments manifest file\n Args\n input:\n segments_manifest file (str): path to segments manifest file, typically from VAD output\n subsegments_manifest_file (str): path to output subsegments manifest file (default (None) : writes to current working directory)\n window (float): window length for segments to subsegments length\n shift (float): hop length for subsegments shift\n min_subsegments_duration (float): exclude subsegments smaller than this duration value\n\n output:\n returns path to subsegment manifest file\n \"\"\"\n if subsegments_manifest_file is None:\n pwd = os.getcwd()\n subsegments_manifest_file = os.path.join(pwd, 'subsegments.json')\n\n with open(segments_manifest_file, 'r') as segments_manifest, open(\n subsegments_manifest_file, 'w'\n ) as subsegments_manifest:\n segments = segments_manifest.readlines()\n for segment in segments:\n segment = segment.strip()\n dic = json.loads(segment)\n audio, offset, duration, label = dic['audio_filepath'], dic['offset'], dic['duration'], dic['label']\n subsegments = get_subsegments(offset=offset, window=window, shift=shift, duration=duration)\n\n for subsegment in subsegments:\n start, dur = subsegment\n if dur > min_subsegment_duration:\n meta = {\"audio_filepath\": audio, \"offset\": start, \"duration\": dur, \"label\": label}\n json.dump(meta, subsegments_manifest)\n subsegments_manifest.write(\"\\n\")\n\n return subsegments_manifest_file\n\n\ndef get_subsegments(offset: float, window: float, shift: float, duration: float):\n \"\"\"\n return subsegments from a segment of audio file\n Args\n input:\n offset (float): start time of audio segment\n window (float): window length for segments to subsegments length\n shift (float): hop length for subsegments shift\n duration (float): duration of segment\n output:\n subsegments (List[tuple[float, float]]): subsegments generated for the segments as list of tuple of start and duration of each subsegment\n \"\"\"\n subsegments = []\n start = offset\n slice_end = start + duration\n base = math.ceil((duration - window) / shift)\n slices = 1 if base < 0 else base + 1\n for slice_id in range(slices):\n end = start + window\n if end > slice_end:\n end = slice_end\n subsegments.append((start, end - start))\n start = offset + (slice_id + 1) * shift\n\n return subsegments\n\n\ndef embedding_normalize(embs, use_std=False, eps=1e-10):\n \"\"\"\n mean and l2 length normalize the input speaker embeddings\n input:\n embs: embeddings of shape (Batch,emb_size)\n output:\n embs: normalized embeddings of shape (Batch,emb_size)\n \"\"\"\n embs = embs - embs.mean(axis=0)\n if use_std:\n embs = embs / (embs.std(axis=0) + eps)\n embs_l2_norm = np.expand_dims(np.linalg.norm(embs, ord=2, axis=-1), axis=1)\n embs = embs / embs_l2_norm\n\n return embs\n", "# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n# Copyright 2017 Johns Hopkins University (Shinji Watanabe)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"\nPart of this code is adopted from https://github.com/espnet/espnet\n\"\"\"\n\nimport math\n\nimport torch\nimport torch.nn as nn\n\n__all__ = [\n 'RelPositionMultiHeadAttention',\n 'RelPositionalEncoding',\n 'PositionalEncoding',\n]\n\n\nclass MultiHeadAttention(nn.Module):\n \"\"\"Multi-Head Attention layer of Transformer.\n Args:\n n_head (int): number of heads\n n_feat (int): size of the features\n dropout_rate (float): dropout rate\n \"\"\"\n\n def __init__(self, n_head, n_feat, dropout_rate):\n \"\"\"Construct an MultiHeadedAttention object.\"\"\"\n super(MultiHeadAttention, self).__init__()\n assert n_feat % n_head == 0\n # We assume d_v always equals d_k\n self.d_k = n_feat // n_head\n self.s_d_k = math.sqrt(self.d_k)\n self.h = n_head\n self.linear_q = nn.Linear(n_feat, n_feat)\n self.linear_k = nn.Linear(n_feat, n_feat)\n self.linear_v = nn.Linear(n_feat, n_feat)\n self.linear_out = nn.Linear(n_feat, n_feat)\n self.dropout = nn.Dropout(p=dropout_rate)\n\n def forward_qkv(self, query, key, value):\n \"\"\"Transforms query, key and value.\n Args:\n query (torch.Tensor): (batch, time1, size)\n key (torch.Tensor): (batch, time2, size)\n value (torch.Tensor): (batch, time2, size)\n returns:\n q (torch.Tensor): (batch, head, time1, size)\n k (torch.Tensor): (batch, head, time2, size)\n v (torch.Tensor): (batch, head, time2, size)\n \"\"\"\n n_batch = query.size(0)\n q = self.linear_q(query).view(n_batch, -1, self.h, self.d_k)\n k = self.linear_k(key).view(n_batch, -1, self.h, self.d_k)\n v = self.linear_v(value).view(n_batch, -1, self.h, self.d_k)\n q = q.transpose(1, 2)\n k = k.transpose(1, 2)\n v = v.transpose(1, 2)\n\n return q, k, v\n\n def forward_attention(self, value, scores, mask):\n \"\"\"Compute attention context vector.\n Args:\n value (torch.Tensor): (batch, time2, size)\n scores(torch.Tensor): (batch, time1, time2)\n mask(torch.Tensor): (batch, time1, time2)\n returns:\n value (torch.Tensor): transformed `value` (batch, time2, d_model) weighted by the attention scores\n \"\"\"\n n_batch = value.size(0)\n if mask is not None:\n mask = mask.unsqueeze(1) # (batch, 1, time1, time2)\n scores = scores.masked_fill(mask, -10000.0)\n attn = torch.softmax(scores, dim=-1).masked_fill(mask, 0.0) # (batch, head, time1, time2)\n else:\n attn = torch.softmax(scores, dim=-1) # (batch, head, time1, time2)\n\n p_attn = self.dropout(attn)\n x = torch.matmul(p_attn, value) # (batch, head, time1, d_k)\n x = x.transpose(1, 2).reshape(n_batch, -1, self.h * self.d_k) # (batch, time1, d_model)\n\n return self.linear_out(x) # (batch, time1, d_model)\n\n def forward(self, query, key, value, mask, pos_emb=None):\n \"\"\"Compute 'Scaled Dot Product Attention'.\n Args:\n query (torch.Tensor): (batch, time1, size)\n key (torch.Tensor): (batch, time2, size)\n value(torch.Tensor): (batch, time2, size)\n mask (torch.Tensor): (batch, time1, time2)\n returns:\n output (torch.Tensor): transformed `value` (batch, time1, d_model) weighted by the query dot key attention\n \"\"\"\n q, k, v = self.forward_qkv(query, key, value)\n scores = torch.matmul(q, k.transpose(-2, -1)) / self.s_d_k\n return self.forward_attention(v, scores, mask)\n\n\nclass RelPositionMultiHeadAttention(MultiHeadAttention):\n \"\"\"Multi-Head Attention layer of Transformer-XL with support of relative positional encoding.\n Paper: https://arxiv.org/abs/1901.02860\n Args:\n n_head (int): number of heads\n n_feat (int): size of the features\n dropout_rate (float): dropout rate\n \"\"\"\n\n def __init__(self, n_head, n_feat, dropout_rate, pos_bias_u, pos_bias_v):\n \"\"\"Construct an RelPositionMultiHeadedAttention object.\"\"\"\n super().__init__(n_head, n_feat, dropout_rate)\n # linear transformation for positional encoding\n self.linear_pos = nn.Linear(n_feat, n_feat, bias=False)\n # these two learnable biases are used in matrix c and matrix d\n # as described in https://arxiv.org/abs/1901.02860 Section 3.3\n if pos_bias_u is None or pos_bias_v is None:\n self.pos_bias_u = nn.Parameter(torch.FloatTensor(self.h, self.d_k))\n self.pos_bias_v = nn.Parameter(torch.FloatTensor(self.h, self.d_k))\n # nn.init.normal_(self.pos_bias_u, 0.0, 0.02)\n # nn.init.normal_(self.pos_bias_v, 0.0, 0.02)\n nn.init.zeros_(self.pos_bias_u)\n nn.init.zeros_(self.pos_bias_v)\n else:\n self.pos_bias_u = pos_bias_u\n self.pos_bias_v = pos_bias_v\n\n def rel_shift(self, x):\n \"\"\"Compute relative positional encoding.\n Args:\n x (torch.Tensor): (batch, nheads, time, 2*time-1)\n \"\"\"\n b, h, qlen, pos_len = x.size() # (b, h, t1, t2)\n # need to add a column of zeros on the left side of last dimension to perform the relative shifting\n x = torch.nn.functional.pad(x, pad=(1, 0)) # (b, h, t1, t2+1)\n x = x.view(b, h, -1, qlen) # (b, h, t2+1, t1)\n # need to drop the first row\n x = x[:, :, 1:].view(b, h, qlen, pos_len) # (b, h, t1, t2)\n return x\n\n def forward(self, query, key, value, mask, pos_emb):\n \"\"\"Compute 'Scaled Dot Product Attention' with rel. positional encoding.\n Args:\n query (torch.Tensor): (batch, time1, size)\n key (torch.Tensor): (batch, time2, size)\n value(torch.Tensor): (batch, time2, size)\n mask (torch.Tensor): (batch, time1, time2)\n pos_emb (torch.Tensor) : (batch, time1, size)\n Returns:\n output (torch.Tensor): transformed `value` (batch, time1, d_model) weighted by the query dot key attention\n \"\"\"\n q, k, v = self.forward_qkv(query, key, value)\n q = q.transpose(1, 2) # (batch, time1, head, d_k)\n\n n_batch_pos = pos_emb.size(0)\n p = self.linear_pos(pos_emb).view(n_batch_pos, -1, self.h, self.d_k)\n p = p.transpose(1, 2) # (batch, head, time1, d_k)\n\n # (batch, head, time1, d_k)\n q_with_bias_u = (q + self.pos_bias_u).transpose(1, 2)\n # (batch, head, time1, d_k)\n q_with_bias_v = (q + self.pos_bias_v).transpose(1, 2)\n\n # compute attention score\n # first compute matrix a and matrix c\n # as described in https://arxiv.org/abs/1901.02860 Section 3.3\n # (batch, head, time1, time2)\n matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1))\n\n # compute matrix b and matrix d\n # (batch, head, time1, time2)\n matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1))\n matrix_bd = self.rel_shift(matrix_bd)\n # drops extra elements in the matrix_bd to match the matrix_ac's size\n matrix_bd = matrix_bd[:, :, :, : matrix_ac.size(-1)]\n\n scores = (matrix_ac + matrix_bd) / self.s_d_k # (batch, head, time1, time2)\n\n return self.forward_attention(v, scores, mask)\n\n\nclass PositionalEncoding(torch.nn.Module):\n \"\"\"Fixed sinusoidal positional encoding.\n Args:\n d_model (int): embedding dim\n dropout_rate (float): dropout rate\n max_len (int): maximum input length\n xscale (bool): whether to scale the input by sqrt(d_model)\n dropout_rate_emb (float): dropout rate for the positional embeddings\n \"\"\"\n\n def __init__(self, d_model, dropout_rate, max_len=5000, xscale=None, dropout_rate_emb=0.0):\n \"\"\"Construct an PositionalEncoding object.\"\"\"\n super(PositionalEncoding, self).__init__()\n self.d_model = d_model\n self.xscale = xscale\n self.dropout = torch.nn.Dropout(p=dropout_rate)\n self.max_len = max_len\n if dropout_rate_emb > 0:\n self.dropout_emb = nn.Dropout(dropout_rate_emb)\n else:\n self.dropout_emb = None\n\n def create_pe(self, positions):\n pos_length = positions.size(0)\n pe = torch.zeros(pos_length, self.d_model, device=positions.device)\n div_term = torch.exp(\n torch.arange(0, self.d_model, 2, dtype=torch.float32, device=positions.device)\n * -(math.log(10000.0) / self.d_model)\n )\n pe[:, 0::2] = torch.sin(positions * div_term)\n pe[:, 1::2] = torch.cos(positions * div_term)\n pe = pe.unsqueeze(0)\n if hasattr(self, 'pe'):\n self.pe = pe\n else:\n self.register_buffer('pe', pe, persistent=False)\n\n def extend_pe(self, length, device):\n \"\"\"Reset and extend the positional encodings if needed.\"\"\"\n if hasattr(self, 'pe') and self.pe.size(1) >= length:\n return\n positions = torch.arange(0, length, dtype=torch.float32, device=device).unsqueeze(1)\n self.create_pe(positions=positions)\n\n def forward(self, x: torch.Tensor):\n \"\"\"Adds positional encoding.\n Args:\n x (torch.Tensor): Input. Its shape is (batch, time, feature_size)\n Returns:\n x+pos_emb (torch.Tensor): Its shape is (batch, time, feature_size)\n pos_emb (torch.Tensor): Its shape is (1, time, feature_size)\n \"\"\"\n if self.xscale:\n x = x * self.xscale\n pos_emb = self.pe[:, : x.size(1)]\n if self.dropout_emb:\n pos_emb = self.dropout_emb(pos_emb)\n x = x + pos_emb\n return self.dropout(x), pos_emb\n\n\nclass RelPositionalEncoding(PositionalEncoding):\n \"\"\"Relative positional encoding for TransformerXL's layers\n See : Appendix B in https://arxiv.org/abs/1901.02860\n Args:\n d_model (int): embedding dim\n dropout_rate (float): dropout rate\n max_len (int): maximum input length\n xscale (bool): whether to scale the input by sqrt(d_model)\n dropout_rate_emb (float): dropout rate for the positional embeddings\n \"\"\"\n\n def extend_pe(self, length, device):\n \"\"\"Reset and extend the positional encodings if needed.\"\"\"\n needed_size = 2 * length - 1\n if hasattr(self, 'pe') and self.pe.size(1) >= needed_size:\n return\n # positions would be from negative numbers to positive\n # positive positions would be used for left positions and negative for right positions\n positions = torch.arange(length - 1, -length, -1, dtype=torch.float32, device=device).unsqueeze(1)\n self.create_pe(positions=positions)\n self.center_pos = torch.tensor(self.pe.size(1) // 2 + 1, dtype=torch.int32, device=device)\n\n def forward(self, x):\n \"\"\"Compute positional encoding.\n Args:\n x (torch.Tensor): Input. Its shape is (batch, time, feature_size)\n Returns:\n x (torch.Tensor): Its shape is (batch, time, feature_size)\n pos_emb (torch.Tensor): Its shape is (1, time, feature_size)\n \"\"\"\n\n if self.xscale:\n x = x * self.xscale\n\n # center_pos would be the index of position 0\n # negative positions would be used for right and positive for left tokens\n # for input of length L, 2*L-1 positions are needed, positions from (L-1) to -(L-1)\n start_pos = self.center_pos - x.size(1)\n end_pos = self.center_pos + x.size(1) - 1\n pos_emb = self.pe[:, start_pos:end_pos]\n if self.dropout_emb:\n pos_emb = self.dropout_emb(pos_emb)\n return self.dropout(x), pos_emb\n", "# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Copyright (c) 2020, Xiaomi CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport struct\nfrom pickle import UnpicklingError\nfrom typing import List, Optional, Tuple, Union\n\nimport torch\n\nfrom nemo.utils import logging\n\n# use k2 import guard\n# fmt: off\nfrom nemo.core.utils.k2_utils import k2_import_guard # isort:skip\nk2_import_guard()\nimport k2 # isort:skip\n# fmt: on\n\n\ndef create_supervision(input_lengths: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Creates a special supervisions tensor from input lengths.\n These supervisions are required for some k2 methods.\n \"\"\"\n supervisions = torch.stack(\n (torch.tensor(range(input_lengths.shape[0])), torch.zeros(input_lengths.shape[0]), input_lengths.cpu(),), 1,\n ).to(dtype=torch.int32)\n # the duration column has to be sorted in decreasing order\n order = torch.argsort(supervisions[:, -1], descending=True).to(dtype=torch.int32)\n return supervisions[order.to(dtype=torch.long)], order\n\n\ndef invert_permutation(indices: torch.Tensor) -> torch.Tensor:\n \"\"\"Produces a tensor of reverse permutation for a given indices.\n \n Based on https://github.com/k2-fsa/snowfall/blob/master/snowfall/common.py\n \"\"\"\n ans = torch.zeros(indices.shape, device=indices.device, dtype=indices.dtype)\n ans[indices.to(dtype=torch.long)] = torch.arange(0, indices.shape[0], device=indices.device, dtype=indices.dtype)\n return ans\n\n\ndef make_blank_first(\n blank_idx: int, log_probs: torch.Tensor, targets: torch.Tensor\n) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Puts blank logits at the first place in input log_probs tensor.\n \"\"\"\n index = list(range(log_probs.shape[-1]))\n del index[blank_idx]\n index = torch.tensor([blank_idx] + index).to(log_probs.device)\n new_log_probs = torch.index_select(log_probs, -1, index)\n # TODO (alaptev): replace targets + 1 with torch.where to work for non-last blank_id\n return new_log_probs, None if targets is None else targets + 1\n\n\ndef load_graph(graph_path: str) -> 'k2.Fsa':\n \"\"\"Fsa graph loading helper function. Loads graphs stored in different formats.\n \"\"\"\n if os.path.exists(graph_path):\n errors = []\n try:\n graph_dict = torch.load(graph_path, map_location=\"cpu\")\n graph = k2.Fsa.from_dict(graph_dict)\n return graph\n except UnpicklingError as e:\n errors.append(e)\n with open(graph_path, \"rt\", encoding=\"utf-8\") as f:\n graph_txt = f.read()\n # order from the most frequent case to the least\n for func, acceptor in [(k2.Fsa.from_openfst, False), (k2.Fsa.from_str, True), (k2.Fsa.from_str, False)]:\n try:\n graph = func(graph_txt, acceptor=acceptor)\n return graph\n except (TypeError, ValueError, RuntimeError) as e:\n errors.append(e)\n raise Exception(errors)\n else:\n logging.warning(f\"\"\"No such file: '{graph_path}'\"\"\")\n return None\n\n\ndef intersect_with_self_loops(base_graph: 'k2.Fsa', aux_graph: 'k2.Fsa') -> 'k2.Fsa':\n \"\"\"Intersection helper function.\n \"\"\"\n assert hasattr(base_graph, \"aux_labels\")\n assert not hasattr(aux_graph, \"aux_labels\")\n aux_graph_with_self_loops = k2.arc_sort(k2.add_epsilon_self_loops(aux_graph)).to(base_graph.device)\n result = k2.intersect(k2.arc_sort(base_graph), aux_graph_with_self_loops, treat_epsilons_specially=False,)\n setattr(result, \"phones\", result.labels)\n return result\n\n\ndef compose_with_self_loops(base_graph: 'k2.Fsa', aux_graph: 'k2.Fsa') -> 'k2.Fsa':\n \"\"\"Composition helper function.\n \"\"\"\n aux_graph_with_self_loops = k2.arc_sort(k2.add_epsilon_self_loops(aux_graph)).to(base_graph.device)\n return k2.compose(base_graph, aux_graph_with_self_loops, treat_epsilons_specially=False, inner_labels=\"phones\",)\n\n\ndef create_sparse_wrapped(\n indices: List[torch.Tensor],\n values: torch.Tensor,\n size: Optional[Union[Tuple[int, int], Tuple[int, int, int]]] = None,\n min_col_index: Optional[int] = None,\n) -> torch.Tensor:\n \"\"\"Wraps up k2.create_sparse to create 2- or 3-dimensional sparse tensors.\n \"\"\"\n assert size is None or len(indices) == len(size)\n\n if len(indices) == 2:\n return k2.create_sparse(\n rows=indices[0], cols=indices[1], values=values, size=size, min_col_index=min_col_index,\n )\n elif len(indices) == 3:\n assert indices[0].ndim == indices[1].ndim == indices[2].ndim == 1\n assert indices[0].numel() == indices[1].numel() == indices[2].numel() == values.numel()\n\n if min_col_index is not None:\n assert isinstance(min_col_index, int)\n kept_indices = indices[-1] >= min_col_index\n indices = [i[kept_indices] for i in indices]\n values = values[kept_indices]\n if size is not None:\n return torch.sparse_coo_tensor(\n torch.stack(indices), values, size=size, device=values.device, requires_grad=values.requires_grad,\n )\n else:\n return torch.sparse_coo_tensor(\n torch.stack(indices), values, device=values.device, requires_grad=values.requires_grad,\n )\n else:\n raise ValueError(f\"len(indices) = {len(indices)}\")\n\n\ndef prep_padded_densefsavec(log_softmax: torch.Tensor, supervisions: torch.Tensor) -> 'k2.DenseFsaVec':\n \"\"\"Performs special epsilon-padding required for composition with some of the topologies.\n \"\"\"\n log_softmax_shifted = torch.cat(\n [\n torch.full((log_softmax.shape[0], log_softmax.shape[1], 1), -float(\"inf\"), device=log_softmax.device,),\n log_softmax,\n ],\n axis=-1,\n )\n log_softmax_padded = torch.zeros(\n (log_softmax_shifted.shape[0], log_softmax_shifted.shape[1] * 2, log_softmax_shifted.shape[2],),\n device=log_softmax.device,\n )\n log_softmax_padded[:, ::2] = log_softmax_shifted\n supervisions_padded = supervisions.clone()\n supervisions_padded[:, 2] *= 2\n dense_log_softmax_padded = k2.DenseFsaVec(log_softmax_padded, supervisions_padded)\n return dense_log_softmax_padded\n\n\ndef shift_labels_inpl(lattices: List['k2.Fsa'], shift: int):\n \"\"\"Shifts lattice labels and aux_labels by a given number. This is an in-place operation.\n \"\"\"\n for lattice in lattices:\n mask = lattice.labels > 0\n lattice.labels[mask] += shift\n if hasattr(lattice, \"aux_labels\"):\n mask = lattice.aux_labels > 0\n lattice.aux_labels[mask] += shift\n return lattices\n\n\ndef get_arc_weights(graph: 'k2.Fsa') -> torch.Tensor:\n \"\"\"Returns 1d torch.Tensor with arc weights of a given graph.\n \"\"\"\n if len(graph.shape) > 2:\n raise NotImplementedError(\"FsaVec is not supported at the moment.\")\n weights_int = graph.arcs_as_tensor()[:, -1].tolist()\n weights_float = struct.unpack('%sf' % len(weights_int), struct.pack('%si' % len(weights_int), *weights_int))\n return torch.Tensor(weights_float)\n\n\ndef get_tot_objf_and_finite_mask(tot_scores: torch.Tensor, reduction: str) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Figures out the total score(log-prob) over all successful supervision segments\n (i.e. those for which the total score wasn't -infinity).\n Args:\n tot_scores: a Torch tensor of shape (num_segments,) containing total scores\n from forward-backward\n reduction: a reduction type ('mean', 'sum' or 'none')\n Returns:\n Returns a tuple of 2 scalar tensors: (tot_score, finite_mask)\n where finite_mask is a tensor containing successful segment mask.\n \n Based on get_tot_objf_and_num_frames\n from https://github.com/k2-fsa/snowfall/blob/master/snowfall/objectives/common.py\n \"\"\"\n finite_mask = ~torch.isnan(tot_scores) & torch.ne(tot_scores, -float(\"inf\"))\n if reduction == \"mean\":\n tot_scores = tot_scores[finite_mask].mean()\n elif reduction == \"sum\":\n tot_scores = tot_scores[finite_mask].sum()\n return tot_scores, finite_mask\n" ]
[ [ "torch.nn.ModuleList", "torch.distributed.is_initialized", "torch.utils.data.DataLoader", "torch.count_nonzero", "numpy.concatenate", "numpy.argmax", "torch.distributed.get_rank", "torch.argmax" ], [ "torch.cat", "torch.manual_seed", "torch.from_numpy", "torch.cuda.amp.autocast", "torch.set_grad_enabled", "torch.no_grad", "torch.unbind", "numpy.array" ], [ "torch.nn.BatchNorm1d", "torch.nn.functional.softmax", "torch.mean", "torch.ones", "torch.cat", "torch.sum", "torch.arange", "torch.nn.Sigmoid", "torch.nn.Tanh", "torch.nn.Conv1d", "torch.nn.ReLU" ], [ "torch.set_grad_enabled", "torch.inference_mode", "torch.cuda.is_available", "torch.cuda.amp.autocast" ], [ "numpy.where", "numpy.cumsum" ], [ "pandas.read_table" ], [ "torch.einsum", "torch.arange", "torch.log_softmax", "torch.matmul", "torch.diag", "torch.ones_like" ], [ "numpy.linalg.norm", "torch.cuda.is_available" ], [ "torch.cos", "torch.nn.Dropout", "torch.softmax", "torch.zeros", "torch.sin", "torch.arange", "torch.nn.Linear", "torch.matmul", "torch.FloatTensor", "torch.nn.init.zeros_", "torch.nn.functional.pad" ], [ "torch.Tensor", "torch.zeros", "torch.load", "torch.isnan", "torch.tensor", "torch.arange", "torch.stack", "torch.argsort", "torch.index_select" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Ipuch/bioptim_exo
[ "a954102a9aad1e2bd5227562aef9571e24a7378d" ]
[ "data/load_events.py" ]
[ "import ezc3d\nfrom pyomeca import Markers\nimport numpy as np\n\n\nclass LoadEvent:\n def __init__(self, c3d_path: str):\n self.c3d_path = c3d_path\n self.c3d = ezc3d.c3d(c3d_path)\n\n def get_time(self, idx: int) -> np.ndarray:\n \"\"\"\n find the time corresponding to the event\n\n Parameters:\n ---------\n\n idx: int\n index number of the event\n\n Returns\n --------\n event_values : ndarray\n array with the time value in seconds\n\n \"\"\"\n event_time = self.c3d[\"parameters\"][\"EVENT\"][\"TIMES\"][\"value\"][1][idx]\n return np.array(event_time)\n\n def get_frame(self, idx: int) -> np.ndarray:\n \"\"\"\n find the frame corresponding to the event\n\n Parameters:\n ---------\n\n idx: int\n index number of the event\n\n Returns\n --------\n event_values : ndarray\n array with the frame number\n\n \"\"\"\n frame_rate = self.c3d[\"parameters\"][\"TRIAL\"][\"CAMERA_RATE\"][\"value\"][0]\n frame = round(self.get_time(idx) * frame_rate)\n start_frame = self.c3d[\"parameters\"][\"TRIAL\"][\"ACTUAL_START_FIELD\"][\"value\"][0]\n event_frame = frame - start_frame\n return np.array(event_frame)\n\n def get_markers(self, idx: int) -> np.ndarray:\n \"\"\"\n find the position of each marker during an event\n\n Parameters:\n ---------\n\n idx: int\n index number of the event\n\n Returns\n --------\n event_values : ndarray\n array with the position along three axes of each marker in millimeters\n\n \"\"\"\n\n markers = Markers.from_c3d(self.c3d_path, prefix_delimiter=\":\").to_numpy()\n event_markers = markers[:3, :, self.get_frame(idx)]\n return event_markers\n\n def get_event(self, idx: int) -> dict:\n \"\"\"\n find the time, the frame and the position of each marker during an event\n\n Parameters:\n ---------\n\n idx: int\n index number of the event\n\n Returns\n --------\n event_values : dict\n dictionary containing the time, the frame and the positions of each marker for the event corresponding to\n the given index\n\n \"\"\"\n\n event_values = {\"time\": self.get_time(idx), \"frame\": self.get_frame(idx), \"markers\": self.get_markers(idx)}\n\n return event_values\n\n\nc3d_events = LoadEvent(\"../event_tracking/F0_tete_05.c3d\")\nprint(c3d_events.get_markers(0))\nprint(c3d_events.get_frame(0))\nprint(c3d_events.get_time(0))\nprint(c3d_events.get_event(0))" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sy2616/DATA
[ "8d2314b23c9757c8f54a85a01b451aaa29054912", "8d2314b23c9757c8f54a85a01b451aaa29054912" ]
[ "poken/train_schetch.py", "CIFA10/resnet.py" ]
[ "import torch\nimport torchvision\nfrom torch import optim,nn\nimport visdom\nfrom torch.utils.data import DataLoader\nfrom poken import Pokemon\nfrom resnet import Resnet18\n\nbatchsz=32\nlr=1e-3\nepochs=10\ndevice=torch.device('cuda' if torch.cuda.is_available() else 'cpu')\ntorch.manual_seed(1234)\ntrain_db=Pokemon('D:\\BaiduNetdiskDownload\\pokemon\\pokeman',224,mode='train')\nval_db=Pokemon('D:\\BaiduNetdiskDownload\\pokemon\\pokeman',224,mode='val')\ntest_db=Pokemon('D:\\BaiduNetdiskDownload\\pokemon\\pokeman',224,mode='test')\ntrain_loader=DataLoader(train_db,batch_size=batchsz,shuffle=True,\n num_workers=4)\nval_loader=DataLoader(val_db,batch_size=batchsz,num_workers=2)\ntest_loader=DataLoader(test_db,batch_size=batchsz,num_workers=2)\nviz=visdom.Visdom()\ndef evalute(model,loader):\n corret=0\n total=len(loader.dataset)\n for x,y in loader:\n x,y=x.to(device),y.to(device)\n with torch.no_grad():\n logits=model(x)\n pred=logits.argmax(dim=1)\n corret+=torch.eq(pred,y).sum().float().item()\n return corret/total\n\ndef main():\n model=Resnet18(5).to(device)\n optimizer=optim.Adam(model.parameters(),lr=lr)\n criten=nn.CrossEntropyLoss()\n best_acc,best_epoch=0,0\n global_step=0\n viz.line([0],[-1],win='loss',opts=dict(title='loss'))\n viz.line([0],[-1],win='val_acc',opts=dict(title='val_acc'))\n for epoch in range(epochs):\n for step,(x,y) in enumerate(train_loader):\n x,y=x.to(device),y.to(device)\n logits=model(x)\n loss=criten(logits,y)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n viz.line([loss.item()],[global_step],win='loss',update='append')\n global_step+=1\n if epoch%1==0:\n val_acc=evalute(model,val_loader)\n if val_acc>best_acc:\n best_epoch=epoch\n best_acc=val_acc\n\n torch.save(model.state_dict(),'best.mdl')\n\n viz.line([val_acc], [global_step], win='val_acc', update='append')\n print('best acc:',best_acc,'best epoch:',best_epoch)\n model.load_state_dict(torch.load('best.mdl'))\n print('loaded from ckpt')\n test_acc=evalute(model,test_loader)\n print('test acc:',test_acc)\n\n\n\n\nif __name__ == '__main__':\n main()\n\n", "import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nclass ResBl(nn.Module):\n def __init__(self,ch_in,ch_out,stride=1):\n super(ResBl,self).__init__()\n self.conv1=nn.Conv2d(ch_in,ch_out,kernel_size=3,stride=stride,padding=1)\n self.bn1=nn.BatchNorm2d(ch_out)\n self.conv2=nn.Conv2d(ch_out,ch_out,kernel_size=3,stride=1,padding=1)\n self.bn2=nn.BatchNorm2d(ch_out)\n self.extra=nn.Sequential()\n if ch_out!=ch_in:\n self.extra=nn.Sequential(\n nn.Conv2d(ch_in,ch_out,kernel_size=1,stride=stride),\n nn.BatchNorm2d(ch_out)\n )\n\n def forward(self, x):\n out=F.relu(self.bn1(self.conv1(x)))\n out=self.bn2(self.conv2(out))\n out=self.extra(x)+out\n return out\n\nclass Resnet(nn.Module):\n def __init__(self):\n super(Resnet,self).__init__()\n self.con1=nn.Sequential(\n nn.Conv2d(3,64,kernel_size=3,stride=3,padding=0),\n nn.BatchNorm2d(64)\n )\n self.blc1=ResBl(64,128,stride=2)\n self.blc2=ResBl(128,256,stride=2)\n self.blc3=ResBl(256,512,stride=2)\n self.blc4=ResBl(512,512,stride=2)\n self.outlayer=nn.Linear(512*1*1,10)\n\n def forward(self,x):\n x=F.relu(self.con1(x))\n x=self.blc1(x)\n x=self.blc2(x)\n x=self.blc3(x)\n x=self.blc4(x)\n #print(x.shape)\n x=F.adaptive_avg_pool2d(x,[1,1])\n #print(x.shape)\n x=x.view(x.size(0),-1)\n x=self.outlayer(x)\n return x\n\n# def main():\n# blk=ResBl(64,128,stride=4)\n# tmp = torch.randn(2, 64, 32, 32)\n# out=blk(tmp)\n# print('block:',out.shape)\n#\n# x=torch.randn(2,3,32,32)\n# model=Resnet()\n# out=model(x)\n# print('resnet:',out.shape)\n#\n#\n# if __name__ == '__main__':\n# main()\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.load", "torch.eq", "torch.manual_seed", "torch.utils.data.DataLoader", "torch.no_grad", "torch.cuda.is_available" ], [ "torch.nn.Sequential", "torch.nn.Conv2d", "torch.nn.functional.adaptive_avg_pool2d", "torch.nn.Linear", "torch.nn.BatchNorm2d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
nestordemeure/tabularGP
[ "30c59bda679986330c2ed08807d81f70edeca8da" ]
[ "tabularGP/trainset_selection.py" ]
[ "# Training points selection\n# Selects the points that will be used inside the gaussian process\n# source: https://github.com/nestordemeure/tabularGP/blob/master/trainset_selection.py\n\nfrom torch import Tensor, nn\nimport torch\nfrom fastai.torch_basics import * # for pytorch to tensor conversion\n\n__all__ = ['trainset_of_databunch', 'select_trainset', 'get_worst_element']\n\n#--------------------------------------------------------------------------------------------------\n# Distance metric\n\ndef _hamming_distances(row:Tensor, data:Tensor):\n \"returns a vector with the hamming distance between a row and each row of a dataset\"\n if row.dim() == 0: return Tensor([0.0]).to(row.device) # deals with absence of categorial features\n return (row.unsqueeze(dim=0) != data).sum(dim=1)\n\ndef _euclidian_distances(row:Tensor, data:Tensor):\n \"returns a vector with the euclidian distance between a row and each row of a dataset\"\n if row.dim() == 0: return Tensor([0.0]).to(row.device) # deals with absence of continuous features\n return torch.sum((row.unsqueeze(dim=0) - data)**2, dim=1)\n\n#--------------------------------------------------------------------------------------------------\n# Selection\n\ndef _maximalyDifferentPoints(data_cont:Tensor, data_cat:Tensor, nb_cluster:int):\n \"\"\"\n returns the given number of indexes such that the associated rows are as far as possible\n according to the hamming distance between categories and, in case of equality, the euclidian distance between continuous columns\n uses a greedy algorithm to quickly get an approximate solution\n \"\"\"\n # initialize with the first point of the dataset\n indexes = [0]\n row_cat = data_cat[0, ...]\n minimum_distances_cat = _hamming_distances(row_cat, data_cat)\n # we suppose that data_cont is normalized so raw euclidian distance is enough\n row_cont = data_cont[0, ...]\n minimum_distances_cont = _euclidian_distances(row_cont, data_cont)\n for _ in range(nb_cluster - 1):\n # finds the row that maximizes the minimum distances to the existing selections\n # choice is done on cat distance (which has granularity 1) and, in case of equality, cont distance (normalized to be in [0;0.5])\n minimum_distances = minimum_distances_cat + minimum_distances_cont / (2.0 * minimum_distances_cont.max())\n index = torch.argmax(minimum_distances, dim=0)\n indexes.append(index.item())\n # updates distances cont\n row_cont = data_cont[index, ...]\n distances_cont = _euclidian_distances(row_cont, data_cont)\n minimum_distances_cont = torch.min(minimum_distances_cont, distances_cont)\n # update distances cat\n row_cat = data_cat[index, ...]\n distances_cat = _hamming_distances(row_cat, data_cat)\n minimum_distances_cat = torch.min(minimum_distances_cat, distances_cat)\n return torch.LongTensor(indexes)\n\ndef trainset_of_databunch(data):\n \"takes a databunch and returns a (cat,cont,y) tuple\"\n # extracts all the dataset as tensors\n # TODO convert the folowing dataframes into tensors\n data_cat = tensor(data.cats).long()\n data_cont = tensor(data.conts).float()\n # transforms the output into one hot encoding if we are dealing with a classification problem\n is_classification = (data.c > 1) and (len(data.y_names) == 1)\n if is_classification:\n data_y = tensor(data.ys).squeeze().long()\n data_y = nn.functional.one_hot(data_y).float()\n else:\n data_y = tensor(data.ys).float()\n return (data_cat, data_cont, data_y)\n\ndef select_trainset(data, nb_points:int, use_random_training_points=False):\n \"gets a (cat,cont,y) tuple with the given number of elements\"\n # extracts all the dataset as tensors\n (data_cat, data_cont, data_y) = trainset_of_databunch(data)\n # selects training points\n if nb_points >= data_cat.size(0): return (data_cat, data_cont, data_y)\n elif use_random_training_points: indices = torch.arange(0, nb_points)\n else: indices = _maximalyDifferentPoints(data_cont, data_cat, nb_points)\n # assemble the training data\n data_cat = data_cat[indices, ...]\n data_cont = data_cont[indices, ...]\n data_y = data_y[indices, ...]\n return (data_cat, data_cont, data_y)\n\ndef get_worst_element(model, dl, loss_func):\n \"gets the element, from the given dataloader, with the maximum loss\"\n max_loss = None\n max_element = None\n for (xcat,xcont),y in dl:\n out = model(xcat,xcont)\n loss = loss_func(out, y, reduction=None).squeeze()\n id_worst_batch_element = torch.argmin(loss)\n if (max_loss is None) or (loss[id_worst_batch_element] > max_loss):\n max_loss = loss[id_worst_batch_element]\n max_element = xcat[id_worst_batch_element, ...], xcont[id_worst_batch_element, ...], y[id_worst_batch_element, ...]\n return max_element\n" ]
[ [ "torch.LongTensor", "torch.Tensor", "torch.min", "torch.argmin", "torch.arange", "torch.nn.functional.one_hot", "torch.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ikedaosushi/modin
[ "4d0a3155b31104ac8083b223bd71ff3e541ecd92", "4d0a3155b31104ac8083b223bd71ff3e541ecd92", "d8a99727658f251148742d87ca50c6881aff5b81" ]
[ "modin/pandas/concat.py", "modin/pandas/test/test_io.py", "modin/pandas/test/test_dataframe.py" ]
[ "# Licensed to Modin Development Team under one or more contributor license agreements.\n# See the NOTICE file distributed with this work for additional information regarding\n# copyright ownership. The Modin Development Team licenses this file to you under the\n# Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n# compliance with the License. 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 distributed under\n# the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific language\n# governing permissions and limitations under the License.\n\nimport pandas\nimport numpy as np\n\nfrom typing import Hashable, Iterable, Mapping, Optional, Union\nfrom pandas._typing import FrameOrSeriesUnion\nfrom pandas.core.dtypes.common import is_list_like\n\nfrom modin.backends.base.query_compiler import BaseQueryCompiler\nfrom .dataframe import DataFrame\nfrom .series import Series\n\n\ndef concat(\n objs: Union[\n Iterable[FrameOrSeriesUnion], Mapping[Optional[Hashable], FrameOrSeriesUnion]\n ],\n axis=0,\n join=\"outer\",\n ignore_index: bool = False,\n keys=None,\n levels=None,\n names=None,\n verify_integrity: bool = False,\n sort: bool = False,\n copy: bool = True,\n) -> FrameOrSeriesUnion:\n if isinstance(objs, (pandas.Series, Series, DataFrame, str, pandas.DataFrame)):\n raise TypeError(\n \"first argument must be an iterable of pandas \"\n \"objects, you passed an object of type \"\n '\"{name}\"'.format(name=type(objs).__name__)\n )\n axis = pandas.DataFrame()._get_axis_number(axis)\n if isinstance(objs, dict):\n list_of_objs = list(objs.values())\n else:\n list_of_objs = list(objs)\n if len(list_of_objs) == 0:\n raise ValueError(\"No objects to concatenate\")\n\n list_of_objs = [obj for obj in list_of_objs if obj is not None]\n\n if len(list_of_objs) == 0:\n raise ValueError(\"All objects passed were None\")\n try:\n type_check = next(\n obj\n for obj in list_of_objs\n if not isinstance(obj, (pandas.Series, Series, pandas.DataFrame, DataFrame))\n )\n except StopIteration:\n type_check = None\n if type_check is not None:\n raise ValueError(\n 'cannot concatenate object of type \"{0}\"; only '\n \"modin.pandas.Series \"\n \"and modin.pandas.DataFrame objs are \"\n \"valid\",\n type(type_check),\n )\n all_series = all(isinstance(obj, Series) for obj in list_of_objs)\n if all_series and axis == 0:\n return Series(\n query_compiler=list_of_objs[0]._query_compiler.concat(\n axis,\n [o._query_compiler for o in list_of_objs[1:]],\n join=join,\n join_axes=None,\n ignore_index=ignore_index,\n keys=None,\n levels=None,\n names=None,\n verify_integrity=False,\n copy=True,\n sort=sort,\n )\n )\n if join not in [\"inner\", \"outer\"]:\n raise ValueError(\n \"Only can inner (intersect) or outer (union) join the other axis\"\n )\n # We have the weird Series and axis check because, when concatenating a\n # dataframe to a series on axis=0, pandas ignores the name of the series,\n # and this check aims to mirror that (possibly buggy) functionality\n list_of_objs = [\n obj\n if isinstance(obj, DataFrame)\n else DataFrame(obj.rename())\n if isinstance(obj, (pandas.Series, Series)) and axis == 0\n else DataFrame(obj)\n for obj in list_of_objs\n ]\n list_of_objs = [\n obj._query_compiler\n for obj in list_of_objs\n if len(obj.index) or len(obj.columns)\n ]\n if keys is not None:\n if all_series:\n new_idx = keys\n else:\n list_of_objs = [\n list_of_objs[i] for i in range(min(len(list_of_objs), len(keys)))\n ]\n new_idx_labels = {\n k: v.index if axis == 0 else v.columns\n for k, v in zip(keys, list_of_objs)\n }\n tuples = [\n (k, *o) if isinstance(o, tuple) else (k, o)\n for k, obj in new_idx_labels.items()\n for o in obj\n ]\n new_idx = pandas.MultiIndex.from_tuples(tuples)\n if names is not None:\n new_idx.names = names\n else:\n old_name = _determine_name(list_of_objs, axis)\n if old_name is not None:\n new_idx.names = [None] + old_name\n elif isinstance(objs, dict):\n new_idx = pandas.concat(\n {k: pandas.Series(index=obj.axes[axis]) for k, obj in objs.items()}\n ).index\n else:\n new_idx = None\n new_query_compiler = list_of_objs[0].concat(\n axis,\n list_of_objs[1:],\n join=join,\n join_axes=None,\n ignore_index=ignore_index,\n keys=None,\n levels=None,\n names=None,\n verify_integrity=False,\n copy=True,\n sort=sort,\n )\n result_df = DataFrame(query_compiler=new_query_compiler)\n if new_idx is not None:\n if axis == 0:\n result_df.index = new_idx\n else:\n result_df.columns = new_idx\n return result_df\n\n\ndef _determine_name(objs: Iterable[BaseQueryCompiler], axis: Union[int, str]):\n \"\"\"\n Determine names of index after concatenation along passed axis\n\n Parameters\n ----------\n objs : iterable of QueryCompilers\n objects to concatenate\n\n axis : int or str\n the axis to concatenate along\n\n Returns\n -------\n `list` with single element - computed index name, `None` if it could not\n be determined\n \"\"\"\n axis = pandas.DataFrame()._get_axis_number(axis)\n\n def get_names(obj):\n return obj.columns.names if axis else obj.index.names\n\n names = np.array([get_names(obj) for obj in objs])\n\n # saving old name, only if index names of all objs are the same\n if np.all(names == names[0]):\n # we must do this check to avoid this calls `list(str_like_name)`\n return list(names[0]) if is_list_like(names[0]) else [names[0]]\n else:\n return None\n", "# Licensed to Modin Development Team under one or more contributor license agreements.\n# See the NOTICE file distributed with this work for additional information regarding\n# copyright ownership. The Modin Development Team licenses this file to you under the\n# Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n# compliance with the License. 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 distributed under\n# the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific language\n# governing permissions and limitations under the License.\n\nimport pytest\nimport numpy as np\nimport pandas\nfrom pandas.errors import ParserWarning\nfrom collections import OrderedDict\nfrom modin.pandas.utils import to_pandas\nfrom pathlib import Path\nimport pyarrow as pa\nimport pyarrow.parquet as pq\nimport os\nimport shutil\nimport sqlalchemy as sa\nimport csv\n\nfrom .utils import (\n df_equals,\n json_short_string,\n json_short_bytes,\n json_long_string,\n json_long_bytes,\n)\n\nfrom modin import execution_engine\n\nif os.environ.get(\"MODIN_BACKEND\", \"Pandas\").lower() == \"pandas\":\n import modin.pandas as pd\nelse:\n import modin.experimental.pandas as pd\n\npd.DEFAULT_NPARTITIONS = 4\n\nTEST_PARQUET_FILENAME = \"test.parquet\"\nTEST_CSV_FILENAME = \"test.csv\"\nTEST_JSON_FILENAME = \"test.json\"\nTEST_HTML_FILENAME = \"test.html\"\nTEST_EXCEL_FILENAME = \"test.xlsx\"\nTEST_FEATHER_FILENAME = \"test.feather\"\nTEST_READ_HDF_FILENAME = \"test.hdf\"\nTEST_WRITE_HDF_FILENAME_MODIN = \"test_write_modin.hdf\"\nTEST_WRITE_HDF_FILENAME_PANDAS = \"test_write_pandas.hdf\"\nTEST_STATA_FILENAME = \"test.dta\"\nTEST_PICKLE_FILENAME = \"test.pkl\"\nTEST_SAS_FILENAME = os.getcwd() + \"/data/test1.sas7bdat\"\nTEST_FWF_FILENAME = \"test_fwf.txt\"\nTEST_GBQ_FILENAME = \"test_gbq.\"\nSMALL_ROW_SIZE = 2000\n\n\[email protected]\ndef make_parquet_file():\n \"\"\"Pytest fixture factory that makes a parquet file/dir for testing.\n\n Yields:\n Function that generates a parquet file/dir\n \"\"\"\n\n def _make_parquet_file(\n row_size=SMALL_ROW_SIZE, force=False, directory=False, partitioned_columns=[]\n ):\n \"\"\"Helper function to generate parquet files/directories.\n\n Args:\n row_size: Number of rows for the dataframe.\n force: Create a new file/directory even if one already exists.\n directory: Create a partitioned directory using pyarrow.\n partitioned_columns: Create a partitioned directory using pandas.\n Will be ignored if directory=True.\n \"\"\"\n df = pandas.DataFrame(\n {\"col1\": np.arange(row_size), \"col2\": np.arange(row_size)}\n )\n if os.path.exists(TEST_PARQUET_FILENAME) and not force:\n pass\n elif directory:\n if os.path.exists(TEST_PARQUET_FILENAME):\n shutil.rmtree(TEST_PARQUET_FILENAME)\n else:\n os.mkdir(TEST_PARQUET_FILENAME)\n table = pa.Table.from_pandas(df)\n pq.write_to_dataset(table, root_path=TEST_PARQUET_FILENAME)\n elif len(partitioned_columns) > 0:\n df.to_parquet(TEST_PARQUET_FILENAME, partition_cols=partitioned_columns)\n else:\n df.to_parquet(TEST_PARQUET_FILENAME)\n\n # Return function that generates csv files\n yield _make_parquet_file\n\n # Delete parquet file that was created\n if os.path.exists(TEST_PARQUET_FILENAME):\n if os.path.isdir(TEST_PARQUET_FILENAME):\n shutil.rmtree(TEST_PARQUET_FILENAME)\n else:\n os.remove(TEST_PARQUET_FILENAME)\n\n\ndef create_test_modin_dataframe():\n df = pd.DataFrame(\n {\n \"col1\": [0, 1, 2, 3],\n \"col2\": [4, 5, 6, 7],\n \"col3\": [8, 9, 10, 11],\n \"col4\": [12, 13, 14, 15],\n \"col5\": [0, 0, 0, 0],\n }\n )\n\n return df\n\n\ndef create_test_pandas_dataframe():\n df = pandas.DataFrame(\n {\n \"col1\": [0, 1, 2, 3],\n \"col2\": [4, 5, 6, 7],\n \"col3\": [8, 9, 10, 11],\n \"col4\": [12, 13, 14, 15],\n \"col5\": [0, 0, 0, 0],\n }\n )\n\n return df\n\n\ndef assert_files_eq(path1, path2):\n with open(path1, \"rb\") as file1, open(path2, \"rb\") as file2:\n file1_content = file1.read()\n file2_content = file2.read()\n\n if file1_content == file2_content:\n return True\n else:\n return False\n\n\ndef teardown_test_file(test_path):\n if os.path.exists(test_path):\n os.remove(test_path)\n\n\[email protected]\ndef make_csv_file(delimiter=\",\", compression=\"infer\"):\n \"\"\"Pytest fixture factory that makes temp csv files for testing.\n\n Yields:\n Function that generates csv files\n \"\"\"\n filenames = []\n\n def _make_csv_file(\n filename=TEST_CSV_FILENAME,\n row_size=SMALL_ROW_SIZE,\n force=True,\n delimiter=delimiter,\n encoding=None,\n compression=compression,\n ):\n if os.path.exists(filename) and not force:\n pass\n else:\n dates = pandas.date_range(\"2000\", freq=\"h\", periods=row_size)\n df = pandas.DataFrame(\n {\n \"col1\": np.arange(row_size),\n \"col2\": [str(x.date()) for x in dates],\n \"col3\": np.arange(row_size),\n \"col4\": [str(x.time()) for x in dates],\n }\n )\n if compression == \"gzip\":\n filename = \"{}.gz\".format(filename)\n elif compression == \"zip\" or compression == \"xz\" or compression == \"bz2\":\n filename = \"{fname}.{comp}\".format(fname=filename, comp=compression)\n\n df.to_csv(\n filename, sep=delimiter, encoding=encoding, compression=compression\n )\n filenames.append(filename)\n return df\n\n # Return function that generates csv files\n yield _make_csv_file\n\n # Delete csv files that were created\n for filename in filenames:\n if os.path.exists(filename):\n try:\n os.remove(filename)\n except PermissionError:\n pass\n\n\ndef setup_json_file(row_size, force=False):\n if os.path.exists(TEST_JSON_FILENAME) and not force:\n pass\n else:\n df = pandas.DataFrame(\n {\"col1\": np.arange(row_size), \"col2\": np.arange(row_size)}\n )\n df.to_json(TEST_JSON_FILENAME)\n\n\ndef setup_json_lines_file(row_size, force=False):\n if os.path.exists(TEST_JSON_FILENAME) and not force:\n pass\n else:\n df = pandas.DataFrame(\n {\"col1\": np.arange(row_size), \"col2\": np.arange(row_size)}\n )\n df.to_json(TEST_JSON_FILENAME, lines=True, orient=\"records\")\n\n\ndef teardown_json_file():\n if os.path.exists(TEST_JSON_FILENAME):\n os.remove(TEST_JSON_FILENAME)\n\n\ndef setup_html_file(row_size, force=False):\n if os.path.exists(TEST_HTML_FILENAME) and not force:\n pass\n else:\n df = pandas.DataFrame(\n {\"col1\": np.arange(row_size), \"col2\": np.arange(row_size)}\n )\n df.to_html(TEST_HTML_FILENAME)\n\n\ndef teardown_html_file():\n if os.path.exists(TEST_HTML_FILENAME):\n os.remove(TEST_HTML_FILENAME)\n\n\ndef setup_clipboard(row_size, force=False):\n df = pandas.DataFrame({\"col1\": np.arange(row_size), \"col2\": np.arange(row_size)})\n df.to_clipboard()\n\n\ndef setup_excel_file(row_size, force=False):\n if os.path.exists(TEST_EXCEL_FILENAME) and not force:\n pass\n else:\n df = pandas.DataFrame(\n {\"col1\": np.arange(row_size), \"col2\": np.arange(row_size)}\n )\n df.to_excel(TEST_EXCEL_FILENAME)\n\n\ndef teardown_excel_file():\n if os.path.exists(TEST_EXCEL_FILENAME):\n try:\n os.remove(TEST_EXCEL_FILENAME)\n except PermissionError:\n pass\n\n\ndef setup_feather_file(row_size, force=False):\n if os.path.exists(TEST_FEATHER_FILENAME) and not force:\n pass\n else:\n df = pandas.DataFrame(\n {\"col1\": np.arange(row_size), \"col2\": np.arange(row_size)}\n )\n df.to_feather(TEST_FEATHER_FILENAME)\n\n\ndef teardown_feather_file():\n if os.path.exists(TEST_FEATHER_FILENAME):\n os.remove(TEST_FEATHER_FILENAME)\n\n\ndef setup_hdf_file(row_size, force=False, format=None):\n if os.path.exists(TEST_READ_HDF_FILENAME) and not force:\n pass\n else:\n df = pandas.DataFrame(\n {\"col1\": np.arange(row_size), \"col2\": np.arange(row_size)}\n )\n df.to_hdf(TEST_READ_HDF_FILENAME, key=\"df\", format=format)\n\n\ndef teardown_hdf_file():\n if os.path.exists(TEST_READ_HDF_FILENAME):\n os.remove(TEST_READ_HDF_FILENAME)\n\n\ndef setup_stata_file(row_size, force=False):\n if os.path.exists(TEST_STATA_FILENAME) and not force:\n pass\n else:\n df = pandas.DataFrame(\n {\"col1\": np.arange(row_size), \"col2\": np.arange(row_size)}\n )\n df.to_stata(TEST_STATA_FILENAME)\n\n\ndef teardown_stata_file():\n if os.path.exists(TEST_STATA_FILENAME):\n os.remove(TEST_STATA_FILENAME)\n\n\ndef setup_pickle_file(row_size, force=False):\n if os.path.exists(TEST_PICKLE_FILENAME) and not force:\n pass\n else:\n df = pandas.DataFrame(\n {\"col1\": np.arange(row_size), \"col2\": np.arange(row_size)}\n )\n df.to_pickle(TEST_PICKLE_FILENAME)\n\n\ndef teardown_pickle_file():\n if os.path.exists(TEST_PICKLE_FILENAME):\n os.remove(TEST_PICKLE_FILENAME)\n\n\[email protected]\ndef make_sql_connection():\n \"\"\"Sets up sql connections and takes them down after the caller is done.\n\n Yields:\n Factory that generates sql connection objects\n \"\"\"\n filenames = []\n\n def _sql_connection(filename, table=\"\"):\n # Remove file if exists\n if os.path.exists(filename):\n os.remove(filename)\n filenames.append(filename)\n # Create connection and, if needed, table\n conn = \"sqlite:///{}\".format(filename)\n if table:\n df = pandas.DataFrame(\n {\n \"col1\": [0, 1, 2, 3, 4, 5, 6],\n \"col2\": [7, 8, 9, 10, 11, 12, 13],\n \"col3\": [14, 15, 16, 17, 18, 19, 20],\n \"col4\": [21, 22, 23, 24, 25, 26, 27],\n \"col5\": [0, 0, 0, 0, 0, 0, 0],\n }\n )\n df.to_sql(table, conn)\n return conn\n\n yield _sql_connection\n\n # Takedown the fixture\n for filename in filenames:\n if os.path.exists(filename):\n os.remove(filename)\n\n\ndef setup_fwf_file(overwrite=False, fwf_data=None):\n if not overwrite and os.path.exists(TEST_FWF_FILENAME):\n return\n\n if fwf_data is None:\n fwf_data = \"\"\"ACW000116041961TAVG -142 k 183 k 419 k 720 k 1075 k 1546 k 1517 k 1428 k 1360 k 1121 k 457 k -92 k\nACW000116041962TAVG 60 k 32 k -207 k 582 k 855 k 1328 k 1457 k 1340 k 1110 k 941 k 270 k -179 k\nACW000116041963TAVG -766 k -606 k -152 k 488 k 1171 k 1574 k 1567 k 1543 k 1279 k 887 k 513 k -161 k\nACW000116041964TAVG 9 k -138 k 2 k 685 k 1166 k 1389 k 1453 k 1504 k 1168 k 735 k 493 k 59 k\nACW000116041965TAVG -9 k -158 k -15 k 537 k 934 k 1447 k 1434 k 1424 k 1324 k 921 k -22 k -231 k\nACW000116041966TAVG -490 k -614 k 108 k 246 k 1082 k 1642 k 1620 k 1471 k 1195 k 803 k 329 k 2 k\nACW000116041967TAVG -270 k 36 k 397 k 481 k 1052 k 1373 k 1655 k 1598 k 1318 k 997 k 559 k -96 k\nACW000116041968TAVG -306 k -183 k 220 k 714 k 935 k 1635 k 1572 k 1718 k 1331 k 781 k 180 k -56 k\nACW000116041969TAVG -134 k -494 k -185 k 497 k 962 k 1634 k 1687 k 1773 k 1379 k 932 k 321 k -275 k\nACW000116041970TAVG -483 k -704 k -75 k 261 k 1093 k 1724 k 1470 k 1609 k 1163 k 836 k 300 k 73 k\nACW000116041971TAVG -6 k 83 k -40 k 472 k 1180 k 1411 k 1700 k 1600 k 1165 k 908 k 361 k 383 k\nACW000116041972TAVG -377 k -4 k 250 k 556 k 1117 k 1444 k 1778 k 1545 k 1073 k 797 k 481 k 404 k\nACW000116041973TAVG 61 k 169 k 453 k 472 k 1075 k 1545 k 1866 k 1579 k 1199 k 563 k 154 k 11 k\nACW000116041974TAVG 191 k 209 k 339 k 748 k 1094 k 1463 k 1498 k 1541 k 1319 k 585 k 428 k 335 k\nACW000116041975TAVG 346 k 88 k 198 k 488 k 1165 k 1483 k 1756 k 1906 k 1374 k 845 k 406 k 387 k\nACW000116041976TAVG -163 k -62 k -135 k 502 k 1128 k 1461 k 1822 k 1759 k 1136 k 715 k 458 k -205 k\nACW000116041977TAVG -192 k -279 k 234 k 332 k 1128 k 1566 k 1565 k 1556 k 1126 k 949 k 421 k 162 k\nACW000116041978TAVG 55 k -354 k 66 k 493 k 1155 k 1552 k 1564 k 1555 k 1061 k 932 k 688 k -464 k\nACW000116041979TAVG -618 k -632 k 35 k 474 k 993 k 1566 k 1484 k 1483 k 1229 k 647 k 412 k -40 k\nACW000116041980TAVG -340 k -500 k -35 k 524 k 1071 k 1534 k 1655 k 1502 k 1269 k 660 k 138 k 125 k\"\"\"\n\n with open(TEST_FWF_FILENAME, \"w\") as f:\n f.write(fwf_data)\n\n\ndef teardown_fwf_file():\n if os.path.exists(TEST_FWF_FILENAME):\n try:\n os.remove(TEST_FWF_FILENAME)\n except PermissionError:\n pass\n\n\ndef test_from_parquet(make_parquet_file):\n make_parquet_file(SMALL_ROW_SIZE)\n\n pandas_df = pandas.read_parquet(TEST_PARQUET_FILENAME)\n modin_df = pd.read_parquet(TEST_PARQUET_FILENAME)\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_parquet_with_columns(make_parquet_file):\n make_parquet_file(SMALL_ROW_SIZE)\n\n pandas_df = pandas.read_parquet(TEST_PARQUET_FILENAME, columns=[\"col1\"])\n modin_df = pd.read_parquet(TEST_PARQUET_FILENAME, columns=[\"col1\"])\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_parquet_partition(make_parquet_file):\n make_parquet_file(SMALL_ROW_SIZE, directory=True)\n\n pandas_df = pandas.read_parquet(TEST_PARQUET_FILENAME)\n modin_df = pd.read_parquet(TEST_PARQUET_FILENAME)\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_parquet_partition_with_columns(make_parquet_file):\n make_parquet_file(SMALL_ROW_SIZE, directory=True)\n\n pandas_df = pandas.read_parquet(TEST_PARQUET_FILENAME, columns=[\"col1\"])\n modin_df = pd.read_parquet(TEST_PARQUET_FILENAME, columns=[\"col1\"])\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_parquet_partitioned_columns(make_parquet_file):\n make_parquet_file(SMALL_ROW_SIZE, partitioned_columns=[\"col1\"])\n\n pandas_df = pandas.read_parquet(TEST_PARQUET_FILENAME)\n modin_df = pd.read_parquet(TEST_PARQUET_FILENAME)\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_parquet_partitioned_columns_with_columns(make_parquet_file):\n make_parquet_file(SMALL_ROW_SIZE, partitioned_columns=[\"col1\"])\n\n pandas_df = pandas.read_parquet(TEST_PARQUET_FILENAME, columns=[\"col1\"])\n modin_df = pd.read_parquet(TEST_PARQUET_FILENAME, columns=[\"col1\"])\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_parquet_pandas_index():\n # Ensure modin can read parquet files written by pandas with a non-RangeIndex object\n pandas_df = pandas.DataFrame(\n {\n \"idx\": np.random.randint(0, 100_000, size=2000),\n \"A\": np.random.randint(0, 100_000, size=2000),\n \"B\": [\"a\", \"b\"] * 1000,\n \"C\": [\"c\"] * 2000,\n }\n )\n filepath = \"tmp.parquet\"\n pandas_df.set_index(\"idx\").to_parquet(filepath)\n # read the same parquet using modin.pandas\n df_equals(pd.read_parquet(filepath), pandas.read_parquet(filepath))\n\n pandas_df.set_index([\"idx\", \"A\"]).to_parquet(filepath)\n df_equals(pd.read_parquet(filepath), pandas.read_parquet(filepath))\n os.remove(filepath)\n\n\ndef test_from_parquet_pandas_index_partitioned():\n # Ensure modin can read parquet files written by pandas with a non-RangeIndex object\n pandas_df = pandas.DataFrame(\n {\n \"idx\": np.random.randint(0, 100_000, size=2000),\n \"A\": np.random.randint(0, 10, size=2000),\n \"B\": [\"a\", \"b\"] * 1000,\n \"C\": [\"c\"] * 2000,\n }\n )\n filepath = \"tmp_folder.parquet\"\n pandas_df.set_index(\"idx\").to_parquet(filepath, partition_cols=[\"A\"])\n # read the same parquet using modin.pandas\n df_equals(pd.read_parquet(filepath), pandas.read_parquet(filepath))\n shutil.rmtree(filepath)\n\n\ndef test_from_parquet_hdfs():\n path = \"modin/pandas/test/data/hdfs.parquet\"\n pandas_df = pandas.read_parquet(path)\n modin_df = pd.read_parquet(path)\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_json():\n setup_json_file(SMALL_ROW_SIZE)\n\n pandas_df = pandas.read_json(TEST_JSON_FILENAME)\n modin_df = pd.read_json(TEST_JSON_FILENAME)\n\n df_equals(modin_df, pandas_df)\n\n teardown_json_file()\n\n\ndef test_from_json_categories():\n pandas_df = pandas.read_json(\n \"modin/pandas/test/data/test_categories.json\",\n dtype={\"one\": \"int64\", \"two\": \"category\"},\n )\n modin_df = pd.read_json(\n \"modin/pandas/test/data/test_categories.json\",\n dtype={\"one\": \"int64\", \"two\": \"category\"},\n )\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_json_lines():\n setup_json_lines_file(SMALL_ROW_SIZE)\n\n pandas_df = pandas.read_json(TEST_JSON_FILENAME, lines=True)\n modin_df = pd.read_json(TEST_JSON_FILENAME, lines=True)\n df_equals(modin_df, pandas_df)\n\n teardown_json_file()\n\n\[email protected](\n \"data\", [json_short_string, json_short_bytes, json_long_string, json_long_bytes],\n)\ndef test_read_json_string_bytes(data):\n with pytest.warns(UserWarning):\n modin_df = pd.read_json(data)\n # For I/O objects we need to rewind to reuse the same object.\n if hasattr(data, \"seek\"):\n data.seek(0)\n df_equals(modin_df, pandas.read_json(data))\n\n\ndef test_from_html():\n setup_html_file(SMALL_ROW_SIZE)\n\n pandas_df = pandas.read_html(TEST_HTML_FILENAME)[0]\n modin_df = pd.read_html(TEST_HTML_FILENAME)\n\n df_equals(modin_df, pandas_df)\n\n teardown_html_file()\n\n\[email protected](reason=\"No clipboard on Travis\")\ndef test_from_clipboard():\n setup_clipboard(SMALL_ROW_SIZE)\n\n pandas_df = pandas.read_clipboard()\n modin_df = pd.read_clipboard()\n\n df_equals(modin_df, pandas_df)\n\n\[email protected](reason=\"read_excel is broken for now, see #1733 for details\")\ndef test_from_excel():\n setup_excel_file(SMALL_ROW_SIZE)\n\n pandas_df = pandas.read_excel(TEST_EXCEL_FILENAME)\n modin_df = pd.read_excel(TEST_EXCEL_FILENAME)\n\n df_equals(modin_df, pandas_df)\n\n teardown_excel_file()\n\n\ndef test_from_excel_engine():\n setup_excel_file(SMALL_ROW_SIZE)\n\n pandas_df = pandas.read_excel(TEST_EXCEL_FILENAME, engine=\"xlrd\")\n with pytest.warns(UserWarning):\n modin_df = pd.read_excel(TEST_EXCEL_FILENAME, engine=\"xlrd\")\n\n df_equals(modin_df, pandas_df)\n\n teardown_excel_file()\n\n\ndef test_from_excel_index_col():\n setup_excel_file(SMALL_ROW_SIZE)\n\n pandas_df = pandas.read_excel(TEST_EXCEL_FILENAME, index_col=0)\n with pytest.warns(UserWarning):\n modin_df = pd.read_excel(TEST_EXCEL_FILENAME, index_col=0)\n\n df_equals(modin_df, pandas_df)\n\n teardown_excel_file()\n\n\ndef test_from_excel_all_sheets():\n setup_excel_file(SMALL_ROW_SIZE)\n\n pandas_df = pandas.read_excel(TEST_EXCEL_FILENAME, sheet_name=None)\n modin_df = pd.read_excel(TEST_EXCEL_FILENAME, sheet_name=None)\n\n assert isinstance(pandas_df, (OrderedDict, dict))\n assert isinstance(modin_df, type(pandas_df))\n\n assert pandas_df.keys() == modin_df.keys()\n\n for key in pandas_df.keys():\n df_equals(modin_df.get(key), pandas_df.get(key))\n\n teardown_excel_file()\n\n\n# @pytest.mark.skip(reason=\"Arrow version mismatch between Pandas and Feather\")\ndef test_from_feather():\n setup_feather_file(SMALL_ROW_SIZE)\n\n pandas_df = pandas.read_feather(TEST_FEATHER_FILENAME)\n modin_df = pd.read_feather(TEST_FEATHER_FILENAME)\n\n df_equals(modin_df, pandas_df)\n\n teardown_feather_file()\n\n\[email protected](os.name == \"nt\", reason=\"Windows not supported\")\ndef test_from_hdf():\n setup_hdf_file(SMALL_ROW_SIZE, format=None)\n\n pandas_df = pandas.read_hdf(TEST_READ_HDF_FILENAME, key=\"df\")\n modin_df = pd.read_hdf(TEST_READ_HDF_FILENAME, key=\"df\")\n\n df_equals(modin_df, pandas_df)\n\n teardown_hdf_file()\n\n\[email protected](os.name == \"nt\", reason=\"Windows not supported\")\ndef test_from_hdf_format():\n setup_hdf_file(SMALL_ROW_SIZE, format=\"table\")\n\n pandas_df = pandas.read_hdf(TEST_READ_HDF_FILENAME, key=\"df\")\n modin_df = pd.read_hdf(TEST_READ_HDF_FILENAME, key=\"df\")\n\n df_equals(modin_df, pandas_df)\n\n teardown_hdf_file()\n\n\ndef test_from_stata():\n setup_stata_file(SMALL_ROW_SIZE)\n\n pandas_df = pandas.read_stata(TEST_STATA_FILENAME)\n modin_df = pd.read_stata(TEST_STATA_FILENAME)\n\n df_equals(modin_df, pandas_df)\n\n teardown_stata_file()\n\n\ndef test_from_pickle():\n setup_pickle_file(SMALL_ROW_SIZE)\n\n pandas_df = pandas.read_pickle(TEST_PICKLE_FILENAME)\n modin_df = pd.read_pickle(TEST_PICKLE_FILENAME)\n\n df_equals(modin_df, pandas_df)\n\n teardown_pickle_file()\n\n\ndef test_from_sql(make_sql_connection):\n filename = \"test_from_sql.db\"\n table = \"test_from_sql\"\n conn = make_sql_connection(filename, table)\n query = \"select * from {0}\".format(table)\n\n pandas_df = pandas.read_sql(query, conn)\n modin_df = pd.read_sql(query, conn)\n\n df_equals(modin_df, pandas_df)\n\n pandas_df = pandas.read_sql(query, conn, index_col=\"index\")\n modin_df = pd.read_sql(query, conn, index_col=\"index\")\n\n df_equals(modin_df, pandas_df)\n\n with pytest.warns(UserWarning):\n pd.read_sql_query(query, conn)\n\n with pytest.warns(UserWarning):\n pd.read_sql_table(table, conn)\n\n # Test SQLAlchemy engine\n conn = sa.create_engine(conn)\n pandas_df = pandas.read_sql(query, conn)\n modin_df = pd.read_sql(query, conn)\n\n df_equals(modin_df, pandas_df)\n\n # Test SQLAlchemy Connection\n conn = conn.connect()\n pandas_df = pandas.read_sql(query, conn)\n modin_df = pd.read_sql(query, conn)\n\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_sql_with_chunksize(make_sql_connection):\n filename = \"test_from_sql.db\"\n table = \"test_from_sql\"\n conn = make_sql_connection(filename, table)\n query = \"select * from {0}\".format(table)\n\n pandas_gen = pandas.read_sql(query, conn, chunksize=10)\n modin_gen = pd.read_sql(query, conn, chunksize=10)\n for modin_df, pandas_df in zip(modin_gen, pandas_gen):\n df_equals(modin_df, pandas_df)\n\n\[email protected](reason=\"No SAS write methods in Pandas\")\ndef test_from_sas():\n pandas_df = pandas.read_sas(TEST_SAS_FILENAME)\n modin_df = pd.read_sas(TEST_SAS_FILENAME)\n\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_csv(make_csv_file):\n make_csv_file()\n\n pandas_df = pandas.read_csv(TEST_CSV_FILENAME)\n modin_df = pd.read_csv(TEST_CSV_FILENAME)\n\n df_equals(modin_df, pandas_df)\n\n pandas_df = pandas.read_csv(Path(TEST_CSV_FILENAME))\n modin_df = pd.read_csv(Path(TEST_CSV_FILENAME))\n\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_csv_sep_none(make_csv_file):\n make_csv_file()\n\n with pytest.warns(ParserWarning):\n pandas_df = pandas.read_csv(TEST_CSV_FILENAME, sep=None)\n with pytest.warns(ParserWarning):\n modin_df = pd.read_csv(TEST_CSV_FILENAME, sep=None)\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_csv_bad_quotes():\n csv_bad_quotes = \"\"\"1, 2, 3, 4\none, two, three, four\nfive, \"six\", seven, \"eight\n\"\"\"\n\n with open(TEST_CSV_FILENAME, \"w\") as f:\n f.write(csv_bad_quotes)\n\n pandas_df = pandas.read_csv(TEST_CSV_FILENAME)\n modin_df = pd.read_csv(TEST_CSV_FILENAME)\n\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_csv_quote_none():\n csv_bad_quotes = \"\"\"1, 2, 3, 4\none, two, three, four\nfive, \"six\", seven, \"eight\n\"\"\"\n with open(TEST_CSV_FILENAME, \"w\") as f:\n f.write(csv_bad_quotes)\n\n pandas_df = pandas.read_csv(TEST_CSV_FILENAME, quoting=csv.QUOTE_NONE)\n modin_df = pd.read_csv(TEST_CSV_FILENAME, quoting=csv.QUOTE_NONE)\n\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_csv_categories():\n pandas_df = pandas.read_csv(\n \"modin/pandas/test/data/test_categories.csv\",\n names=[\"one\", \"two\"],\n dtype={\"one\": \"int64\", \"two\": \"category\"},\n )\n modin_df = pd.read_csv(\n \"modin/pandas/test/data/test_categories.csv\",\n names=[\"one\", \"two\"],\n dtype={\"one\": \"int64\", \"two\": \"category\"},\n )\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_csv_gzip(make_csv_file):\n make_csv_file(compression=\"gzip\")\n gzip_path = \"{}.gz\".format(TEST_CSV_FILENAME)\n\n pandas_df = pandas.read_csv(gzip_path)\n modin_df = pd.read_csv(gzip_path)\n df_equals(modin_df, pandas_df)\n\n pandas_df = pandas.read_csv(gzip_path, compression=\"gzip\")\n modin_df = pd.read_csv(gzip_path, compression=\"gzip\")\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_csv_bz2(make_csv_file):\n make_csv_file(compression=\"bz2\")\n bz2_path = \"{}.bz2\".format(TEST_CSV_FILENAME)\n\n pandas_df = pandas.read_csv(bz2_path)\n modin_df = pd.read_csv(bz2_path)\n df_equals(modin_df, pandas_df)\n\n pandas_df = pandas.read_csv(bz2_path, compression=\"bz2\")\n modin_df = pd.read_csv(bz2_path, compression=\"bz2\")\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_csv_xz(make_csv_file):\n make_csv_file(compression=\"xz\")\n xz_path = \"{}.xz\".format(TEST_CSV_FILENAME)\n\n pandas_df = pandas.read_csv(xz_path)\n modin_df = pd.read_csv(xz_path)\n df_equals(modin_df, pandas_df)\n\n pandas_df = pandas.read_csv(xz_path, compression=\"xz\")\n modin_df = pd.read_csv(xz_path, compression=\"xz\")\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_csv_zip(make_csv_file):\n make_csv_file(compression=\"zip\")\n zip_path = \"{}.zip\".format(TEST_CSV_FILENAME)\n\n pandas_df = pandas.read_csv(zip_path)\n modin_df = pd.read_csv(zip_path)\n df_equals(modin_df, pandas_df)\n\n pandas_df = pandas.read_csv(zip_path, compression=\"zip\")\n modin_df = pd.read_csv(zip_path, compression=\"zip\")\n df_equals(modin_df, pandas_df)\n\n\ndef test_parse_dates_read_csv():\n pandas_df = pandas.read_csv(\"modin/pandas/test/data/test_time_parsing.csv\")\n modin_df = pd.read_csv(\"modin/pandas/test/data/test_time_parsing.csv\")\n df_equals(modin_df, pandas_df)\n\n pandas_df = pandas.read_csv(\n \"modin/pandas/test/data/test_time_parsing.csv\",\n names=[\n \"timestamp\",\n \"symbol\",\n \"high\",\n \"low\",\n \"open\",\n \"close\",\n \"spread\",\n \"volume\",\n ],\n header=0,\n index_col=0,\n encoding=\"utf-8\",\n )\n modin_df = pd.read_csv(\n \"modin/pandas/test/data/test_time_parsing.csv\",\n names=[\n \"timestamp\",\n \"symbol\",\n \"high\",\n \"low\",\n \"open\",\n \"close\",\n \"spread\",\n \"volume\",\n ],\n header=0,\n index_col=0,\n encoding=\"utf-8\",\n )\n df_equals(modin_df, pandas_df)\n\n pandas_df = pandas.read_csv(\n \"modin/pandas/test/data/test_time_parsing.csv\",\n names=[\n \"timestamp\",\n \"symbol\",\n \"high\",\n \"low\",\n \"open\",\n \"close\",\n \"spread\",\n \"volume\",\n ],\n header=0,\n index_col=0,\n parse_dates=[\"timestamp\"],\n encoding=\"utf-8\",\n )\n modin_df = pd.read_csv(\n \"modin/pandas/test/data/test_time_parsing.csv\",\n names=[\n \"timestamp\",\n \"symbol\",\n \"high\",\n \"low\",\n \"open\",\n \"close\",\n \"spread\",\n \"volume\",\n ],\n header=0,\n index_col=0,\n parse_dates=[\"timestamp\"],\n encoding=\"utf-8\",\n )\n df_equals(modin_df, pandas_df)\n\n pandas_df = pandas.read_csv(\n \"modin/pandas/test/data/test_time_parsing.csv\",\n names=[\n \"timestamp\",\n \"symbol\",\n \"high\",\n \"low\",\n \"open\",\n \"close\",\n \"spread\",\n \"volume\",\n ],\n header=0,\n index_col=2,\n parse_dates=[\"timestamp\"],\n encoding=\"utf-8\",\n )\n modin_df = pd.read_csv(\n \"modin/pandas/test/data/test_time_parsing.csv\",\n names=[\n \"timestamp\",\n \"symbol\",\n \"high\",\n \"low\",\n \"open\",\n \"close\",\n \"spread\",\n \"volume\",\n ],\n header=0,\n index_col=2,\n parse_dates=[\"timestamp\"],\n encoding=\"utf-8\",\n )\n df_equals(modin_df, pandas_df)\n\n\[email protected](\n \"kwargs\",\n [\n {\"header\": None, \"usecols\": [0, 7]},\n {\"usecols\": [0, 7]},\n {\"names\": [0, 7], \"usecols\": [0, 7]},\n ],\n)\ndef test_from_csv_with_args(kwargs):\n file_name = \"modin/pandas/test/data/issue_621.csv\"\n pandas_df = pandas.read_csv(file_name, **kwargs)\n modin_df = pd.read_csv(file_name, **kwargs)\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_table(make_csv_file):\n make_csv_file(delimiter=\"\\t\")\n\n pandas_df = pandas.read_table(TEST_CSV_FILENAME)\n modin_df = pd.read_table(TEST_CSV_FILENAME)\n\n df_equals(modin_df, pandas_df)\n\n pandas_df = pandas.read_table(Path(TEST_CSV_FILENAME))\n modin_df = pd.read_table(Path(TEST_CSV_FILENAME))\n\n df_equals(modin_df, pandas_df)\n\n\[email protected](\"usecols\", [[\"a\"], [\"a\", \"b\", \"e\"], [0, 1, 4]])\ndef test_from_csv_with_usecols(usecols):\n fname = \"modin/pandas/test/data/test_usecols.csv\"\n pandas_df = pandas.read_csv(fname, usecols=usecols)\n modin_df = pd.read_csv(fname, usecols=usecols)\n df_equals(modin_df, pandas_df)\n\n\[email protected](\n execution_engine.get().lower() == \"python\", reason=\"Using pandas implementation\"\n)\ndef test_from_csv_s3(make_csv_file):\n dataset_url = \"s3://noaa-ghcn-pds/csv/1788.csv\"\n pandas_df = pandas.read_csv(dataset_url)\n\n # This first load is to trigger all the import deprecation warnings\n modin_df = pd.read_csv(dataset_url)\n\n # This will warn if it defaults to pandas behavior, but it shouldn't\n with pytest.warns(None) as record:\n modin_df = pd.read_csv(dataset_url)\n\n assert not any(\n \"defaulting to pandas implementation\" in str(err) for err in record.list\n )\n\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_csv_default(make_csv_file):\n # We haven't implemented read_csv from https, but if it's implemented, then this needs to change\n dataset_url = \"https://raw.githubusercontent.com/modin-project/modin/master/modin/pandas/test/data/blah.csv\"\n pandas_df = pandas.read_csv(dataset_url)\n\n with pytest.warns(UserWarning):\n modin_df = pd.read_csv(dataset_url)\n\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_csv_chunksize(make_csv_file):\n make_csv_file()\n\n # Tests __next__ and correctness of reader as an iterator\n # Use larger chunksize to read through file quicker\n rdf_reader = pd.read_csv(TEST_CSV_FILENAME, chunksize=500)\n pd_reader = pandas.read_csv(TEST_CSV_FILENAME, chunksize=500)\n\n for modin_df, pd_df in zip(rdf_reader, pd_reader):\n df_equals(modin_df, pd_df)\n\n # Tests that get_chunk works correctly\n rdf_reader = pd.read_csv(TEST_CSV_FILENAME, chunksize=1)\n pd_reader = pandas.read_csv(TEST_CSV_FILENAME, chunksize=1)\n\n modin_df = rdf_reader.get_chunk(1)\n pd_df = pd_reader.get_chunk(1)\n\n df_equals(modin_df, pd_df)\n\n # Tests that read works correctly\n rdf_reader = pd.read_csv(TEST_CSV_FILENAME, chunksize=1)\n pd_reader = pandas.read_csv(TEST_CSV_FILENAME, chunksize=1)\n\n modin_df = rdf_reader.read()\n pd_df = pd_reader.read()\n\n df_equals(modin_df, pd_df)\n\n\ndef test_from_csv_skiprows(make_csv_file):\n make_csv_file()\n\n pandas_df = pandas.read_csv(TEST_CSV_FILENAME, skiprows=2)\n modin_df = pd.read_csv(TEST_CSV_FILENAME, skiprows=2)\n df_equals(modin_df, pandas_df)\n\n pandas_df = pandas.read_csv(\n TEST_CSV_FILENAME, names=[\"c1\", \"c2\", \"c3\", \"c4\"], skiprows=2\n )\n modin_df = pd.read_csv(\n TEST_CSV_FILENAME, names=[\"c1\", \"c2\", \"c3\", \"c4\"], skiprows=2\n )\n df_equals(modin_df, pandas_df)\n\n pandas_df = pandas.read_csv(\n TEST_CSV_FILENAME, names=[\"c1\", \"c2\", \"c3\", \"c4\"], skiprows=lambda x: x % 2\n )\n modin_df = pd.read_csv(\n TEST_CSV_FILENAME, names=[\"c1\", \"c2\", \"c3\", \"c4\"], skiprows=lambda x: x % 2\n )\n df_equals(modin_df, pandas_df)\n\n\[email protected](\n \"encoding\", [\"latin8\", \"ISO-8859-1\", \"latin1\", \"iso-8859-1\", \"cp1252\", \"utf8\"]\n)\ndef test_from_csv_encoding(make_csv_file, encoding):\n make_csv_file(encoding=encoding)\n\n pandas_df = pandas.read_csv(TEST_CSV_FILENAME, encoding=encoding)\n modin_df = pd.read_csv(TEST_CSV_FILENAME, encoding=encoding)\n\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_csv_default_to_pandas_behavior(make_csv_file):\n make_csv_file()\n\n with pytest.warns(UserWarning):\n # Test nrows\n pd.read_csv(TEST_CSV_FILENAME, nrows=10)\n\n with pytest.warns(UserWarning):\n # This tests that we default to pandas on a buffer\n from io import StringIO\n\n pd.read_csv(StringIO(open(TEST_CSV_FILENAME, \"r\").read()))\n\n with pytest.warns(UserWarning):\n pd.read_csv(TEST_CSV_FILENAME, skiprows=lambda x: x in [0, 2])\n\n\ndef test_from_csv_index_col(make_csv_file):\n make_csv_file()\n\n pandas_df = pandas.read_csv(TEST_CSV_FILENAME, index_col=\"col1\")\n modin_df = pd.read_csv(TEST_CSV_FILENAME, index_col=\"col1\")\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_csv_skipfooter(make_csv_file):\n make_csv_file()\n\n pandas_df = pandas.read_csv(TEST_CSV_FILENAME, skipfooter=13)\n modin_df = pd.read_csv(TEST_CSV_FILENAME, skipfooter=13)\n\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_csv_parse_dates(make_csv_file):\n make_csv_file(force=True)\n\n pandas_df = pandas.read_csv(TEST_CSV_FILENAME, parse_dates=[[\"col2\", \"col4\"]])\n modin_df = pd.read_csv(TEST_CSV_FILENAME, parse_dates=[[\"col2\", \"col4\"]])\n df_equals(modin_df, pandas_df)\n\n pandas_df = pandas.read_csv(\n TEST_CSV_FILENAME, parse_dates={\"time\": [\"col2\", \"col4\"]}\n )\n modin_df = pd.read_csv(TEST_CSV_FILENAME, parse_dates={\"time\": [\"col2\", \"col4\"]})\n df_equals(modin_df, pandas_df)\n\n\ndef test_from_csv_newlines_in_quotes():\n pandas_df = pandas.read_csv(\"modin/pandas/test/data/newlines.csv\")\n modin_df = pd.read_csv(\"modin/pandas/test/data/newlines.csv\")\n df_equals(modin_df, pandas_df)\n\n\[email protected](reason=\"No clipboard on Travis\")\ndef test_to_clipboard():\n modin_df = create_test_modin_dataframe()\n pandas_df = create_test_pandas_dataframe()\n\n modin_df.to_clipboard()\n modin_as_clip = pandas.read_clipboard()\n\n pandas_df.to_clipboard()\n pandas_as_clip = pandas.read_clipboard()\n\n assert modin_as_clip.equals(pandas_as_clip)\n\n\ndef test_dataframe_to_csv():\n modin_df = create_test_modin_dataframe()\n pandas_df = create_test_pandas_dataframe()\n\n TEST_CSV_DF_FILENAME = \"test_df.csv\"\n TEST_CSV_pandas_FILENAME = \"test_pandas.csv\"\n\n modin_df.to_csv(TEST_CSV_DF_FILENAME)\n pandas_df.to_csv(TEST_CSV_pandas_FILENAME)\n\n assert assert_files_eq(TEST_CSV_DF_FILENAME, TEST_CSV_pandas_FILENAME)\n\n teardown_test_file(TEST_CSV_pandas_FILENAME)\n teardown_test_file(TEST_CSV_DF_FILENAME)\n\n\ndef test_series_to_csv():\n modin_df = create_test_modin_dataframe()\n pandas_df = create_test_pandas_dataframe()\n\n TEST_CSV_DF_FILENAME = \"test_df.csv\"\n TEST_CSV_pandas_FILENAME = \"test_pandas.csv\"\n\n modin_s = modin_df[\"col1\"]\n pandas_s = pandas_df[\"col1\"]\n modin_s.to_csv(TEST_CSV_DF_FILENAME)\n pandas_s.to_csv(TEST_CSV_pandas_FILENAME)\n\n df_equals(modin_s, pandas_s)\n assert modin_s.name == pandas_s.name\n assert assert_files_eq(TEST_CSV_DF_FILENAME, TEST_CSV_pandas_FILENAME)\n\n teardown_test_file(TEST_CSV_pandas_FILENAME)\n teardown_test_file(TEST_CSV_DF_FILENAME)\n\n\[email protected](reason=\"Defaulting to Pandas\")\ndef test_to_dense():\n modin_df = create_test_modin_dataframe()\n\n with pytest.raises(NotImplementedError):\n modin_df.to_dense()\n\n\ndef test_to_dict():\n modin_df = create_test_modin_dataframe()\n assert modin_df.to_dict() == to_pandas(modin_df).to_dict()\n\n\[email protected](strict=False, reason=\"Flaky test, defaults to pandas\")\ndef test_to_excel():\n modin_df = create_test_modin_dataframe()\n pandas_df = create_test_pandas_dataframe()\n\n TEST_EXCEL_DF_FILENAME = \"test_df.xlsx\"\n TEST_EXCEL_pandas_FILENAME = \"test_pandas.xlsx\"\n\n modin_writer = pandas.ExcelWriter(TEST_EXCEL_DF_FILENAME)\n pandas_writer = pandas.ExcelWriter(TEST_EXCEL_pandas_FILENAME)\n\n modin_df.to_excel(modin_writer)\n pandas_df.to_excel(pandas_writer)\n\n modin_writer.save()\n pandas_writer.save()\n\n assert assert_files_eq(TEST_EXCEL_DF_FILENAME, TEST_EXCEL_pandas_FILENAME)\n\n teardown_test_file(TEST_EXCEL_DF_FILENAME)\n teardown_test_file(TEST_EXCEL_pandas_FILENAME)\n\n\ndef test_to_feather():\n modin_df = create_test_modin_dataframe()\n pandas_df = create_test_pandas_dataframe()\n\n TEST_FEATHER_DF_FILENAME = \"test_df.feather\"\n TEST_FEATHER_pandas_FILENAME = \"test_pandas.feather\"\n\n modin_df.to_feather(TEST_FEATHER_DF_FILENAME)\n pandas_df.to_feather(TEST_FEATHER_pandas_FILENAME)\n\n assert assert_files_eq(TEST_FEATHER_DF_FILENAME, TEST_FEATHER_pandas_FILENAME)\n\n teardown_test_file(TEST_FEATHER_pandas_FILENAME)\n teardown_test_file(TEST_FEATHER_DF_FILENAME)\n\n\ndef test_to_html():\n modin_df = create_test_modin_dataframe()\n pandas_df = create_test_pandas_dataframe()\n\n TEST_HTML_DF_FILENAME = \"test_df.html\"\n TEST_HTML_pandas_FILENAME = \"test_pandas.html\"\n\n modin_df.to_html(TEST_HTML_DF_FILENAME)\n pandas_df.to_html(TEST_HTML_pandas_FILENAME)\n\n assert assert_files_eq(TEST_HTML_DF_FILENAME, TEST_HTML_pandas_FILENAME)\n\n teardown_test_file(TEST_HTML_pandas_FILENAME)\n teardown_test_file(TEST_HTML_DF_FILENAME)\n\n\ndef test_to_json():\n modin_df = create_test_modin_dataframe()\n pandas_df = create_test_pandas_dataframe()\n\n TEST_JSON_DF_FILENAME = \"test_df.json\"\n TEST_JSON_pandas_FILENAME = \"test_pandas.json\"\n\n modin_df.to_json(TEST_JSON_DF_FILENAME)\n pandas_df.to_json(TEST_JSON_pandas_FILENAME)\n\n assert assert_files_eq(TEST_JSON_DF_FILENAME, TEST_JSON_pandas_FILENAME)\n\n teardown_test_file(TEST_JSON_pandas_FILENAME)\n teardown_test_file(TEST_JSON_DF_FILENAME)\n\n\ndef test_to_latex():\n modin_df = create_test_modin_dataframe()\n assert modin_df.to_latex() == to_pandas(modin_df).to_latex()\n\n\ndef test_to_parquet():\n modin_df = create_test_modin_dataframe()\n pandas_df = create_test_pandas_dataframe()\n\n TEST_PARQUET_DF_FILENAME = \"test_df.parquet\"\n TEST_PARQUET_pandas_FILENAME = \"test_pandas.parquet\"\n\n modin_df.to_parquet(TEST_PARQUET_DF_FILENAME)\n pandas_df.to_parquet(TEST_PARQUET_pandas_FILENAME)\n\n assert assert_files_eq(TEST_PARQUET_DF_FILENAME, TEST_PARQUET_pandas_FILENAME)\n\n teardown_test_file(TEST_PARQUET_pandas_FILENAME)\n teardown_test_file(TEST_PARQUET_DF_FILENAME)\n\n\[email protected](reason=\"Defaulting to Pandas\")\ndef test_to_period():\n modin_df = create_test_modin_dataframe()\n\n with pytest.raises(NotImplementedError):\n modin_df.to_period()\n\n\ndef test_to_pickle():\n modin_df = create_test_modin_dataframe()\n pandas_df = create_test_pandas_dataframe()\n\n TEST_PICKLE_DF_FILENAME = \"test_df.pkl\"\n TEST_PICKLE_pandas_FILENAME = \"test_pandas.pkl\"\n\n modin_df.to_pickle(TEST_PICKLE_DF_FILENAME)\n pandas_df.to_pickle(TEST_PICKLE_pandas_FILENAME)\n\n assert assert_files_eq(TEST_PICKLE_DF_FILENAME, TEST_PICKLE_pandas_FILENAME)\n\n teardown_test_file(TEST_PICKLE_pandas_FILENAME)\n teardown_test_file(TEST_PICKLE_DF_FILENAME)\n\n pd.to_pickle(modin_df, TEST_PICKLE_DF_FILENAME)\n pandas.to_pickle(pandas_df, TEST_PICKLE_pandas_FILENAME)\n\n assert assert_files_eq(TEST_PICKLE_DF_FILENAME, TEST_PICKLE_pandas_FILENAME)\n\n teardown_test_file(TEST_PICKLE_pandas_FILENAME)\n teardown_test_file(TEST_PICKLE_DF_FILENAME)\n\n\ndef test_to_sql_without_index(make_sql_connection):\n table_name = \"tbl_without_index\"\n modin_df = create_test_modin_dataframe()\n pandas_df = create_test_pandas_dataframe()\n\n # We do not pass the table name so the fixture won't generate a table\n conn = make_sql_connection(\"test_to_sql.db\")\n modin_df.to_sql(table_name, conn, index=False)\n df_modin_sql = pandas.read_sql(table_name, con=conn)\n\n # We do not pass the table name so the fixture won't generate a table\n conn = make_sql_connection(\"test_to_sql_pandas.db\")\n pandas_df.to_sql(table_name, conn, index=False)\n df_pandas_sql = pandas.read_sql(table_name, con=conn)\n\n assert df_modin_sql.sort_index().equals(df_pandas_sql.sort_index())\n\n\ndef test_to_sql_with_index(make_sql_connection):\n table_name = \"tbl_with_index\"\n modin_df = create_test_modin_dataframe()\n pandas_df = create_test_pandas_dataframe()\n\n # We do not pass the table name so the fixture won't generate a table\n conn = make_sql_connection(\"test_to_sql.db\")\n modin_df.to_sql(table_name, conn)\n df_modin_sql = pandas.read_sql(table_name, con=conn, index_col=\"index\")\n\n # We do not pass the table name so the fixture won't generate a table\n conn = make_sql_connection(\"test_to_sql_pandas.db\")\n pandas_df.to_sql(table_name, conn)\n df_pandas_sql = pandas.read_sql(table_name, con=conn, index_col=\"index\")\n\n assert df_modin_sql.sort_index().equals(df_pandas_sql.sort_index())\n\n\ndef test_to_stata():\n modin_df = create_test_modin_dataframe()\n pandas_df = create_test_pandas_dataframe()\n\n TEST_STATA_DF_FILENAME = \"test_df.stata\"\n TEST_STATA_pandas_FILENAME = \"test_pandas.stata\"\n\n modin_df.to_stata(TEST_STATA_DF_FILENAME)\n pandas_df.to_stata(TEST_STATA_pandas_FILENAME)\n\n assert assert_files_eq(TEST_STATA_DF_FILENAME, TEST_STATA_pandas_FILENAME)\n\n teardown_test_file(TEST_STATA_pandas_FILENAME)\n teardown_test_file(TEST_STATA_DF_FILENAME)\n\n\[email protected](os.name == \"nt\", reason=\"Windows not supported\")\ndef test_HDFStore():\n modin_store = pd.HDFStore(TEST_WRITE_HDF_FILENAME_MODIN)\n pandas_store = pandas.HDFStore(TEST_WRITE_HDF_FILENAME_PANDAS)\n\n modin_df = create_test_modin_dataframe()\n pandas_df = create_test_pandas_dataframe()\n\n modin_store[\"foo\"] = modin_df\n pandas_store[\"foo\"] = pandas_df\n\n assert assert_files_eq(\n TEST_WRITE_HDF_FILENAME_MODIN, TEST_WRITE_HDF_FILENAME_PANDAS\n )\n modin_df = modin_store.get(\"foo\")\n pandas_df = pandas_store.get(\"foo\")\n df_equals(modin_df, pandas_df)\n\n assert isinstance(modin_store, pd.HDFStore)\n\n hdf_file = \"/tmp/test_read_hdf.hdf5\"\n with pd.HDFStore(hdf_file, mode=\"w\") as store:\n store.append(\"data/df1\", pd.DataFrame(np.random.randn(5, 5)))\n store.append(\"data/df2\", pd.DataFrame(np.random.randn(4, 4)))\n\n modin_df = pd.read_hdf(hdf_file, key=\"data/df1\", mode=\"r\")\n pandas_df = pandas.read_hdf(hdf_file, key=\"data/df1\", mode=\"r\")\n df_equals(modin_df, pandas_df)\n\n\ndef test_ExcelFile():\n setup_excel_file(SMALL_ROW_SIZE)\n\n modin_excel_file = pd.ExcelFile(TEST_EXCEL_FILENAME)\n pandas_excel_file = pandas.ExcelFile(TEST_EXCEL_FILENAME)\n\n df_equals(modin_excel_file.parse(), pandas_excel_file.parse())\n\n assert modin_excel_file.io == TEST_EXCEL_FILENAME\n assert isinstance(modin_excel_file, pd.ExcelFile)\n modin_excel_file.close()\n pandas_excel_file.close()\n\n teardown_excel_file()\n\n\ndef test_fwf_file():\n fwf_data = \"\"\"id8141 360.242940 149.910199 11950.7\nid1594 444.953632 166.985655 11788.4\nid1849 364.136849 183.628767 11806.2\nid1230 413.836124 184.375703 11916.8\nid1948 502.953953 173.237159 12468.3\"\"\"\n\n setup_fwf_file(True, fwf_data=fwf_data)\n\n colspecs = [(0, 6), (8, 20), (21, 33), (34, 43)]\n df = pd.read_fwf(TEST_FWF_FILENAME, colspecs=colspecs, header=None, index_col=0)\n assert isinstance(df, pd.DataFrame)\n\n teardown_fwf_file()\n\n\[email protected](\n \"kwargs\",\n [\n {\n \"colspecs\": [\n (0, 11),\n (11, 15),\n (19, 24),\n (27, 32),\n (35, 40),\n (43, 48),\n (51, 56),\n (59, 64),\n (67, 72),\n (75, 80),\n (83, 88),\n (91, 96),\n (99, 104),\n (107, 112),\n ],\n \"names\": [\"stationID\", \"year\", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],\n \"na_values\": [\"-9999\"],\n \"index_col\": [\"stationID\", \"year\"],\n },\n {\n \"widths\": [20, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8],\n \"names\": [\"id\", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],\n \"index_col\": [0],\n },\n ],\n)\ndef test_fwf_file_colspecs_widths(kwargs):\n setup_fwf_file(overwrite=True)\n\n modin_df = pd.read_fwf(TEST_FWF_FILENAME, **kwargs)\n pandas_df = pd.read_fwf(TEST_FWF_FILENAME, **kwargs)\n\n df_equals(modin_df, pandas_df)\n\n\[email protected](\"usecols\", [[\"a\"], [\"a\", \"b\", \"d\"], [0, 1, 3]])\ndef test_fwf_file_usecols(usecols):\n fwf_data = \"\"\"a b c d\nid8141 360.242940 149.910199 11950.7\nid1594 444.953632 166.985655 11788.4\nid1849 364.136849 183.628767 11806.2\nid1230 413.836124 184.375703 11916.8\nid1948 502.953953 173.237159 12468.3\"\"\"\n\n setup_fwf_file(overwrite=True, fwf_data=fwf_data)\n\n pandas_df = pandas.read_fwf(TEST_FWF_FILENAME, usecols=usecols)\n modin_df = pd.read_fwf(TEST_FWF_FILENAME, usecols=usecols)\n\n df_equals(modin_df, pandas_df)\n\n teardown_fwf_file()\n\n\ndef test_fwf_file_chunksize():\n setup_fwf_file(overwrite=True)\n\n # Tests __next__ and correctness of reader as an iterator\n rdf_reader = pd.read_fwf(TEST_FWF_FILENAME, chunksize=5)\n pd_reader = pandas.read_fwf(TEST_FWF_FILENAME, chunksize=5)\n\n for modin_df, pd_df in zip(rdf_reader, pd_reader):\n df_equals(modin_df, pd_df)\n\n # Tests that get_chunk works correctly\n rdf_reader = pd.read_fwf(TEST_FWF_FILENAME, chunksize=1)\n pd_reader = pandas.read_fwf(TEST_FWF_FILENAME, chunksize=1)\n\n modin_df = rdf_reader.get_chunk(1)\n pd_df = pd_reader.get_chunk(1)\n\n df_equals(modin_df, pd_df)\n\n # Tests that read works correctly\n rdf_reader = pd.read_fwf(TEST_FWF_FILENAME, chunksize=1)\n pd_reader = pandas.read_fwf(TEST_FWF_FILENAME, chunksize=1)\n\n modin_df = rdf_reader.read()\n pd_df = pd_reader.read()\n\n df_equals(modin_df, pd_df)\n\n\ndef test_fwf_file_skiprows():\n setup_fwf_file(overwrite=True)\n\n pandas_df = pandas.read_fwf(TEST_FWF_FILENAME, skiprows=2)\n modin_df = pd.read_fwf(TEST_FWF_FILENAME, skiprows=2)\n df_equals(modin_df, pandas_df)\n\n pandas_df = pandas.read_fwf(TEST_FWF_FILENAME, usecols=[0, 4, 7], skiprows=[2, 5])\n modin_df = pd.read_fwf(TEST_FWF_FILENAME, usecols=[0, 4, 7], skiprows=[2, 5])\n df_equals(modin_df, pandas_df)\n\n\ndef test_fwf_file_index_col():\n fwf_data = \"\"\"a b c d\nid8141 360.242940 149.910199 11950.7\nid1594 444.953632 166.985655 11788.4\nid1849 364.136849 183.628767 11806.2\nid1230 413.836124 184.375703 11916.8\nid1948 502.953953 173.237159 12468.3\"\"\"\n\n setup_fwf_file(overwrite=True, fwf_data=fwf_data)\n\n pandas_df = pandas.read_fwf(TEST_FWF_FILENAME, index_col=\"c\")\n modin_df = pd.read_fwf(TEST_FWF_FILENAME, index_col=\"c\")\n df_equals(modin_df, pandas_df)\n\n teardown_fwf_file()\n\n\ndef test_fwf_file_skipfooter():\n setup_fwf_file(overwrite=True)\n\n pandas_df = pandas.read_fwf(TEST_FWF_FILENAME, skipfooter=2)\n modin_df = pd.read_fwf(TEST_FWF_FILENAME, skipfooter=2)\n\n df_equals(modin_df, pandas_df)\n\n\ndef test_fwf_file_parse_dates():\n dates = pandas.date_range(\"2000\", freq=\"h\", periods=10)\n fwf_data = \"col1 col2 col3 col4\"\n for i in range(10, 20):\n fwf_data = fwf_data + \"\\n{col1} {col2} {col3} {col4}\".format(\n col1=str(i),\n col2=str(dates[i - 10].date()),\n col3=str(i),\n col4=str(dates[i - 10].time()),\n )\n\n setup_fwf_file(overwrite=True, fwf_data=fwf_data)\n\n pandas_df = pandas.read_fwf(TEST_FWF_FILENAME, parse_dates=[[\"col2\", \"col4\"]])\n modin_df = pd.read_fwf(TEST_FWF_FILENAME, parse_dates=[[\"col2\", \"col4\"]])\n df_equals(modin_df, pandas_df)\n\n pandas_df = pandas.read_fwf(\n TEST_FWF_FILENAME, parse_dates={\"time\": [\"col2\", \"col4\"]}\n )\n modin_df = pd.read_fwf(TEST_FWF_FILENAME, parse_dates={\"time\": [\"col2\", \"col4\"]})\n df_equals(modin_df, pandas_df)\n\n teardown_fwf_file()\n\n\[email protected](reason=\"Need to verify GBQ access\")\ndef test_from_gbq():\n # Test API, but do not supply credentials until credits can be secured.\n with pytest.raises(\n ValueError, match=\"Could not determine project ID and one was not supplied.\"\n ):\n pd.read_gbq(\"SELECT 1\")\n\n\[email protected](reason=\"Need to verify GBQ access\")\ndef test_to_gbq():\n modin_df = create_test_modin_dataframe()\n # Test API, but do not supply credentials until credits can be secured.\n with pytest.raises(\n ValueError, match=\"Could not determine project ID and one was not supplied.\"\n ):\n modin_df.to_gbq(\"modin.table\")\n\n\ndef test_cleanup():\n filenames = [\n TEST_PARQUET_FILENAME,\n TEST_CSV_FILENAME,\n TEST_JSON_FILENAME,\n TEST_HTML_FILENAME,\n TEST_EXCEL_FILENAME,\n TEST_FEATHER_FILENAME,\n TEST_READ_HDF_FILENAME,\n TEST_WRITE_HDF_FILENAME_MODIN,\n TEST_WRITE_HDF_FILENAME_PANDAS,\n TEST_STATA_FILENAME,\n TEST_PICKLE_FILENAME,\n TEST_SAS_FILENAME,\n TEST_FWF_FILENAME,\n TEST_GBQ_FILENAME,\n ]\n for f in filenames:\n if os.path.exists(f):\n # Need try..except for Windows\n try:\n os.remove(f)\n except PermissionError:\n pass\n", "# Licensed to Modin Development Team under one or more contributor license agreements.\n# See the NOTICE file distributed with this work for additional information regarding\n# copyright ownership. The Modin Development Team licenses this file to you under the\n# Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n# compliance with the License. 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 distributed under\n# the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific language\n# governing permissions and limitations under the License.\n\nimport pytest\nimport numpy as np\nimport pandas\nimport pandas.util.testing as tm\nimport matplotlib\nimport modin.pandas as pd\nfrom modin.pandas.utils import to_pandas\nfrom numpy.testing import assert_array_equal\nimport io\nimport sys\n\nfrom .utils import (\n random_state,\n RAND_LOW,\n RAND_HIGH,\n df_equals,\n df_is_empty,\n arg_keys,\n name_contains,\n test_data_values,\n test_data_keys,\n test_data_with_duplicates_values,\n test_data_with_duplicates_keys,\n numeric_dfs,\n no_numeric_dfs,\n test_func_keys,\n test_func_values,\n query_func_keys,\n query_func_values,\n agg_func_keys,\n agg_func_values,\n numeric_agg_funcs,\n quantiles_keys,\n quantiles_values,\n indices_keys,\n indices_values,\n axis_keys,\n axis_values,\n bool_arg_keys,\n bool_arg_values,\n int_arg_keys,\n int_arg_values,\n eval_general,\n create_test_dfs,\n)\n\npd.DEFAULT_NPARTITIONS = 4\n\n# Force matplotlib to not use any Xwindows backend.\nmatplotlib.use(\"Agg\")\n\n\ndef eval_insert(modin_df, pandas_df, **kwargs):\n _kwargs = {\"loc\": 0, \"col\": \"New column\"}\n _kwargs.update(kwargs)\n\n eval_general(\n modin_df,\n pandas_df,\n operation=lambda df, **kwargs: df.insert(**kwargs),\n **_kwargs,\n )\n\n\nclass TestDataFrameBinary:\n def inter_df_math_helper(self, modin_df, pandas_df, op):\n # Test dataframe to dataframe\n try:\n pandas_result = getattr(pandas_df, op)(pandas_df)\n except Exception as e:\n with pytest.raises(type(e)):\n getattr(modin_df, op)(modin_df)\n else:\n modin_result = getattr(modin_df, op)(modin_df)\n df_equals(modin_result, pandas_result)\n\n # Test dataframe to int\n try:\n pandas_result = getattr(pandas_df, op)(4)\n except Exception as e:\n with pytest.raises(type(e)):\n getattr(modin_df, op)(4)\n else:\n modin_result = getattr(modin_df, op)(4)\n df_equals(modin_result, pandas_result)\n\n # Test dataframe to float\n try:\n pandas_result = getattr(pandas_df, op)(4.0)\n except Exception as e:\n with pytest.raises(type(e)):\n getattr(modin_df, op)(4.0)\n else:\n modin_result = getattr(modin_df, op)(4.0)\n df_equals(modin_result, pandas_result)\n\n # Test transposed dataframes to float\n try:\n pandas_result = getattr(pandas_df.T, op)(4.0)\n except Exception as e:\n with pytest.raises(type(e)):\n getattr(modin_df.T, op)(4.0)\n else:\n modin_result = getattr(modin_df.T, op)(4.0)\n df_equals(modin_result, pandas_result)\n\n frame_data = {\n \"{}_other\".format(modin_df.columns[0]): [0, 2],\n modin_df.columns[0]: [0, 19],\n modin_df.columns[1]: [1, 1],\n }\n modin_df2 = pd.DataFrame(frame_data)\n pandas_df2 = pandas.DataFrame(frame_data)\n\n # Test dataframe to different dataframe shape\n try:\n pandas_result = getattr(pandas_df, op)(pandas_df2)\n except Exception as e:\n with pytest.raises(type(e)):\n getattr(modin_df, op)(modin_df2)\n else:\n modin_result = getattr(modin_df, op)(modin_df2)\n df_equals(modin_result, pandas_result)\n\n # Test dataframe fill value\n try:\n pandas_result = getattr(pandas_df, op)(pandas_df2, fill_value=0)\n except Exception as e:\n with pytest.raises(type(e)):\n getattr(modin_df, op)(modin_df2, fill_value=0)\n else:\n modin_result = getattr(modin_df, op)(modin_df2, fill_value=0)\n df_equals(modin_result, pandas_result)\n\n # Test dataframe to list\n list_test = random_state.randint(RAND_LOW, RAND_HIGH, size=(modin_df.shape[1]))\n try:\n pandas_result = getattr(pandas_df, op)(list_test, axis=1)\n except Exception as e:\n with pytest.raises(type(e)):\n getattr(modin_df, op)(list_test, axis=1)\n else:\n modin_result = getattr(modin_df, op)(list_test, axis=1)\n df_equals(modin_result, pandas_result)\n\n # Test dataframe to series axis=0\n series_test_modin = modin_df[modin_df.columns[0]]\n series_test_pandas = pandas_df[pandas_df.columns[0]]\n try:\n pandas_result = getattr(pandas_df, op)(series_test_pandas, axis=0)\n except Exception as e:\n with pytest.raises(type(e)):\n getattr(modin_df, op)(series_test_modin, axis=0)\n else:\n modin_result = getattr(modin_df, op)(series_test_modin, axis=0)\n df_equals(modin_result, pandas_result)\n\n # Test dataframe to series axis=1\n series_test_modin = modin_df.iloc[0]\n series_test_pandas = pandas_df.iloc[0]\n try:\n pandas_result = getattr(pandas_df, op)(series_test_pandas, axis=1)\n except Exception as e:\n with pytest.raises(type(e)):\n getattr(modin_df, op)(series_test_modin, axis=1)\n else:\n modin_result = getattr(modin_df, op)(series_test_modin, axis=1)\n df_equals(modin_result, pandas_result)\n\n # Test dataframe to list axis=1\n series_test_modin = series_test_pandas = list(pandas_df.iloc[0])\n try:\n pandas_result = getattr(pandas_df, op)(series_test_pandas, axis=1)\n except Exception as e:\n with pytest.raises(type(e)):\n getattr(modin_df, op)(series_test_modin, axis=1)\n else:\n modin_result = getattr(modin_df, op)(series_test_modin, axis=1)\n df_equals(modin_result, pandas_result)\n\n # Test dataframe to list axis=0\n series_test_modin = series_test_pandas = list(pandas_df[pandas_df.columns[0]])\n try:\n pandas_result = getattr(pandas_df, op)(series_test_pandas, axis=0)\n except Exception as e:\n with pytest.raises(type(e)):\n getattr(modin_df, op)(series_test_modin, axis=0)\n else:\n modin_result = getattr(modin_df, op)(series_test_modin, axis=0)\n df_equals(modin_result, pandas_result)\n\n # Test dataframe to series missing values\n series_test_modin = modin_df.iloc[0, :-2]\n series_test_pandas = pandas_df.iloc[0, :-2]\n try:\n pandas_result = getattr(pandas_df, op)(series_test_pandas, axis=1)\n except Exception as e:\n with pytest.raises(type(e)):\n getattr(modin_df, op)(series_test_modin, axis=1)\n else:\n modin_result = getattr(modin_df, op)(series_test_modin, axis=1)\n df_equals(modin_result, pandas_result)\n\n # Test dataframe to series with different index\n series_test_modin = modin_df[modin_df.columns[0]].reset_index(drop=True)\n series_test_pandas = pandas_df[pandas_df.columns[0]].reset_index(drop=True)\n try:\n pandas_result = getattr(pandas_df, op)(series_test_pandas, axis=0)\n except Exception as e:\n with pytest.raises(type(e)):\n getattr(modin_df, op)(series_test_modin, axis=0)\n else:\n modin_result = getattr(modin_df, op)(series_test_modin, axis=0)\n df_equals(modin_result, pandas_result)\n\n # Level test\n new_idx = pandas.MultiIndex.from_tuples(\n [(i // 4, i // 2, i) for i in modin_df.index]\n )\n modin_df_multi_level = modin_df.copy()\n modin_df_multi_level.index = new_idx\n # Defaults to pandas\n with pytest.warns(UserWarning):\n # Operation against self for sanity check\n getattr(modin_df_multi_level, op)(modin_df_multi_level, axis=0, level=1)\n\n @pytest.mark.parametrize(\n \"function\",\n [\n \"add\",\n \"div\",\n \"divide\",\n \"floordiv\",\n \"mod\",\n \"mul\",\n \"multiply\",\n \"pow\",\n \"sub\",\n \"subtract\",\n \"truediv\",\n \"__div__\",\n \"__add__\",\n \"__radd__\",\n \"__mul__\",\n \"__rmul__\",\n \"__pow__\",\n \"__rpow__\",\n \"__sub__\",\n \"__floordiv__\",\n \"__rfloordiv__\",\n \"__truediv__\",\n \"__rtruediv__\",\n \"__mod__\",\n \"__rmod__\",\n \"__rdiv__\",\n ],\n )\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_math_functions(self, data, function):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n self.inter_df_math_helper(modin_df, pandas_df, function)\n\n @pytest.mark.parametrize(\"other\", [\"as_left\", 4, 4.0, \"a\"])\n @pytest.mark.parametrize(\"op\", [\"eq\", \"ge\", \"gt\", \"le\", \"lt\", \"ne\"])\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_comparison(self, data, op, other):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n eval_general(\n modin_df,\n pandas_df,\n operation=lambda df, **kwargs: getattr(df, op)(\n df if other == \"as_left\" else other\n ),\n )\n\n @pytest.mark.parametrize(\"op\", [\"eq\", \"ge\", \"gt\", \"le\", \"lt\", \"ne\"])\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_multi_level_comparison(self, data, op):\n modin_df_multi_level = pd.DataFrame(data)\n\n new_idx = pandas.MultiIndex.from_tuples(\n [(i // 4, i // 2, i) for i in modin_df_multi_level.index]\n )\n modin_df_multi_level.index = new_idx\n\n # Defaults to pandas\n with pytest.warns(UserWarning):\n # Operation against self for sanity check\n getattr(modin_df_multi_level, op)(modin_df_multi_level, axis=0, level=1)\n\n # Test dataframe right operations\n def inter_df_math_right_ops_helper(self, modin_df, pandas_df, op):\n try:\n pandas_result = getattr(pandas_df, op)(4)\n except Exception as e:\n with pytest.raises(type(e)):\n getattr(modin_df, op)(4)\n else:\n modin_result = getattr(modin_df, op)(4)\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = getattr(pandas_df, op)(4.0)\n except Exception as e:\n with pytest.raises(type(e)):\n getattr(modin_df, op)(4.0)\n else:\n modin_result = getattr(modin_df, op)(4.0)\n df_equals(modin_result, pandas_result)\n\n new_idx = pandas.MultiIndex.from_tuples(\n [(i // 4, i // 2, i) for i in modin_df.index]\n )\n modin_df_multi_level = modin_df.copy()\n modin_df_multi_level.index = new_idx\n\n # Defaults to pandas\n with pytest.warns(UserWarning):\n # Operation against self for sanity check\n getattr(modin_df_multi_level, op)(modin_df_multi_level, axis=0, level=1)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_radd(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n self.inter_df_math_right_ops_helper(modin_df, pandas_df, \"radd\")\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_rdiv(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n self.inter_df_math_right_ops_helper(modin_df, pandas_df, \"rdiv\")\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_rfloordiv(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n self.inter_df_math_right_ops_helper(modin_df, pandas_df, \"rfloordiv\")\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_rmod(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n self.inter_df_math_right_ops_helper(modin_df, pandas_df, \"rmod\")\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_rmul(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n self.inter_df_math_right_ops_helper(modin_df, pandas_df, \"rmul\")\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_rpow(self, request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n # TODO: Revert to others once we have an efficient way of preprocessing for positive values\n # We need to check that negative integers are not used efficiently\n if \"100x100\" not in request.node.name:\n self.inter_df_math_right_ops_helper(modin_df, pandas_df, \"rpow\")\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_rsub(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n self.inter_df_math_right_ops_helper(modin_df, pandas_df, \"rsub\")\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_rtruediv(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n self.inter_df_math_right_ops_helper(modin_df, pandas_df, \"rtruediv\")\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___rsub__(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n self.inter_df_math_right_ops_helper(modin_df, pandas_df, \"__rsub__\")\n\n # END test dataframe right operations\n\n def test_equals(self):\n frame_data = {\"col1\": [2.9, 3, 3, 3], \"col2\": [2, 3, 4, 1]}\n modin_df1 = pd.DataFrame(frame_data)\n modin_df2 = pd.DataFrame(frame_data)\n\n assert modin_df1.equals(modin_df2)\n\n df_equals(modin_df1, modin_df2)\n df_equals(modin_df1, pd.DataFrame(modin_df1))\n\n frame_data = {\"col1\": [2.9, 3, 3, 3], \"col2\": [2, 3, 5, 1]}\n modin_df3 = pd.DataFrame(frame_data, index=list(\"abcd\"))\n\n assert not modin_df1.equals(modin_df3)\n\n with pytest.raises(AssertionError):\n df_equals(modin_df3, modin_df1)\n\n with pytest.raises(AssertionError):\n df_equals(modin_df3, modin_df2)\n\n assert modin_df1.equals(modin_df2._query_compiler.to_pandas())\n\n\nclass TestDataFrameMapMetadata:\n def test_indexing(self):\n modin_df = pd.DataFrame(\n dict(a=[1, 2, 3], b=[4, 5, 6], c=[7, 8, 9]), index=[\"a\", \"b\", \"c\"]\n )\n pandas_df = pandas.DataFrame(\n dict(a=[1, 2, 3], b=[4, 5, 6], c=[7, 8, 9]), index=[\"a\", \"b\", \"c\"]\n )\n\n modin_result = modin_df\n pandas_result = pandas_df\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df[\"b\"]\n pandas_result = pandas_df[\"b\"]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df[[\"b\"]]\n pandas_result = pandas_df[[\"b\"]]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df[[\"b\", \"a\"]]\n pandas_result = pandas_df[[\"b\", \"a\"]]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[\"b\"]\n pandas_result = pandas_df.loc[\"b\"]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[[\"b\"]]\n pandas_result = pandas_df.loc[[\"b\"]]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[[\"b\", \"a\"]]\n pandas_result = pandas_df.loc[[\"b\", \"a\"]]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[[\"b\", \"a\"], [\"a\", \"c\"]]\n pandas_result = pandas_df.loc[[\"b\", \"a\"], [\"a\", \"c\"]]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[:, [\"a\", \"c\"]]\n pandas_result = pandas_df.loc[:, [\"a\", \"c\"]]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[:, [\"c\"]]\n pandas_result = pandas_df.loc[:, [\"c\"]]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[[]]\n pandas_result = pandas_df.loc[[]]\n df_equals(modin_result, pandas_result)\n\n def test_empty_df(self):\n df = pd.DataFrame(index=[\"a\", \"b\"])\n df_is_empty(df)\n tm.assert_index_equal(df.index, pd.Index([\"a\", \"b\"]))\n assert len(df.columns) == 0\n\n df = pd.DataFrame(columns=[\"a\", \"b\"])\n df_is_empty(df)\n assert len(df.index) == 0\n tm.assert_index_equal(df.columns, pd.Index([\"a\", \"b\"]))\n\n df = pd.DataFrame()\n df_is_empty(df)\n assert len(df.index) == 0\n assert len(df.columns) == 0\n\n df = pd.DataFrame(index=[\"a\", \"b\"])\n df_is_empty(df)\n tm.assert_index_equal(df.index, pd.Index([\"a\", \"b\"]))\n assert len(df.columns) == 0\n\n df = pd.DataFrame(columns=[\"a\", \"b\"])\n df_is_empty(df)\n assert len(df.index) == 0\n tm.assert_index_equal(df.columns, pd.Index([\"a\", \"b\"]))\n\n df = pd.DataFrame()\n df_is_empty(df)\n assert len(df.index) == 0\n assert len(df.columns) == 0\n\n df = pd.DataFrame()\n pd_df = pandas.DataFrame()\n df[\"a\"] = [1, 2, 3, 4, 5]\n pd_df[\"a\"] = [1, 2, 3, 4, 5]\n df_equals(df, pd_df)\n\n df = pd.DataFrame()\n pd_df = pandas.DataFrame()\n df[\"a\"] = list(\"ABCDEF\")\n pd_df[\"a\"] = list(\"ABCDEF\")\n df_equals(df, pd_df)\n\n df = pd.DataFrame()\n pd_df = pandas.DataFrame()\n df[\"a\"] = pd.Series([1, 2, 3, 4, 5])\n pd_df[\"a\"] = pandas.Series([1, 2, 3, 4, 5])\n df_equals(df, pd_df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_abs(self, request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.abs()\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.abs()\n else:\n modin_result = modin_df.abs()\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_add_prefix(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n test_prefix = \"TEST\"\n new_modin_df = modin_df.add_prefix(test_prefix)\n new_pandas_df = pandas_df.add_prefix(test_prefix)\n df_equals(new_modin_df.columns, new_pandas_df.columns)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"testfunc\", test_func_values, ids=test_func_keys)\n def test_applymap(self, request, data, testfunc):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n with pytest.raises(ValueError):\n x = 2\n modin_df.applymap(x)\n\n try:\n pandas_result = pandas_df.applymap(testfunc)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.applymap(testfunc)\n else:\n modin_result = modin_df.applymap(testfunc)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"testfunc\", test_func_values, ids=test_func_keys)\n def test_applymap_numeric(self, request, data, testfunc):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if name_contains(request.node.name, numeric_dfs):\n try:\n pandas_result = pandas_df.applymap(testfunc)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.applymap(testfunc)\n else:\n modin_result = modin_df.applymap(testfunc)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_add_suffix(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n test_suffix = \"TEST\"\n new_modin_df = modin_df.add_suffix(test_suffix)\n new_pandas_df = pandas_df.add_suffix(test_suffix)\n\n df_equals(new_modin_df.columns, new_pandas_df.columns)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_at(self, request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n # We skip nan datasets because nan != nan\n if \"nan\" not in request.node.name:\n key1 = modin_df.columns[0]\n # Scaler\n assert modin_df.at[0, key1] == pandas_df.at[0, key1]\n\n # Series\n df_equals(modin_df.loc[0].at[key1], pandas_df.loc[0].at[key1])\n\n # Write Item\n modin_df_copy = modin_df.copy()\n pandas_df_copy = pandas_df.copy()\n modin_df_copy.at[1, key1] = modin_df.at[0, key1]\n pandas_df_copy.at[1, key1] = pandas_df.at[0, key1]\n df_equals(modin_df_copy, pandas_df_copy)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_axes(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n for modin_axis, pd_axis in zip(modin_df.axes, pandas_df.axes):\n assert np.array_equal(modin_axis, pd_axis)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_copy(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data) # noqa F841\n\n # pandas_df is unused but there so there won't be confusing list comprehension\n # stuff in the pytest.mark.parametrize\n new_modin_df = modin_df.copy()\n\n assert new_modin_df is not modin_df\n assert np.array_equal(\n new_modin_df._query_compiler._modin_frame._partitions,\n modin_df._query_compiler._modin_frame._partitions,\n )\n assert new_modin_df is not modin_df\n df_equals(new_modin_df, modin_df)\n\n # Shallow copy tests\n modin_df = pd.DataFrame(data)\n modin_df_cp = modin_df.copy(False)\n\n modin_df[modin_df.columns[0]] = 0\n df_equals(modin_df, modin_df_cp)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_dtypes(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.dtypes, pandas_df.dtypes)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"key\", indices_values, ids=indices_keys)\n def test_get(self, data, key):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.get(key), pandas_df.get(key))\n df_equals(\n modin_df.get(key, default=\"default\"), pandas_df.get(key, default=\"default\")\n )\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\n \"dummy_na\", bool_arg_values, ids=arg_keys(\"dummy_na\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"drop_first\", bool_arg_values, ids=arg_keys(\"drop_first\", bool_arg_keys)\n )\n def test_get_dummies(self, request, data, dummy_na, drop_first):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas.get_dummies(\n pandas_df, dummy_na=dummy_na, drop_first=drop_first\n )\n except Exception as e:\n with pytest.raises(type(e)):\n pd.get_dummies(modin_df, dummy_na=dummy_na, drop_first=drop_first)\n else:\n modin_result = pd.get_dummies(\n modin_df, dummy_na=dummy_na, drop_first=drop_first\n )\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_isna(self, data):\n pandas_df = pandas.DataFrame(data)\n modin_df = pd.DataFrame(data)\n\n pandas_result = pandas_df.isna()\n modin_result = modin_df.isna()\n\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_isnull(self, data):\n pandas_df = pandas.DataFrame(data)\n modin_df = pd.DataFrame(data)\n\n pandas_result = pandas_df.isnull()\n modin_result = modin_df.isnull()\n\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_append(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n data_to_append = {\"append_a\": 2, \"append_b\": 1000}\n\n ignore_idx_values = [True, False]\n\n for ignore in ignore_idx_values:\n try:\n pandas_result = pandas_df.append(data_to_append, ignore_index=ignore)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.append(data_to_append, ignore_index=ignore)\n else:\n modin_result = modin_df.append(data_to_append, ignore_index=ignore)\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.append(pandas_df.iloc[-1])\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.append(modin_df.iloc[-1])\n else:\n modin_result = modin_df.append(modin_df.iloc[-1])\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.append(list(pandas_df.iloc[-1]))\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.append(list(modin_df.iloc[-1]))\n else:\n modin_result = modin_df.append(list(modin_df.iloc[-1]))\n df_equals(modin_result, pandas_result)\n\n verify_integrity_values = [True, False]\n\n for verify_integrity in verify_integrity_values:\n try:\n pandas_result = pandas_df.append(\n [pandas_df, pandas_df], verify_integrity=verify_integrity\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.append(\n [modin_df, modin_df], verify_integrity=verify_integrity\n )\n else:\n modin_result = modin_df.append(\n [modin_df, modin_df], verify_integrity=verify_integrity\n )\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.append(\n pandas_df, verify_integrity=verify_integrity\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.append(modin_df, verify_integrity=verify_integrity)\n else:\n modin_result = modin_df.append(\n modin_df, verify_integrity=verify_integrity\n )\n df_equals(modin_result, pandas_result)\n\n def test_astype(self):\n td = pandas.DataFrame(tm.getSeriesData())\n modin_df = pd.DataFrame(td.values, index=td.index, columns=td.columns)\n expected_df = pandas.DataFrame(td.values, index=td.index, columns=td.columns)\n\n modin_df_casted = modin_df.astype(np.int32)\n expected_df_casted = expected_df.astype(np.int32)\n df_equals(modin_df_casted, expected_df_casted)\n\n modin_df_casted = modin_df.astype(np.float64)\n expected_df_casted = expected_df.astype(np.float64)\n df_equals(modin_df_casted, expected_df_casted)\n\n modin_df_casted = modin_df.astype(str)\n expected_df_casted = expected_df.astype(str)\n df_equals(modin_df_casted, expected_df_casted)\n\n modin_df_casted = modin_df.astype(\"category\")\n expected_df_casted = expected_df.astype(\"category\")\n df_equals(modin_df_casted, expected_df_casted)\n\n dtype_dict = {\"A\": np.int32, \"B\": np.int64, \"C\": str}\n modin_df_casted = modin_df.astype(dtype_dict)\n expected_df_casted = expected_df.astype(dtype_dict)\n df_equals(modin_df_casted, expected_df_casted)\n\n # Ignore lint because this is testing bad input\n bad_dtype_dict = {\"B\": np.int32, \"B\": np.int64, \"B\": str} # noqa F601\n modin_df_casted = modin_df.astype(bad_dtype_dict)\n expected_df_casted = expected_df.astype(bad_dtype_dict)\n df_equals(modin_df_casted, expected_df_casted)\n\n modin_df = pd.DataFrame(index=[\"row1\"], columns=[\"col1\"])\n modin_df[\"col1\"][\"row1\"] = 11\n modin_df_casted = modin_df.astype(int)\n expected_df = pandas.DataFrame(index=[\"row1\"], columns=[\"col1\"])\n expected_df[\"col1\"][\"row1\"] = 11\n expected_df_casted = expected_df.astype(int)\n df_equals(modin_df_casted, expected_df_casted)\n\n with pytest.raises(KeyError):\n modin_df.astype({\"not_exists\": np.uint8})\n\n def test_astype_category(self):\n modin_df = pd.DataFrame(\n {\"col1\": [\"A\", \"A\", \"B\", \"B\", \"A\"], \"col2\": [1, 2, 3, 4, 5]}\n )\n pandas_df = pandas.DataFrame(\n {\"col1\": [\"A\", \"A\", \"B\", \"B\", \"A\"], \"col2\": [1, 2, 3, 4, 5]}\n )\n\n modin_result = modin_df.astype({\"col1\": \"category\"})\n pandas_result = pandas_df.astype({\"col1\": \"category\"})\n df_equals(modin_result, pandas_result)\n assert modin_result.dtypes.equals(pandas_result.dtypes)\n\n modin_result = modin_df.astype(\"category\")\n pandas_result = pandas_df.astype(\"category\")\n df_equals(modin_result, pandas_result)\n assert modin_result.dtypes.equals(pandas_result.dtypes)\n\n @pytest.mark.xfail(\n reason=\"Categorical dataframe created in memory don't work yet and categorical dtype is lost\"\n )\n def test_astype_category_large(self):\n series_length = 10_000\n modin_df = pd.DataFrame(\n {\n \"col1\": [\"str{0}\".format(i) for i in range(0, series_length)],\n \"col2\": [i for i in range(0, series_length)],\n }\n )\n pandas_df = pandas.DataFrame(\n {\n \"col1\": [\"str{0}\".format(i) for i in range(0, series_length)],\n \"col2\": [i for i in range(0, series_length)],\n }\n )\n\n modin_result = modin_df.astype({\"col1\": \"category\"})\n pandas_result = pandas_df.astype({\"col1\": \"category\"})\n df_equals(modin_result, pandas_result)\n assert modin_result.dtypes.equals(pandas_result.dtypes)\n\n modin_result = modin_df.astype(\"category\")\n pandas_result = pandas_df.astype(\"category\")\n df_equals(modin_result, pandas_result)\n assert modin_result.dtypes.equals(pandas_result.dtypes)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n def test_clip(self, request, data, axis):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if name_contains(request.node.name, numeric_dfs):\n ind_len = (\n len(modin_df.index)\n if not pandas.DataFrame()._get_axis_number(axis)\n else len(modin_df.columns)\n )\n # set bounds\n lower, upper = np.sort(random_state.random_integers(RAND_LOW, RAND_HIGH, 2))\n lower_list = random_state.random_integers(RAND_LOW, RAND_HIGH, ind_len)\n upper_list = random_state.random_integers(RAND_LOW, RAND_HIGH, ind_len)\n\n # test only upper scalar bound\n modin_result = modin_df.clip(None, upper, axis=axis)\n pandas_result = pandas_df.clip(None, upper, axis=axis)\n df_equals(modin_result, pandas_result)\n\n # test lower and upper scalar bound\n modin_result = modin_df.clip(lower, upper, axis=axis)\n pandas_result = pandas_df.clip(lower, upper, axis=axis)\n df_equals(modin_result, pandas_result)\n\n # test lower and upper list bound on each column\n modin_result = modin_df.clip(lower_list, upper_list, axis=axis)\n pandas_result = pandas_df.clip(lower_list, upper_list, axis=axis)\n df_equals(modin_result, pandas_result)\n\n # test only upper list bound on each column\n modin_result = modin_df.clip(np.nan, upper_list, axis=axis)\n pandas_result = pandas_df.clip(np.nan, upper_list, axis=axis)\n df_equals(modin_result, pandas_result)\n\n with pytest.raises(ValueError):\n modin_df.clip(lower=[1, 2, 3], axis=None)\n\n def test_drop(self):\n frame_data = {\"A\": [1, 2, 3, 4], \"B\": [0, 1, 2, 3]}\n simple = pandas.DataFrame(frame_data)\n modin_simple = pd.DataFrame(frame_data)\n df_equals(modin_simple.drop(\"A\", axis=1), simple[[\"B\"]])\n df_equals(modin_simple.drop([\"A\", \"B\"], axis=\"columns\"), simple[[]])\n df_equals(modin_simple.drop([0, 1, 3], axis=0), simple.loc[[2], :])\n df_equals(modin_simple.drop([0, 3], axis=\"index\"), simple.loc[[1, 2], :])\n\n pytest.raises(ValueError, modin_simple.drop, 5)\n pytest.raises(ValueError, modin_simple.drop, \"C\", 1)\n pytest.raises(ValueError, modin_simple.drop, [1, 5])\n pytest.raises(ValueError, modin_simple.drop, [\"A\", \"C\"], 1)\n\n # errors = 'ignore'\n df_equals(modin_simple.drop(5, errors=\"ignore\"), simple)\n df_equals(modin_simple.drop([0, 5], errors=\"ignore\"), simple.loc[[1, 2, 3], :])\n df_equals(modin_simple.drop(\"C\", axis=1, errors=\"ignore\"), simple)\n df_equals(modin_simple.drop([\"A\", \"C\"], axis=1, errors=\"ignore\"), simple[[\"B\"]])\n\n # non-unique\n nu_df = pandas.DataFrame(\n zip(range(3), range(-3, 1), list(\"abc\")), columns=[\"a\", \"a\", \"b\"]\n )\n modin_nu_df = pd.DataFrame(nu_df)\n df_equals(modin_nu_df.drop(\"a\", axis=1), nu_df[[\"b\"]])\n df_equals(modin_nu_df.drop(\"b\", axis=\"columns\"), nu_df[\"a\"])\n df_equals(modin_nu_df.drop([]), nu_df)\n\n nu_df = nu_df.set_index(pandas.Index([\"X\", \"Y\", \"X\"]))\n nu_df.columns = list(\"abc\")\n modin_nu_df = pd.DataFrame(nu_df)\n df_equals(modin_nu_df.drop(\"X\", axis=\"rows\"), nu_df.loc[[\"Y\"], :])\n df_equals(modin_nu_df.drop([\"X\", \"Y\"], axis=0), nu_df.loc[[], :])\n\n # inplace cache issue\n frame_data = random_state.randn(10, 3)\n df = pandas.DataFrame(frame_data, columns=list(\"abc\"))\n modin_df = pd.DataFrame(frame_data, columns=list(\"abc\"))\n expected = df[~(df.b > 0)]\n modin_df.drop(labels=df[df.b > 0].index, inplace=True)\n df_equals(modin_df, expected)\n\n midx = pd.MultiIndex(\n levels=[[\"lama\", \"cow\", \"falcon\"], [\"speed\", \"weight\", \"length\"]],\n codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]],\n )\n df = pd.DataFrame(\n index=midx,\n columns=[\"big\", \"small\"],\n data=[\n [45, 30],\n [200, 100],\n [1.5, 1],\n [30, 20],\n [250, 150],\n [1.5, 0.8],\n [320, 250],\n [1, 0.8],\n [0.3, 0.2],\n ],\n )\n with pytest.warns(UserWarning):\n df.drop(index=\"length\", level=1)\n\n def test_drop_api_equivalence(self):\n # equivalence of the labels/axis and index/columns API's\n frame_data = [[1, 2, 3], [3, 4, 5], [5, 6, 7]]\n\n modin_df = pd.DataFrame(\n frame_data, index=[\"a\", \"b\", \"c\"], columns=[\"d\", \"e\", \"f\"]\n )\n\n modin_df1 = modin_df.drop(\"a\")\n modin_df2 = modin_df.drop(index=\"a\")\n df_equals(modin_df1, modin_df2)\n\n modin_df1 = modin_df.drop(\"d\", 1)\n modin_df2 = modin_df.drop(columns=\"d\")\n df_equals(modin_df1, modin_df2)\n\n modin_df1 = modin_df.drop(labels=\"e\", axis=1)\n modin_df2 = modin_df.drop(columns=\"e\")\n df_equals(modin_df1, modin_df2)\n\n modin_df1 = modin_df.drop([\"a\"], axis=0)\n modin_df2 = modin_df.drop(index=[\"a\"])\n df_equals(modin_df1, modin_df2)\n\n modin_df1 = modin_df.drop([\"a\"], axis=0).drop([\"d\"], axis=1)\n modin_df2 = modin_df.drop(index=[\"a\"], columns=[\"d\"])\n df_equals(modin_df1, modin_df2)\n\n with pytest.raises(ValueError):\n modin_df.drop(labels=\"a\", index=\"b\")\n\n with pytest.raises(ValueError):\n modin_df.drop(labels=\"a\", columns=\"b\")\n\n with pytest.raises(ValueError):\n modin_df.drop(axis=1)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_drop_transpose(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n modin_result = modin_df.T.drop(columns=[0, 1, 2])\n pandas_result = pandas_df.T.drop(columns=[0, 1, 2])\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.T.drop(index=[\"col3\", \"col1\"])\n pandas_result = pandas_df.T.drop(index=[\"col3\", \"col1\"])\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.T.drop(columns=[0, 1, 2], index=[\"col3\", \"col1\"])\n pandas_result = pandas_df.T.drop(columns=[0, 1, 2], index=[\"col3\", \"col1\"])\n df_equals(modin_result, pandas_result)\n\n def test_droplevel(self):\n df = (\n pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])\n .set_index([0, 1])\n .rename_axis([\"a\", \"b\"])\n )\n df.columns = pd.MultiIndex.from_tuples(\n [(\"c\", \"e\"), (\"d\", \"f\")], names=[\"level_1\", \"level_2\"]\n )\n df.droplevel(\"a\")\n df.droplevel(\"level_2\", axis=1)\n\n @pytest.mark.parametrize(\n \"data\", test_data_with_duplicates_values, ids=test_data_with_duplicates_keys\n )\n @pytest.mark.parametrize(\n \"keep\", [\"last\", \"first\", False], ids=[\"last\", \"first\", \"False\"]\n )\n @pytest.mark.parametrize(\n \"subset\",\n [None, \"col1\", \"name\", (\"col1\", \"col3\"), [\"col1\", \"col3\", \"col7\"]],\n ids=[\"None\", \"string\", \"name\", \"tuple\", \"list\"],\n )\n def test_drop_duplicates(self, data, keep, subset):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_df.drop_duplicates(keep=keep, inplace=False, subset=subset)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.drop_duplicates(keep=keep, inplace=False, subset=subset)\n else:\n df_equals(\n pandas_df.drop_duplicates(keep=keep, inplace=False, subset=subset),\n modin_df.drop_duplicates(keep=keep, inplace=False, subset=subset),\n )\n\n try:\n pandas_results = pandas_df.drop_duplicates(\n keep=keep, inplace=True, subset=subset\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.drop_duplicates(keep=keep, inplace=True, subset=subset)\n else:\n modin_results = modin_df.drop_duplicates(\n keep=keep, inplace=True, subset=subset\n )\n df_equals(modin_results, pandas_results)\n\n def test_drop_duplicates_with_missing_index_values(self):\n data = {\n \"columns\": [\"value\", \"time\", \"id\"],\n \"index\": [\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n 12,\n 13,\n 14,\n 15,\n 20,\n 21,\n 22,\n 23,\n 24,\n 25,\n 26,\n 27,\n 32,\n 33,\n 34,\n 35,\n 36,\n 37,\n 38,\n 39,\n 40,\n 41,\n ],\n \"data\": [\n [\"3\", 1279213398000.0, 88.0],\n [\"3\", 1279204682000.0, 88.0],\n [\"0\", 1245772835000.0, 448.0],\n [\"0\", 1270564258000.0, 32.0],\n [\"0\", 1267106669000.0, 118.0],\n [\"7\", 1300621123000.0, 5.0],\n [\"0\", 1251130752000.0, 957.0],\n [\"0\", 1311683506000.0, 62.0],\n [\"9\", 1283692698000.0, 89.0],\n [\"9\", 1270234253000.0, 64.0],\n [\"0\", 1285088818000.0, 50.0],\n [\"0\", 1218212725000.0, 695.0],\n [\"2\", 1383933968000.0, 348.0],\n [\"0\", 1368227625000.0, 257.0],\n [\"1\", 1454514093000.0, 446.0],\n [\"1\", 1428497427000.0, 134.0],\n [\"1\", 1459184936000.0, 568.0],\n [\"1\", 1502293302000.0, 599.0],\n [\"1\", 1491833358000.0, 829.0],\n [\"1\", 1485431534000.0, 806.0],\n [\"8\", 1351800505000.0, 101.0],\n [\"0\", 1357247721000.0, 916.0],\n [\"0\", 1335804423000.0, 370.0],\n [\"24\", 1327547726000.0, 720.0],\n [\"0\", 1332334140000.0, 415.0],\n [\"0\", 1309543100000.0, 30.0],\n [\"18\", 1309541141000.0, 30.0],\n [\"0\", 1298979435000.0, 48.0],\n [\"14\", 1276098160000.0, 59.0],\n [\"0\", 1233936302000.0, 109.0],\n ],\n }\n\n pandas_df = pandas.DataFrame(\n data[\"data\"], index=data[\"index\"], columns=data[\"columns\"]\n )\n modin_df = pd.DataFrame(\n data[\"data\"], index=data[\"index\"], columns=data[\"columns\"]\n )\n modin_result = modin_df.sort_values([\"id\", \"time\"]).drop_duplicates([\"id\"])\n pandas_result = pandas_df.sort_values([\"id\", \"time\"]).drop_duplicates([\"id\"])\n df_equals(modin_result, pandas_result)\n\n def test_drop_duplicates_after_sort(self):\n data = [\n {\"value\": 1, \"time\": 2},\n {\"value\": 1, \"time\": 1},\n {\"value\": 2, \"time\": 1},\n {\"value\": 2, \"time\": 2},\n ]\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n modin_result = modin_df.sort_values([\"value\", \"time\"]).drop_duplicates(\n [\"value\"]\n )\n pandas_result = pandas_df.sort_values([\"value\", \"time\"]).drop_duplicates(\n [\"value\"]\n )\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\"how\", [\"any\", \"all\"], ids=[\"any\", \"all\"])\n def test_dropna(self, data, axis, how):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n with pytest.raises(ValueError):\n modin_df.dropna(axis=axis, how=\"invalid\")\n\n with pytest.raises(TypeError):\n modin_df.dropna(axis=axis, how=None, thresh=None)\n\n with pytest.raises(KeyError):\n modin_df.dropna(axis=axis, subset=[\"NotExists\"], how=how)\n\n modin_result = modin_df.dropna(axis=axis, how=how)\n pandas_result = pandas_df.dropna(axis=axis, how=how)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_dropna_inplace(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n pandas_result = pandas_df.dropna()\n modin_df.dropna(inplace=True)\n df_equals(modin_df, pandas_result)\n\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n pandas_df.dropna(thresh=2, inplace=True)\n modin_df.dropna(thresh=2, inplace=True)\n df_equals(modin_df, pandas_df)\n\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n pandas_df.dropna(axis=1, how=\"any\", inplace=True)\n modin_df.dropna(axis=1, how=\"any\", inplace=True)\n df_equals(modin_df, pandas_df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_dropna_multiple_axes(self, data):\n modin_df = pd.DataFrame(data)\n\n with pytest.raises(TypeError):\n modin_df.dropna(how=\"all\", axis=[0, 1])\n with pytest.raises(TypeError):\n modin_df.dropna(how=\"all\", axis=(0, 1))\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_dropna_subset(self, request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if \"empty_data\" not in request.node.name:\n column_subset = modin_df.columns[0:2]\n df_equals(\n modin_df.dropna(how=\"all\", subset=column_subset),\n pandas_df.dropna(how=\"all\", subset=column_subset),\n )\n df_equals(\n modin_df.dropna(how=\"any\", subset=column_subset),\n pandas_df.dropna(how=\"any\", subset=column_subset),\n )\n\n row_subset = modin_df.index[0:2]\n df_equals(\n modin_df.dropna(how=\"all\", axis=1, subset=row_subset),\n pandas_df.dropna(how=\"all\", axis=1, subset=row_subset),\n )\n df_equals(\n modin_df.dropna(how=\"any\", axis=1, subset=row_subset),\n pandas_df.dropna(how=\"any\", axis=1, subset=row_subset),\n )\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_dropna_subset_error(self, data):\n modin_df = pd.DataFrame(data)\n\n # pandas_df is unused so there won't be confusing list comprehension\n # stuff in the pytest.mark.parametrize\n with pytest.raises(KeyError):\n modin_df.dropna(subset=list(\"EF\"))\n\n if len(modin_df.columns) < 5:\n with pytest.raises(KeyError):\n modin_df.dropna(axis=1, subset=[4, 5])\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\n \"astype\",\n [\n \"category\",\n pytest.param(\n \"int32\",\n marks=pytest.mark.xfail(\n reason=\"Modin astype() does not raises ValueError at non-numeric argument when Pandas does.\"\n ),\n ),\n \"float\",\n ],\n )\n def test_insert_dtypes(self, data, astype):\n modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)\n\n # categories with NaN works incorrect for now\n if astype == \"category\" and pandas_df.iloc[:, 0].isnull().any():\n return\n\n eval_insert(\n modin_df,\n pandas_df,\n col=\"TypeSaver\",\n value=lambda df: df.iloc[:, 0].astype(astype),\n )\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"loc\", int_arg_values, ids=arg_keys(\"loc\", int_arg_keys))\n def test_insert_loc(self, data, loc):\n modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)\n value = modin_df.iloc[:, 0]\n\n eval_insert(modin_df, pandas_df, loc=loc, value=value)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_insert(self, data):\n modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)\n\n eval_insert(\n modin_df, pandas_df, col=\"Duplicate\", value=lambda df: df[df.columns[0]]\n )\n eval_insert(modin_df, pandas_df, col=\"Scalar\", value=100)\n eval_insert(\n pd.DataFrame(columns=list(\"ab\")),\n pandas.DataFrame(columns=list(\"ab\")),\n col=lambda df: df.columns[0],\n value=lambda df: df[df.columns[0]],\n )\n eval_insert(\n pd.DataFrame(index=modin_df.index),\n pandas.DataFrame(index=pandas_df.index),\n col=lambda df: df.columns[0],\n value=lambda df: df[df.columns[0]],\n )\n eval_insert(\n modin_df,\n pandas_df,\n col=\"DataFrame insert\",\n value=lambda df: df[[df.columns[0]]],\n )\n\n # Bad inserts\n eval_insert(modin_df, pandas_df, col=\"Bad Column\", value=lambda df: df)\n eval_insert(\n modin_df,\n pandas_df,\n col=\"Too Short\",\n value=lambda df: list(df[df.columns[0]])[:-1],\n )\n eval_insert(\n modin_df,\n pandas_df,\n col=lambda df: df.columns[0],\n value=lambda df: df[df.columns[0]],\n )\n eval_insert(\n modin_df,\n pandas_df,\n loc=lambda df: len(df.columns) + 100,\n col=\"Bad Loc\",\n value=100,\n )\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_ndim(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n assert modin_df.ndim == pandas_df.ndim\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_notna(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.notna(), pandas_df.notna())\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_notnull(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.notnull(), pandas_df.notnull())\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_round(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.round(), pandas_df.round())\n df_equals(modin_df.round(1), pandas_df.round(1))\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n def test_set_axis(self, data, axis):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n x = pandas.DataFrame()._get_axis_number(axis)\n index = modin_df.columns if x else modin_df.index\n labels = [\"{0}_{1}\".format(index[i], i) for i in range(modin_df.shape[x])]\n\n modin_result = modin_df.set_axis(labels, axis=axis, inplace=False)\n pandas_result = pandas_df.set_axis(labels, axis=axis, inplace=False)\n df_equals(modin_result, pandas_result)\n\n modin_df_copy = modin_df.copy()\n modin_df.set_axis(labels, axis=axis, inplace=True)\n\n # Check that the copy and original are different\n try:\n df_equals(modin_df, modin_df_copy)\n except AssertionError:\n assert True\n else:\n assert False\n\n pandas_df.set_axis(labels, axis=axis, inplace=True)\n df_equals(modin_df, pandas_df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\n \"drop\", bool_arg_values, ids=arg_keys(\"drop\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"append\", bool_arg_values, ids=arg_keys(\"append\", bool_arg_keys)\n )\n def test_set_index(self, request, data, drop, append):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if \"empty_data\" not in request.node.name:\n key = modin_df.columns[0]\n modin_result = modin_df.set_index(\n key, drop=drop, append=append, inplace=False\n )\n pandas_result = pandas_df.set_index(\n key, drop=drop, append=append, inplace=False\n )\n df_equals(modin_result, pandas_result)\n\n modin_df_copy = modin_df.copy()\n modin_df.set_index(key, drop=drop, append=append, inplace=True)\n\n # Check that the copy and original are different\n try:\n df_equals(modin_df, modin_df_copy)\n except AssertionError:\n assert True\n else:\n assert False\n\n pandas_df.set_index(key, drop=drop, append=append, inplace=True)\n df_equals(modin_df, pandas_df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_shape(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n assert modin_df.shape == pandas_df.shape\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_size(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n assert modin_df.size == pandas_df.size\n\n def test_squeeze(self):\n frame_data = {\n \"col1\": [0, 1, 2, 3],\n \"col2\": [4, 5, 6, 7],\n \"col3\": [8, 9, 10, 11],\n \"col4\": [12, 13, 14, 15],\n \"col5\": [0, 0, 0, 0],\n }\n frame_data_2 = {\"col1\": [0, 1, 2, 3]}\n frame_data_3 = {\n \"col1\": [0],\n \"col2\": [4],\n \"col3\": [8],\n \"col4\": [12],\n \"col5\": [0],\n }\n frame_data_4 = {\"col1\": [2]}\n frame_data_5 = {\"col1\": [\"string\"]}\n # Different data for different cases\n pandas_df = pandas.DataFrame(frame_data).squeeze()\n modin_df = pd.DataFrame(frame_data).squeeze()\n df_equals(modin_df, pandas_df)\n\n pandas_df_2 = pandas.DataFrame(frame_data_2).squeeze()\n modin_df_2 = pd.DataFrame(frame_data_2).squeeze()\n df_equals(modin_df_2, pandas_df_2)\n\n pandas_df_3 = pandas.DataFrame(frame_data_3).squeeze()\n modin_df_3 = pd.DataFrame(frame_data_3).squeeze()\n df_equals(modin_df_3, pandas_df_3)\n\n pandas_df_4 = pandas.DataFrame(frame_data_4).squeeze()\n modin_df_4 = pd.DataFrame(frame_data_4).squeeze()\n df_equals(modin_df_4, pandas_df_4)\n\n pandas_df_5 = pandas.DataFrame(frame_data_5).squeeze()\n modin_df_5 = pd.DataFrame(frame_data_5).squeeze()\n df_equals(modin_df_5, pandas_df_5)\n\n data = [\n [\n pd.Timestamp(\"2019-01-02\"),\n pd.Timestamp(\"2019-01-03\"),\n pd.Timestamp(\"2019-01-04\"),\n pd.Timestamp(\"2019-01-05\"),\n ],\n [1, 1, 1, 2],\n ]\n df = pd.DataFrame(data, index=[\"date\", \"value\"]).T\n pf = pandas.DataFrame(data, index=[\"date\", \"value\"]).T\n df.set_index(\"date\", inplace=True)\n pf.set_index(\"date\", inplace=True)\n df_equals(df.iloc[0], pf.iloc[0])\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_transpose(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.T, pandas_df.T)\n df_equals(modin_df.transpose(), pandas_df.transpose())\n\n # Test for map across full axis for select indices\n df_equals(modin_df.T.dropna(), pandas_df.T.dropna())\n # Test for map across full axis\n df_equals(modin_df.T.nunique(), pandas_df.T.nunique())\n # Test for map across blocks\n df_equals(modin_df.T.notna(), pandas_df.T.notna())\n\n @pytest.mark.parametrize(\n \"data, other_data\",\n [\n ({\"A\": [1, 2, 3], \"B\": [400, 500, 600]}, {\"B\": [4, 5, 6], \"C\": [7, 8, 9]}),\n (\n {\"A\": [\"a\", \"b\", \"c\"], \"B\": [\"x\", \"y\", \"z\"]},\n {\"B\": [\"d\", \"e\", \"f\", \"g\", \"h\", \"i\"]},\n ),\n ({\"A\": [1, 2, 3], \"B\": [400, 500, 600]}, {\"B\": [4, np.nan, 6]}),\n ],\n )\n def test_update(self, data, other_data):\n modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)\n other_modin_df, other_pandas_df = (\n pd.DataFrame(other_data),\n pandas.DataFrame(other_data),\n )\n modin_df.update(other_modin_df)\n pandas_df.update(other_pandas_df)\n df_equals(modin_df, pandas_df)\n\n with pytest.raises(ValueError):\n modin_df.update(other_modin_df, errors=\"raise\")\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___neg__(self, request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.__neg__()\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.__neg__()\n else:\n modin_result = modin_df.__neg__()\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___invert__(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n try:\n pandas_result = ~pandas_df\n except Exception as e:\n with pytest.raises(type(e)):\n repr(~modin_df)\n else:\n modin_result = ~modin_df\n df_equals(modin_result, pandas_result)\n\n def test___hash__(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n try:\n pd.DataFrame(data).__hash__()\n except TypeError:\n pass\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___delitem__(self, request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if \"empty_data\" not in request.node.name:\n key = pandas_df.columns[0]\n\n modin_df = modin_df.copy()\n pandas_df = pandas_df.copy()\n modin_df.__delitem__(key)\n pandas_df.__delitem__(key)\n df_equals(modin_df, pandas_df)\n\n # Issue 2027\n last_label = pandas_df.iloc[:, -1].name\n modin_df.__delitem__(last_label)\n pandas_df.__delitem__(last_label)\n df_equals(modin_df, pandas_df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___nonzero__(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data) # noqa F841\n\n with pytest.raises(ValueError):\n # Always raises ValueError\n modin_df.__nonzero__()\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___abs__(self, request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = abs(pandas_df)\n except Exception as e:\n with pytest.raises(type(e)):\n abs(modin_df)\n else:\n modin_result = abs(modin_df)\n df_equals(modin_result, pandas_result)\n\n def test___round__(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).__round__()\n\n\nclass TestDataFrameUDF:\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\"func\", agg_func_values, ids=agg_func_keys)\n def test_agg(self, data, axis, func):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.agg(func, axis)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.agg(func, axis)\n else:\n modin_result = modin_df.agg(func, axis)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\"func\", agg_func_values, ids=agg_func_keys)\n def test_agg_numeric(self, request, data, axis, func):\n if name_contains(request.node.name, numeric_agg_funcs) and name_contains(\n request.node.name, numeric_dfs\n ):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.agg(func, axis)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.agg(func, axis)\n else:\n modin_result = modin_df.agg(func, axis)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\"func\", agg_func_values, ids=agg_func_keys)\n def test_aggregate(self, request, data, func, axis):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.aggregate(func, axis)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.aggregate(func, axis)\n else:\n modin_result = modin_df.aggregate(func, axis)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\"func\", agg_func_values, ids=agg_func_keys)\n def test_aggregate_numeric(self, request, data, axis, func):\n if name_contains(request.node.name, numeric_agg_funcs) and name_contains(\n request.node.name, numeric_dfs\n ):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.agg(func, axis)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.agg(func, axis)\n else:\n modin_result = modin_df.agg(func, axis)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_aggregate_error_checking(self, data):\n modin_df = pd.DataFrame(data)\n\n assert modin_df.aggregate(\"ndim\") == 2\n\n with pytest.warns(UserWarning):\n modin_df.aggregate(\n {modin_df.columns[0]: \"sum\", modin_df.columns[1]: \"mean\"}\n )\n\n with pytest.warns(UserWarning):\n modin_df.aggregate(\"cumproduct\")\n\n with pytest.raises(ValueError):\n modin_df.aggregate(\"NOT_EXISTS\")\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\"func\", agg_func_values, ids=agg_func_keys)\n def test_apply(self, request, data, func, axis):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n with pytest.raises(TypeError):\n modin_df.apply({\"row\": func}, axis=1)\n\n try:\n pandas_result = pandas_df.apply(func, axis)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.apply(func, axis)\n else:\n modin_result = modin_df.apply(func, axis)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"axis\", [0, 1])\n @pytest.mark.parametrize(\"level\", [None, -1, 0, 1])\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"func\", [\"count\", \"sum\", \"mean\", \"all\", \"kurt\"])\n def test_apply_text_func_with_level(self, level, data, func, axis):\n func_kwargs = {\"level\": level, \"axis\": axis}\n rows_number = len(next(iter(data.values()))) # length of the first data column\n level_0 = np.random.choice([0, 1, 2], rows_number)\n level_1 = np.random.choice([3, 4, 5], rows_number)\n index = pd.MultiIndex.from_arrays([level_0, level_1])\n\n eval_general(\n pd.DataFrame(data, index=index),\n pandas.DataFrame(data, index=index),\n lambda df, *args, **kwargs: df.apply(func, *args, **kwargs),\n **func_kwargs,\n )\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n def test_apply_args(self, data, axis):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n def apply_func(series, y):\n try:\n return series + y\n except TypeError:\n return series.map(str) + str(y)\n\n modin_result = modin_df.apply(apply_func, axis=axis, args=(1,))\n pandas_result = pandas_df.apply(apply_func, axis=axis, args=(1,))\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.apply(apply_func, axis=axis, args=(\"_A\",))\n pandas_result = pandas_df.apply(apply_func, axis=axis, args=(\"_A\",))\n df_equals(modin_result, pandas_result)\n\n def test_apply_metadata(self):\n def add(a, b, c):\n return a + b + c\n\n data = {\"A\": [1, 2, 3], \"B\": [4, 5, 6], \"C\": [7, 8, 9]}\n\n modin_df = pd.DataFrame(data)\n modin_df[\"add\"] = modin_df.apply(\n lambda row: add(row[\"A\"], row[\"B\"], row[\"C\"]), axis=1\n )\n\n pandas_df = pandas.DataFrame(data)\n pandas_df[\"add\"] = pandas_df.apply(\n lambda row: add(row[\"A\"], row[\"B\"], row[\"C\"]), axis=1\n )\n df_equals(modin_df, pandas_df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"func\", agg_func_values, ids=agg_func_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n def test_apply_numeric(self, request, data, func, axis):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if name_contains(request.node.name, numeric_dfs):\n try:\n pandas_result = pandas_df.apply(func, axis)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.apply(func, axis)\n else:\n modin_result = modin_df.apply(func, axis)\n df_equals(modin_result, pandas_result)\n\n if \"empty_data\" not in request.node.name:\n key = modin_df.columns[0]\n modin_result = modin_df.apply(lambda df: df.drop(key), axis=1)\n pandas_result = pandas_df.apply(lambda df: df.drop(key), axis=1)\n df_equals(modin_result, pandas_result)\n\n def test_eval_df_use_case(self):\n frame_data = {\"a\": random_state.randn(10), \"b\": random_state.randn(10)}\n df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data)\n\n # test eval for series results\n tmp_pandas = df.eval(\"arctan2(sin(a), b)\", engine=\"python\", parser=\"pandas\")\n tmp_modin = modin_df.eval(\n \"arctan2(sin(a), b)\", engine=\"python\", parser=\"pandas\"\n )\n\n assert isinstance(tmp_modin, pd.Series)\n df_equals(tmp_modin, tmp_pandas)\n\n # Test not inplace assignments\n tmp_pandas = df.eval(\"e = arctan2(sin(a), b)\", engine=\"python\", parser=\"pandas\")\n tmp_modin = modin_df.eval(\n \"e = arctan2(sin(a), b)\", engine=\"python\", parser=\"pandas\"\n )\n df_equals(tmp_modin, tmp_pandas)\n\n # Test inplace assignments\n df.eval(\n \"e = arctan2(sin(a), b)\", engine=\"python\", parser=\"pandas\", inplace=True\n )\n modin_df.eval(\n \"e = arctan2(sin(a), b)\", engine=\"python\", parser=\"pandas\", inplace=True\n )\n # TODO: Use a series equality validator.\n df_equals(modin_df, df)\n\n def test_eval_df_arithmetic_subexpression(self):\n frame_data = {\"a\": random_state.randn(10), \"b\": random_state.randn(10)}\n df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data)\n df.eval(\"not_e = sin(a + b)\", engine=\"python\", parser=\"pandas\", inplace=True)\n modin_df.eval(\n \"not_e = sin(a + b)\", engine=\"python\", parser=\"pandas\", inplace=True\n )\n # TODO: Use a series equality validator.\n df_equals(modin_df, df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_filter(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n by = {\"items\": [\"col1\", \"col5\"], \"regex\": \"4$|3$\", \"like\": \"col\"}\n df_equals(\n modin_df.filter(items=by[\"items\"]), pandas_df.filter(items=by[\"items\"])\n )\n\n df_equals(\n modin_df.filter(regex=by[\"regex\"], axis=0),\n pandas_df.filter(regex=by[\"regex\"], axis=0),\n )\n df_equals(\n modin_df.filter(regex=by[\"regex\"], axis=1),\n pandas_df.filter(regex=by[\"regex\"], axis=1),\n )\n\n df_equals(modin_df.filter(like=by[\"like\"]), pandas_df.filter(like=by[\"like\"]))\n\n with pytest.raises(TypeError):\n modin_df.filter(items=by[\"items\"], regex=by[\"regex\"])\n\n with pytest.raises(TypeError):\n modin_df.filter()\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_pipe(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n n = len(modin_df.index)\n a, b, c = 2 % n, 0, 3 % n\n col = modin_df.columns[3 % len(modin_df.columns)]\n\n def h(x):\n return x.drop(columns=[col])\n\n def g(x, arg1=0):\n for _ in range(arg1):\n x = x.append(x)\n return x\n\n def f(x, arg2=0, arg3=0):\n return x.drop([arg2, arg3])\n\n df_equals(\n f(g(h(modin_df), arg1=a), arg2=b, arg3=c),\n (modin_df.pipe(h).pipe(g, arg1=a).pipe(f, arg2=b, arg3=c)),\n )\n df_equals(\n (modin_df.pipe(h).pipe(g, arg1=a).pipe(f, arg2=b, arg3=c)),\n (pandas_df.pipe(h).pipe(g, arg1=a).pipe(f, arg2=b, arg3=c)),\n )\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"funcs\", query_func_values, ids=query_func_keys)\n def test_query(self, data, funcs):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n with pytest.raises(ValueError):\n modin_df.query(\"\")\n with pytest.raises(NotImplementedError):\n x = 2 # noqa F841\n modin_df.query(\"col1 < @x\")\n\n try:\n pandas_result = pandas_df.query(funcs)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.query(funcs)\n else:\n modin_result = modin_df.query(funcs)\n df_equals(modin_result, pandas_result)\n\n def test_query_after_insert(self):\n modin_df = pd.DataFrame({\"x\": [-1, 0, 1, None], \"y\": [1, 2, None, 3]})\n modin_df[\"z\"] = modin_df.eval(\"x / y\")\n modin_df = modin_df.query(\"z >= 0\")\n modin_result = modin_df.reset_index(drop=True)\n modin_result.columns = [\"a\", \"b\", \"c\"]\n\n pandas_df = pd.DataFrame({\"x\": [-1, 0, 1, None], \"y\": [1, 2, None, 3]})\n pandas_df[\"z\"] = pandas_df.eval(\"x / y\")\n pandas_df = pandas_df.query(\"z >= 0\")\n pandas_result = pandas_df.reset_index(drop=True)\n pandas_result.columns = [\"a\", \"b\", \"c\"]\n\n df_equals(modin_result, pandas_result)\n df_equals(modin_df, pandas_df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"func\", agg_func_values, ids=agg_func_keys)\n def test_transform(self, request, data, func):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.transform(func)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.transform(func)\n else:\n modin_result = modin_df.transform(func)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"func\", agg_func_values, ids=agg_func_keys)\n def test_transform_numeric(self, request, data, func):\n if name_contains(request.node.name, numeric_agg_funcs) and name_contains(\n request.node.name, numeric_dfs\n ):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.transform(func)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.transform(func)\n else:\n modin_result = modin_df.transform(func)\n df_equals(modin_result, pandas_result)\n\n\nclass TestDataFrameDefault:\n def test_align(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).align(pd.DataFrame(data))\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_to_numpy(self, data):\n modin_frame = pd.DataFrame(data)\n pandas_frame = pandas.DataFrame(data)\n assert_array_equal(modin_frame.values, pandas_frame.values)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_partition_to_numpy(self, data):\n frame = pd.DataFrame(data)\n for (\n partition\n ) in frame._query_compiler._modin_frame._partitions.flatten().tolist():\n assert_array_equal(partition.to_pandas().values, partition.to_numpy())\n\n def test_asfreq(self):\n index = pd.date_range(\"1/1/2000\", periods=4, freq=\"T\")\n series = pd.Series([0.0, None, 2.0, 3.0], index=index)\n df = pd.DataFrame({\"s\": series})\n with pytest.warns(UserWarning):\n # We are only testing that this defaults to pandas, so we will just check for\n # the warning\n df.asfreq(freq=\"30S\")\n\n def test_asof(self):\n df = pd.DataFrame(\n {\"a\": [10, 20, 30, 40, 50], \"b\": [None, None, None, None, 500]},\n index=pd.DatetimeIndex(\n [\n \"2018-02-27 09:01:00\",\n \"2018-02-27 09:02:00\",\n \"2018-02-27 09:03:00\",\n \"2018-02-27 09:04:00\",\n \"2018-02-27 09:05:00\",\n ]\n ),\n )\n with pytest.warns(UserWarning):\n df.asof(pd.DatetimeIndex([\"2018-02-27 09:03:30\", \"2018-02-27 09:04:30\"]))\n\n def test_assign(self):\n data = test_data_values[0]\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n modin_result = modin_df.assign(new_column=pd.Series(modin_df.iloc[:, 0]))\n pandas_result = pandas_df.assign(new_column=pandas.Series(pandas_df.iloc[:, 0]))\n df_equals(modin_result, pandas_result)\n modin_result = modin_df.assign(\n new_column=pd.Series(modin_df.iloc[:, 0]),\n new_column2=pd.Series(modin_df.iloc[:, 1]),\n )\n pandas_result = pandas_df.assign(\n new_column=pandas.Series(pandas_df.iloc[:, 0]),\n new_column2=pandas.Series(pandas_df.iloc[:, 1]),\n )\n df_equals(modin_result, pandas_result)\n\n def test_at_time(self):\n i = pd.date_range(\"2008-01-01\", periods=1000, freq=\"12H\")\n modin_df = pd.DataFrame(\n {\"A\": list(range(1000)), \"B\": list(range(1000))}, index=i\n )\n pandas_df = pandas.DataFrame(\n {\"A\": list(range(1000)), \"B\": list(range(1000))}, index=i\n )\n df_equals(modin_df.at_time(\"12:00\"), pandas_df.at_time(\"12:00\"))\n df_equals(modin_df.at_time(\"3:00\"), pandas_df.at_time(\"3:00\"))\n df_equals(\n modin_df.T.at_time(\"12:00\", axis=1), pandas_df.T.at_time(\"12:00\", axis=1)\n )\n\n def test_between_time(self):\n i = pd.date_range(\"2008-01-01\", periods=1000, freq=\"12H\")\n modin_df = pd.DataFrame(\n {\"A\": list(range(1000)), \"B\": list(range(1000))}, index=i\n )\n pandas_df = pandas.DataFrame(\n {\"A\": list(range(1000)), \"B\": list(range(1000))}, index=i\n )\n df_equals(\n modin_df.between_time(\"12:00\", \"17:00\"),\n pandas_df.between_time(\"12:00\", \"17:00\"),\n )\n df_equals(\n modin_df.between_time(\"3:00\", \"4:00\"),\n pandas_df.between_time(\"3:00\", \"4:00\"),\n )\n df_equals(\n modin_df.T.between_time(\"12:00\", \"17:00\", axis=1),\n pandas_df.T.between_time(\"12:00\", \"17:00\", axis=1),\n )\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_bfill(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n df_equals(modin_df.bfill(), pandas_df.bfill())\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_bool(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data) # noqa F841\n\n with pytest.raises(ValueError):\n modin_df.bool()\n modin_df.__bool__()\n\n single_bool_pandas_df = pandas.DataFrame([True])\n single_bool_modin_df = pd.DataFrame([True])\n\n assert single_bool_pandas_df.bool() == single_bool_modin_df.bool()\n\n with pytest.raises(ValueError):\n # __bool__ always raises this error for DataFrames\n single_bool_modin_df.__bool__()\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_boxplot(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data) # noqa F841\n\n assert modin_df.boxplot() == to_pandas(modin_df).boxplot()\n\n def test_combine_first(self):\n data1 = {\"A\": [None, 0], \"B\": [None, 4]}\n modin_df1 = pd.DataFrame(data1)\n pandas_df1 = pandas.DataFrame(data1)\n data2 = {\"A\": [1, 1], \"B\": [3, 3]}\n modin_df2 = pd.DataFrame(data2)\n pandas_df2 = pandas.DataFrame(data2)\n df_equals(\n modin_df1.combine_first(modin_df2), pandas_df1.combine_first(pandas_df2)\n )\n\n def test_corr(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).corr()\n\n def test_corrwith(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).corrwith(pd.DataFrame(data))\n\n def test_cov(self):\n data = test_data_values[0]\n modin_result = pd.DataFrame(data).cov()\n pandas_result = pandas.DataFrame(data).cov()\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_dot(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n col_len = len(modin_df.columns)\n\n # Test list input\n arr = np.arange(col_len)\n modin_result = modin_df.dot(arr)\n pandas_result = pandas_df.dot(arr)\n df_equals(modin_result, pandas_result)\n\n # Test bad dimensions\n with pytest.raises(ValueError):\n modin_result = modin_df.dot(np.arange(col_len + 10))\n\n # Test series input\n modin_series = pd.Series(np.arange(col_len), index=modin_df.columns)\n pandas_series = pandas.Series(np.arange(col_len), index=pandas_df.columns)\n modin_result = modin_df.dot(modin_series)\n pandas_result = pandas_df.dot(pandas_series)\n df_equals(modin_result, pandas_result)\n\n # Test dataframe input\n modin_result = modin_df.dot(modin_df.T)\n pandas_result = pandas_df.dot(pandas_df.T)\n df_equals(modin_result, pandas_result)\n\n # Test when input series index doesn't line up with columns\n with pytest.raises(ValueError):\n modin_result = modin_df.dot(pd.Series(np.arange(col_len)))\n\n # Test case when left dataframe has size (n x 1)\n # and right dataframe has size (1 x n)\n modin_df = pd.DataFrame(modin_series)\n pandas_df = pandas.DataFrame(pandas_series)\n modin_result = modin_df.dot(modin_df.T)\n pandas_result = pandas_df.dot(pandas_df.T)\n df_equals(modin_result, pandas_result)\n\n # Test case when left dataframe has size (1 x 1)\n # and right dataframe has size (1 x n)\n modin_result = pd.DataFrame([1]).dot(modin_df.T)\n pandas_result = pandas.DataFrame([1]).dot(pandas_df.T)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_matmul(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n col_len = len(modin_df.columns)\n\n # Test list input\n arr = np.arange(col_len)\n modin_result = modin_df @ arr\n pandas_result = pandas_df @ arr\n df_equals(modin_result, pandas_result)\n\n # Test bad dimensions\n with pytest.raises(ValueError):\n modin_result = modin_df @ np.arange(col_len + 10)\n\n # Test series input\n modin_series = pd.Series(np.arange(col_len), index=modin_df.columns)\n pandas_series = pandas.Series(np.arange(col_len), index=pandas_df.columns)\n modin_result = modin_df @ modin_series\n pandas_result = pandas_df @ pandas_series\n df_equals(modin_result, pandas_result)\n\n # Test dataframe input\n modin_result = modin_df @ modin_df.T\n pandas_result = pandas_df @ pandas_df.T\n df_equals(modin_result, pandas_result)\n\n # Test when input series index doesn't line up with columns\n with pytest.raises(ValueError):\n modin_result = modin_df @ pd.Series(np.arange(col_len))\n\n def test_ewm(self):\n df = pd.DataFrame({\"B\": [0, 1, 2, np.nan, 4]})\n with pytest.warns(UserWarning):\n df.ewm(com=0.5).mean()\n\n def test_expanding(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).expanding()\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_explode(self, data):\n modin_df = pd.DataFrame(data)\n with pytest.warns(UserWarning):\n modin_df.explode(modin_df.columns[0])\n\n def test_first(self):\n i = pd.date_range(\"2010-04-09\", periods=400, freq=\"2D\")\n modin_df = pd.DataFrame({\"A\": list(range(400)), \"B\": list(range(400))}, index=i)\n pandas_df = pandas.DataFrame(\n {\"A\": list(range(400)), \"B\": list(range(400))}, index=i\n )\n df_equals(modin_df.first(\"3D\"), pandas_df.first(\"3D\"))\n df_equals(modin_df.first(\"20D\"), pandas_df.first(\"20D\"))\n\n @pytest.mark.skip(reason=\"Defaulting to Pandas\")\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_from_dict(self, data):\n modin_df = pd.DataFrame(data) # noqa F841\n pandas_df = pandas.DataFrame(data) # noqa F841\n\n with pytest.raises(NotImplementedError):\n pd.DataFrame.from_dict(None)\n\n @pytest.mark.skip(reason=\"Defaulting to Pandas\")\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_from_items(self, data):\n modin_df = pd.DataFrame(data) # noqa F841\n pandas_df = pandas.DataFrame(data) # noqa F841\n\n with pytest.raises(NotImplementedError):\n pd.DataFrame.from_items(None)\n\n @pytest.mark.skip(reason=\"Defaulting to Pandas\")\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_from_records(self, data):\n modin_df = pd.DataFrame(data) # noqa F841\n pandas_df = pandas.DataFrame(data) # noqa F841\n\n with pytest.raises(NotImplementedError):\n pd.DataFrame.from_records(None)\n\n def test_hist(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).hist(None)\n\n def test_infer_objects(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).infer_objects()\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"verbose\", [None, True, False])\n @pytest.mark.parametrize(\"max_cols\", [None, 10, 99999999])\n @pytest.mark.parametrize(\"memory_usage\", [None, True, False, \"deep\"])\n @pytest.mark.parametrize(\"null_counts\", [None, True, False])\n def test_info(self, data, verbose, max_cols, memory_usage, null_counts):\n with io.StringIO() as first, io.StringIO() as second:\n eval_general(\n pd.DataFrame(data),\n pandas.DataFrame(data),\n operation=lambda df, **kwargs: df.info(**kwargs),\n verbose=verbose,\n max_cols=max_cols,\n memory_usage=memory_usage,\n null_counts=null_counts,\n buf=lambda df: second if isinstance(df, pandas.DataFrame) else first,\n )\n modin_info = first.getvalue().splitlines()\n pandas_info = second.getvalue().splitlines()\n\n assert modin_info[0] == str(pd.DataFrame)\n assert pandas_info[0] == str(pandas.DataFrame)\n assert modin_info[1:] == pandas_info[1:]\n\n def test_interpolate(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).interpolate()\n\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\"skipna\", bool_arg_values, ids=bool_arg_keys)\n @pytest.mark.parametrize(\"level\", [None, -1, 0, 1])\n @pytest.mark.parametrize(\"numeric_only\", bool_arg_values, ids=bool_arg_keys)\n def test_kurt_kurtosis(self, axis, skipna, level, numeric_only):\n func_kwargs = {\n \"axis\": axis,\n \"skipna\": skipna,\n \"level\": level,\n \"numeric_only\": numeric_only,\n }\n data = test_data_values[0]\n df_modin = pd.DataFrame(data)\n df_pandas = pandas.DataFrame(data)\n\n eval_general(\n df_modin, df_pandas, lambda df: df.kurtosis(**func_kwargs),\n )\n\n if level is not None:\n cols_number = len(data.keys())\n arrays = [\n np.random.choice([\"bar\", \"baz\", \"foo\", \"qux\"], cols_number),\n np.random.choice([\"one\", \"two\"], cols_number),\n ]\n index = pd.MultiIndex.from_tuples(\n list(zip(*arrays)), names=[\"first\", \"second\"]\n )\n df_modin.columns = index\n df_pandas.columns = index\n eval_general(\n df_modin, df_pandas, lambda df: df.kurtosis(**func_kwargs),\n )\n\n def test_last(self):\n modin_index = pd.date_range(\"2010-04-09\", periods=400, freq=\"2D\")\n pandas_index = pandas.date_range(\"2010-04-09\", periods=400, freq=\"2D\")\n modin_df = pd.DataFrame(\n {\"A\": list(range(400)), \"B\": list(range(400))}, index=modin_index\n )\n pandas_df = pandas.DataFrame(\n {\"A\": list(range(400)), \"B\": list(range(400))}, index=pandas_index\n )\n df_equals(modin_df.last(\"3D\"), pandas_df.last(\"3D\"))\n df_equals(modin_df.last(\"20D\"), pandas_df.last(\"20D\"))\n\n def test_lookup(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).lookup([0, 1], [\"col1\", \"col2\"])\n\n @pytest.mark.parametrize(\"data\", test_data_values)\n @pytest.mark.parametrize(\"axis\", [None, 0, 1])\n @pytest.mark.parametrize(\"skipna\", [None, True, False])\n @pytest.mark.parametrize(\"level\", [0, -1, None])\n def test_mad(self, level, data, axis, skipna):\n modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)\n df_equals(\n modin_df.mad(axis=axis, skipna=skipna, level=level),\n pandas_df.mad(axis=axis, skipna=skipna, level=level),\n )\n\n def test_mask(self):\n df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=[\"A\", \"B\"])\n m = df % 3 == 0\n with pytest.warns(UserWarning):\n try:\n df.mask(~m, -df)\n except ValueError:\n pass\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\n \"id_vars\", [lambda df: df.columns[0], lambda df: df.columns[:4], None]\n )\n @pytest.mark.parametrize(\n \"value_vars\", [lambda df: df.columns[-1], lambda df: df.columns[-4:], None]\n )\n def test_melt(self, data, id_vars, value_vars):\n eval_general(\n *create_test_dfs(data),\n lambda df, *args, **kwargs: df.melt(*args, **kwargs)\n .sort_values([\"variable\", \"value\"])\n .reset_index(drop=True),\n id_vars=id_vars,\n value_vars=value_vars,\n )\n\n def test_pct_change(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).pct_change()\n\n def test_pivot(self):\n df = pd.DataFrame(\n {\n \"foo\": [\"one\", \"one\", \"one\", \"two\", \"two\", \"two\"],\n \"bar\": [\"A\", \"B\", \"C\", \"A\", \"B\", \"C\"],\n \"baz\": [1, 2, 3, 4, 5, 6],\n \"zoo\": [\"x\", \"y\", \"z\", \"q\", \"w\", \"t\"],\n }\n )\n with pytest.warns(UserWarning):\n df.pivot(index=\"foo\", columns=\"bar\", values=\"baz\")\n\n def test_pivot_table(self):\n df = pd.DataFrame(\n {\n \"A\": [\"foo\", \"foo\", \"foo\", \"foo\", \"foo\", \"bar\", \"bar\", \"bar\", \"bar\"],\n \"B\": [\"one\", \"one\", \"one\", \"two\", \"two\", \"one\", \"one\", \"two\", \"two\"],\n \"C\": [\n \"small\",\n \"large\",\n \"large\",\n \"small\",\n \"small\",\n \"large\",\n \"small\",\n \"small\",\n \"large\",\n ],\n \"D\": [1, 2, 2, 3, 3, 4, 5, 6, 7],\n \"E\": [2, 4, 5, 5, 6, 6, 8, 9, 9],\n }\n )\n with pytest.warns(UserWarning):\n df.pivot_table(values=\"D\", index=[\"A\", \"B\"], columns=[\"C\"], aggfunc=np.sum)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_plot(self, request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if name_contains(request.node.name, numeric_dfs):\n # We have to test this way because equality in plots means same object.\n zipped_plot_lines = zip(modin_df.plot().lines, pandas_df.plot().lines)\n for left, right in zipped_plot_lines:\n if isinstance(left.get_xdata(), np.ma.core.MaskedArray) and isinstance(\n right.get_xdata(), np.ma.core.MaskedArray\n ):\n assert all((left.get_xdata() == right.get_xdata()).data)\n else:\n assert np.array_equal(left.get_xdata(), right.get_xdata())\n if isinstance(left.get_ydata(), np.ma.core.MaskedArray) and isinstance(\n right.get_ydata(), np.ma.core.MaskedArray\n ):\n assert all((left.get_ydata() == right.get_ydata()).data)\n else:\n assert np.array_equal(left.get_xdata(), right.get_xdata())\n\n def test_replace(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).replace()\n\n @pytest.mark.parametrize(\"rule\", [\"5T\", pandas.offsets.Hour()])\n @pytest.mark.parametrize(\"axis\", [0, \"columns\"])\n @pytest.mark.parametrize(\"closed\", [\"left\", \"right\"])\n @pytest.mark.parametrize(\"label\", [\"right\", \"left\"])\n @pytest.mark.parametrize(\"on\", [None, \"DateColumn\"])\n @pytest.mark.parametrize(\"level\", [None, 1])\n def test_resample(self, rule, axis, closed, label, on, level):\n freq = \"H\"\n base = 2\n index = pandas.date_range(\"31/12/2000\", periods=12, freq=freq)\n data = {\"A\": range(12), \"B\": range(12)}\n\n pandas_df = pandas.DataFrame(data, index=index)\n modin_df = pd.DataFrame(data, index=index)\n\n if on is not None and axis == 0:\n pandas_df[on] = pandas.date_range(\"22/06/1941\", periods=12, freq=\"T\")\n modin_df[on] = pandas.date_range(\"22/06/1941\", periods=12, freq=\"T\")\n else:\n on = None\n\n if axis == \"columns\":\n pandas_df = pandas_df.T\n modin_df = modin_df.T\n\n if level is not None and axis == 0 and on is None:\n index = pandas.MultiIndex.from_product(\n [[\"a\", \"b\", \"c\"], pandas.date_range(\"31/12/2000\", periods=4, freq=freq)]\n )\n pandas_df.index = index\n modin_df.index = index\n else:\n level = None\n\n pandas_resampler = pandas_df.resample(\n rule, axis=axis, closed=closed, label=label, base=base, on=on, level=level\n )\n modin_resampler = modin_df.resample(\n rule, axis=axis, closed=closed, label=label, base=base, on=on, level=level\n )\n\n df_equals(modin_resampler.count(), pandas_resampler.count())\n df_equals(modin_resampler.var(0), pandas_resampler.var(0))\n df_equals(modin_resampler.sum(), pandas_resampler.sum())\n df_equals(modin_resampler.std(), pandas_resampler.std())\n df_equals(modin_resampler.sem(), pandas_resampler.sem())\n df_equals(modin_resampler.size(), pandas_resampler.size())\n df_equals(modin_resampler.prod(), pandas_resampler.prod())\n if on is None:\n df_equals(modin_resampler.ohlc(), pandas_resampler.ohlc())\n df_equals(modin_resampler.min(), pandas_resampler.min())\n df_equals(modin_resampler.median(), pandas_resampler.median())\n df_equals(modin_resampler.mean(), pandas_resampler.mean())\n df_equals(modin_resampler.max(), pandas_resampler.max())\n df_equals(modin_resampler.last(), pandas_resampler.last())\n df_equals(modin_resampler.first(), pandas_resampler.first())\n df_equals(modin_resampler.nunique(), pandas_resampler.nunique())\n df_equals(\n modin_resampler.pipe(lambda x: x.max() - x.min()),\n pandas_resampler.pipe(lambda x: x.max() - x.min()),\n )\n df_equals(\n modin_resampler.transform(lambda x: (x - x.mean()) / x.std()),\n pandas_resampler.transform(lambda x: (x - x.mean()) / x.std()),\n )\n df_equals(\n pandas_resampler.aggregate(\"max\"), modin_resampler.aggregate(\"max\"),\n )\n df_equals(\n modin_resampler.apply(\"sum\"), pandas_resampler.apply(\"sum\"),\n )\n df_equals(\n modin_resampler.get_group(name=list(modin_resampler.groups)[0]),\n pandas_resampler.get_group(name=list(pandas_resampler.groups)[0]),\n )\n assert pandas_resampler.indices == modin_resampler.indices\n assert pandas_resampler.groups == modin_resampler.groups\n df_equals(modin_resampler.quantile(), pandas_resampler.quantile())\n if axis == 0:\n # Upsampling from level= or on= selection is not supported\n if on is None and level is None:\n df_equals(\n modin_resampler.interpolate(), pandas_resampler.interpolate(),\n )\n df_equals(modin_resampler.asfreq(), pandas_resampler.asfreq())\n df_equals(\n modin_resampler.fillna(method=\"nearest\"),\n pandas_resampler.fillna(method=\"nearest\"),\n )\n df_equals(modin_resampler.pad(), pandas_resampler.pad())\n df_equals(modin_resampler.nearest(), pandas_resampler.nearest())\n df_equals(modin_resampler.bfill(), pandas_resampler.bfill())\n df_equals(modin_resampler.backfill(), pandas_resampler.backfill())\n df_equals(modin_resampler.ffill(), pandas_resampler.ffill())\n df_equals(\n pandas_resampler.apply([\"sum\", \"mean\", \"max\"]),\n modin_resampler.apply([\"sum\", \"mean\", \"max\"]),\n )\n df_equals(\n modin_resampler.aggregate([\"sum\", \"mean\", \"max\"]),\n pandas_resampler.aggregate([\"sum\", \"mean\", \"max\"]),\n )\n\n def test_sem(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).sem()\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"index\", [\"default\", \"ndarray\"])\n @pytest.mark.parametrize(\"axis\", [0, 1])\n @pytest.mark.parametrize(\"periods\", [0, 1, -1, 10, -10, 1000000000, -1000000000])\n def test_shift(self, data, index, axis, periods):\n if index == \"default\":\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n elif index == \"ndarray\":\n data_column_length = len(data[next(iter(data))])\n index_data = np.arange(2, data_column_length + 2)\n modin_df = pd.DataFrame(data, index=index_data)\n pandas_df = pandas.DataFrame(data, index=index_data)\n\n df_equals(\n modin_df.shift(periods=periods, axis=axis),\n pandas_df.shift(periods=periods, axis=axis),\n )\n df_equals(\n modin_df.shift(periods=periods, axis=axis, fill_value=777),\n pandas_df.shift(periods=periods, axis=axis, fill_value=777),\n )\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"index\", [\"default\", \"ndarray\"])\n @pytest.mark.parametrize(\"axis\", [0, 1])\n @pytest.mark.parametrize(\"periods\", [0, 1, -1, 10, -10, 1000000000, -1000000000])\n def test_slice_shift(self, data, index, axis, periods):\n if index == \"default\":\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n elif index == \"ndarray\":\n data_column_length = len(data[next(iter(data))])\n index_data = np.arange(2, data_column_length + 2)\n modin_df = pd.DataFrame(data, index=index_data)\n pandas_df = pandas.DataFrame(data, index=index_data)\n\n df_equals(\n modin_df.slice_shift(periods=periods, axis=axis),\n pandas_df.slice_shift(periods=periods, axis=axis),\n )\n\n def test_stack(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).stack()\n\n def test_style(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).style\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis1\", [0, 1, \"columns\", \"index\"])\n @pytest.mark.parametrize(\"axis2\", [0, 1, \"columns\", \"index\"])\n def test_swapaxes(self, data, axis1, axis2):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n try:\n pandas_result = pandas_df.swapaxes(axis1, axis2)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.swapaxes(axis1, axis2)\n else:\n modin_result = modin_df.swapaxes(axis1, axis2)\n df_equals(modin_result, pandas_result)\n\n def test_swaplevel(self):\n data = np.random.randint(1, 100, 12)\n modin_df = pd.DataFrame(\n data,\n index=pd.MultiIndex.from_tuples(\n [\n (num, letter, color)\n for num in range(1, 3)\n for letter in [\"a\", \"b\", \"c\"]\n for color in [\"Red\", \"Green\"]\n ],\n names=[\"Number\", \"Letter\", \"Color\"],\n ),\n )\n pandas_df = pandas.DataFrame(\n data,\n index=pandas.MultiIndex.from_tuples(\n [\n (num, letter, color)\n for num in range(1, 3)\n for letter in [\"a\", \"b\", \"c\"]\n for color in [\"Red\", \"Green\"]\n ],\n names=[\"Number\", \"Letter\", \"Color\"],\n ),\n )\n df_equals(\n modin_df.swaplevel(\"Number\", \"Color\"),\n pandas_df.swaplevel(\"Number\", \"Color\"),\n )\n df_equals(modin_df.swaplevel(), pandas_df.swaplevel())\n df_equals(modin_df.swaplevel(0, 1), pandas_df.swaplevel(0, 1))\n\n def test_take(self):\n modin_df = pd.DataFrame(\n [\n (\"falcon\", \"bird\", 389.0),\n (\"parrot\", \"bird\", 24.0),\n (\"lion\", \"mammal\", 80.5),\n (\"monkey\", \"mammal\", np.nan),\n ],\n columns=[\"name\", \"class\", \"max_speed\"],\n index=[0, 2, 3, 1],\n )\n pandas_df = pandas.DataFrame(\n [\n (\"falcon\", \"bird\", 389.0),\n (\"parrot\", \"bird\", 24.0),\n (\"lion\", \"mammal\", 80.5),\n (\"monkey\", \"mammal\", np.nan),\n ],\n columns=[\"name\", \"class\", \"max_speed\"],\n index=[0, 2, 3, 1],\n )\n df_equals(modin_df.take([0, 3]), pandas_df.take([0, 3]))\n df_equals(modin_df.take([2], axis=1), pandas_df.take([2], axis=1))\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_to_records(self, request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n # Skips nan because only difference is nan instead of NaN\n if not name_contains(request.node.name, [\"nan\"]):\n try:\n pandas_result = pandas_df.to_records()\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.to_records()\n else:\n modin_result = modin_df.to_records()\n assert np.array_equal(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_to_string(self, request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data) # noqa F841\n\n # Skips nan because only difference is nan instead of NaN\n if not name_contains(request.node.name, [\"nan\"]):\n assert modin_df.to_string() == to_pandas(modin_df).to_string()\n\n def test_to_timestamp(self):\n idx = pd.date_range(\"1/1/2012\", periods=5, freq=\"M\")\n df = pd.DataFrame(np.random.randint(0, 100, size=(len(idx), 4)), index=idx)\n\n with pytest.warns(UserWarning):\n df.to_period().to_timestamp()\n\n def test_to_xarray(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).to_xarray()\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_truncate(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n before = 1\n after = len(modin_df - 3)\n df_equals(modin_df.truncate(before, after), pandas_df.truncate(before, after))\n\n before = 1\n after = 3\n df_equals(modin_df.truncate(before, after), pandas_df.truncate(before, after))\n\n before = modin_df.columns[1]\n after = modin_df.columns[-3]\n try:\n pandas_result = pandas_df.truncate(before, after, axis=1)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.truncate(before, after, axis=1)\n else:\n modin_result = modin_df.truncate(before, after, axis=1)\n df_equals(modin_result, pandas_result)\n\n before = modin_df.columns[1]\n after = modin_df.columns[3]\n try:\n pandas_result = pandas_df.truncate(before, after, axis=1)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.truncate(before, after, axis=1)\n else:\n modin_result = modin_df.truncate(before, after, axis=1)\n df_equals(modin_result, pandas_result)\n\n before = None\n after = None\n df_equals(modin_df.truncate(before, after), pandas_df.truncate(before, after))\n try:\n pandas_result = pandas_df.truncate(before, after, axis=1)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.truncate(before, after, axis=1)\n else:\n modin_result = modin_df.truncate(before, after, axis=1)\n df_equals(modin_result, pandas_result)\n\n def test_tshift(self):\n idx = pd.date_range(\"1/1/2012\", periods=5, freq=\"M\")\n data = np.random.randint(0, 100, size=(len(idx), 4))\n modin_df = pd.DataFrame(data, index=idx)\n pandas_df = pandas.DataFrame(data, index=idx)\n df_equals(modin_df.tshift(4), pandas_df.tshift(4))\n\n def test_tz_convert(self):\n modin_idx = pd.date_range(\n \"1/1/2012\", periods=500, freq=\"2D\", tz=\"America/Los_Angeles\"\n )\n pandas_idx = pandas.date_range(\n \"1/1/2012\", periods=500, freq=\"2D\", tz=\"America/Los_Angeles\"\n )\n data = np.random.randint(0, 100, size=(len(modin_idx), 4))\n modin_df = pd.DataFrame(data, index=modin_idx)\n pandas_df = pandas.DataFrame(data, index=pandas_idx)\n modin_result = modin_df.tz_convert(\"UTC\", axis=0)\n pandas_result = pandas_df.tz_convert(\"UTC\", axis=0)\n df_equals(modin_result, pandas_result)\n\n modin_multi = pd.MultiIndex.from_arrays([modin_idx, range(len(modin_idx))])\n pandas_multi = pandas.MultiIndex.from_arrays(\n [pandas_idx, range(len(modin_idx))]\n )\n modin_series = pd.DataFrame(data, index=modin_multi)\n pandas_series = pandas.DataFrame(data, index=pandas_multi)\n df_equals(\n modin_series.tz_convert(\"UTC\", axis=0, level=0),\n pandas_series.tz_convert(\"UTC\", axis=0, level=0),\n )\n\n def test_tz_localize(self):\n idx = pd.date_range(\"1/1/2012\", periods=400, freq=\"2D\")\n data = np.random.randint(0, 100, size=(len(idx), 4))\n modin_df = pd.DataFrame(data, index=idx)\n pandas_df = pandas.DataFrame(data, index=idx)\n df_equals(\n modin_df.tz_localize(\"UTC\", axis=0), pandas_df.tz_localize(\"UTC\", axis=0)\n )\n df_equals(\n modin_df.tz_localize(\"America/Los_Angeles\", axis=0),\n pandas_df.tz_localize(\"America/Los_Angeles\", axis=0),\n )\n\n def test_unstack(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).unstack()\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___array__(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n assert_array_equal(modin_df.__array__(), pandas_df.__array__())\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___bool__(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.__bool__()\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.__bool__()\n else:\n modin_result = modin_df.__bool__()\n df_equals(modin_result, pandas_result)\n\n def test___getstate__(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).__getstate__()\n\n def test___setstate__(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n try:\n pd.DataFrame(data).__setstate__(None)\n except TypeError:\n pass\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_hasattr_sparse(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n try:\n pandas_result = hasattr(pandas_df, \"sparse\")\n except Exception as e:\n with pytest.raises(type(e)):\n hasattr(modin_df, \"sparse\")\n else:\n modin_result = hasattr(modin_df, \"sparse\")\n assert modin_result == pandas_result\n\n\nclass TestDataFrameReduction_A:\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"bool_only\", bool_arg_values, ids=arg_keys(\"bool_only\", bool_arg_keys)\n )\n def test_all(self, data, axis, skipna, bool_only):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.all(axis=axis, skipna=skipna, bool_only=bool_only)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.all(axis=axis, skipna=skipna, bool_only=bool_only)\n else:\n modin_result = modin_df.all(axis=axis, skipna=skipna, bool_only=bool_only)\n df_equals(modin_result, pandas_result)\n\n # Test when axis is None. This will get repeated but easier than using list in parameterize decorator\n try:\n pandas_result = pandas_df.all(axis=None, skipna=skipna, bool_only=bool_only)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.all(axis=None, skipna=skipna, bool_only=bool_only)\n else:\n modin_result = modin_df.all(axis=None, skipna=skipna, bool_only=bool_only)\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.T.all(\n axis=axis, skipna=skipna, bool_only=bool_only\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.T.all(axis=axis, skipna=skipna, bool_only=bool_only)\n else:\n modin_result = modin_df.T.all(axis=axis, skipna=skipna, bool_only=bool_only)\n df_equals(modin_result, pandas_result)\n\n # Test when axis is None. This will get repeated but easier than using list in parameterize decorator\n try:\n pandas_result = pandas_df.T.all(\n axis=None, skipna=skipna, bool_only=bool_only\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.T.all(axis=None, skipna=skipna, bool_only=bool_only)\n else:\n modin_result = modin_df.T.all(axis=None, skipna=skipna, bool_only=bool_only)\n df_equals(modin_result, pandas_result)\n\n # test level\n modin_df_multi_level = modin_df.copy()\n pandas_df_multi_level = pandas_df.copy()\n axis = modin_df._get_axis_number(axis) if axis is not None else 0\n levels = 3\n axis_names_list = [[\"a\", \"b\", \"c\"], None]\n for axis_names in axis_names_list:\n if axis == 0:\n new_idx = pandas.MultiIndex.from_tuples(\n [(i // 4, i // 2, i) for i in range(len(modin_df.index))],\n names=axis_names,\n )\n modin_df_multi_level.index = new_idx\n pandas_df_multi_level.index = new_idx\n else:\n new_col = pandas.MultiIndex.from_tuples(\n [(i // 4, i // 2, i) for i in range(len(modin_df.columns))],\n names=axis_names,\n )\n modin_df_multi_level.columns = new_col\n pandas_df_multi_level.columns = new_col\n\n for level in list(range(levels)) + (axis_names if axis_names else []):\n try:\n pandas_multi_level_result = pandas_df_multi_level.all(\n axis=axis, bool_only=bool_only, level=level, skipna=skipna\n )\n\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df_multi_level.all(\n axis=axis, bool_only=bool_only, level=level, skipna=skipna\n )\n else:\n modin_multi_level_result = modin_df_multi_level.all(\n axis=axis, bool_only=bool_only, level=level, skipna=skipna\n )\n\n df_equals(modin_multi_level_result, pandas_multi_level_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"bool_only\", bool_arg_values, ids=arg_keys(\"bool_only\", bool_arg_keys)\n )\n def test_any(self, data, axis, skipna, bool_only):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.any(axis=axis, skipna=skipna, bool_only=bool_only)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.any(axis=axis, skipna=skipna, bool_only=bool_only)\n else:\n modin_result = modin_df.any(axis=axis, skipna=skipna, bool_only=bool_only)\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.any(axis=None, skipna=skipna, bool_only=bool_only)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.any(axis=None, skipna=skipna, bool_only=bool_only)\n else:\n modin_result = modin_df.any(axis=None, skipna=skipna, bool_only=bool_only)\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.T.any(\n axis=axis, skipna=skipna, bool_only=bool_only\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.T.any(axis=axis, skipna=skipna, bool_only=bool_only)\n else:\n modin_result = modin_df.T.any(axis=axis, skipna=skipna, bool_only=bool_only)\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.T.any(\n axis=None, skipna=skipna, bool_only=bool_only\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.T.any(axis=None, skipna=skipna, bool_only=bool_only)\n else:\n modin_result = modin_df.T.any(axis=None, skipna=skipna, bool_only=bool_only)\n df_equals(modin_result, pandas_result)\n\n # test level\n modin_df_multi_level = modin_df.copy()\n pandas_df_multi_level = pandas_df.copy()\n axis = modin_df._get_axis_number(axis) if axis is not None else 0\n levels = 3\n axis_names_list = [[\"a\", \"b\", \"c\"], None]\n for axis_names in axis_names_list:\n if axis == 0:\n new_idx = pandas.MultiIndex.from_tuples(\n [(i // 4, i // 2, i) for i in range(len(modin_df.index))],\n names=axis_names,\n )\n modin_df_multi_level.index = new_idx\n pandas_df_multi_level.index = new_idx\n else:\n new_col = pandas.MultiIndex.from_tuples(\n [(i // 4, i // 2, i) for i in range(len(modin_df.columns))],\n names=axis_names,\n )\n modin_df_multi_level.columns = new_col\n pandas_df_multi_level.columns = new_col\n\n for level in list(range(levels)) + (axis_names if axis_names else []):\n try:\n pandas_multi_level_result = pandas_df_multi_level.any(\n axis=axis, bool_only=bool_only, level=level, skipna=skipna\n )\n\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df_multi_level.any(\n axis=axis, bool_only=bool_only, level=level, skipna=skipna\n )\n else:\n modin_multi_level_result = modin_df_multi_level.any(\n axis=axis, bool_only=bool_only, level=level, skipna=skipna\n )\n\n df_equals(modin_multi_level_result, pandas_multi_level_result)\n\n\nclass TestDataFrameReduction_B:\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"numeric_only\", bool_arg_values, ids=arg_keys(\"numeric_only\", bool_arg_keys)\n )\n def test_count(self, request, data, axis, numeric_only):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n modin_result = modin_df.count(axis=axis, numeric_only=numeric_only)\n pandas_result = pandas_df.count(axis=axis, numeric_only=numeric_only)\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.T.count(axis=axis, numeric_only=numeric_only)\n pandas_result = pandas_df.T.count(axis=axis, numeric_only=numeric_only)\n df_equals(modin_result, pandas_result)\n\n # test level\n modin_df_multi_level = modin_df.copy()\n pandas_df_multi_level = pandas_df.copy()\n axis = modin_df._get_axis_number(axis) if axis is not None else 0\n levels = 3\n axis_names_list = [[\"a\", \"b\", \"c\"], None]\n for axis_names in axis_names_list:\n if axis == 0:\n new_idx = pandas.MultiIndex.from_tuples(\n [(i // 4, i // 2, i) for i in range(len(modin_df.index))],\n names=axis_names,\n )\n modin_df_multi_level.index = new_idx\n pandas_df_multi_level.index = new_idx\n try: # test error\n pandas_df_multi_level.count(\n axis=1, numeric_only=numeric_only, level=0\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df_multi_level.count(\n axis=1, numeric_only=numeric_only, level=0\n )\n else:\n new_col = pandas.MultiIndex.from_tuples(\n [(i // 4, i // 2, i) for i in range(len(modin_df.columns))],\n names=axis_names,\n )\n modin_df_multi_level.columns = new_col\n pandas_df_multi_level.columns = new_col\n try: # test error\n pandas_df_multi_level.count(\n axis=0, numeric_only=numeric_only, level=0\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df_multi_level.count(\n axis=0, numeric_only=numeric_only, level=0\n )\n\n for level in list(range(levels)) + (axis_names if axis_names else []):\n modin_multi_level_result = modin_df_multi_level.count(\n axis=axis, numeric_only=numeric_only, level=level\n )\n pandas_multi_level_result = pandas_df_multi_level.count(\n axis=axis, numeric_only=numeric_only, level=level\n )\n df_equals(modin_multi_level_result, pandas_multi_level_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_describe(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.describe(), pandas_df.describe())\n percentiles = [0.10, 0.11, 0.44, 0.78, 0.99]\n df_equals(\n modin_df.describe(percentiles=percentiles),\n pandas_df.describe(percentiles=percentiles),\n )\n\n try:\n pandas_result = pandas_df.describe(exclude=[np.float64])\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.describe(exclude=[np.float64])\n else:\n modin_result = modin_df.describe(exclude=[np.float64])\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.describe(exclude=np.float64)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.describe(exclude=np.float64)\n else:\n modin_result = modin_df.describe(exclude=np.float64)\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.describe(\n include=[np.timedelta64, np.datetime64, np.object, np.bool]\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.describe(\n include=[np.timedelta64, np.datetime64, np.object, np.bool]\n )\n else:\n modin_result = modin_df.describe(\n include=[np.timedelta64, np.datetime64, np.object, np.bool]\n )\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.describe(include=str(modin_df.dtypes.values[0]))\n pandas_result = pandas_df.describe(include=str(pandas_df.dtypes.values[0]))\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.describe(include=[np.number])\n pandas_result = pandas_df.describe(include=[np.number])\n df_equals(modin_result, pandas_result)\n\n df_equals(modin_df.describe(include=\"all\"), pandas_df.describe(include=\"all\"))\n\n modin_df = pd.DataFrame(data).applymap(str)\n pandas_df = pandas.DataFrame(data).applymap(str)\n\n try:\n df_equals(modin_df.describe(), pandas_df.describe())\n except AssertionError:\n # We have to do this because we choose the highest count slightly differently\n # than pandas. Because there is no true guarantee which one will be first,\n # If they don't match, make sure that the `freq` is the same at least.\n df_equals(\n modin_df.describe().loc[[\"count\", \"unique\", \"freq\"]],\n pandas_df.describe().loc[[\"count\", \"unique\", \"freq\"]],\n )\n\n def test_describe_dtypes(self):\n modin_df = pd.DataFrame(\n {\n \"col1\": list(\"abc\"),\n \"col2\": list(\"abc\"),\n \"col3\": list(\"abc\"),\n \"col4\": [1, 2, 3],\n }\n )\n pandas_df = pandas.DataFrame(\n {\n \"col1\": list(\"abc\"),\n \"col2\": list(\"abc\"),\n \"col3\": list(\"abc\"),\n \"col4\": [1, 2, 3],\n }\n )\n\n modin_result = modin_df.describe()\n pandas_result = pandas_df.describe()\n\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n def test_idxmax(self, data, axis, skipna):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n pandas_result = pandas_df.idxmax(axis=axis, skipna=skipna)\n modin_result = modin_df.idxmax(axis=axis, skipna=skipna)\n df_equals(modin_result, pandas_result)\n\n pandas_result = pandas_df.T.idxmax(axis=axis, skipna=skipna)\n modin_result = modin_df.T.idxmax(axis=axis, skipna=skipna)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n def test_idxmin(self, data, axis, skipna):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n modin_result = modin_df.idxmin(axis=axis, skipna=skipna)\n pandas_result = pandas_df.idxmin(axis=axis, skipna=skipna)\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.T.idxmin(axis=axis, skipna=skipna)\n pandas_result = pandas_df.T.idxmin(axis=axis, skipna=skipna)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_last_valid_index(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n assert modin_df.last_valid_index() == (pandas_df.last_valid_index())\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"numeric_only\", bool_arg_values, ids=arg_keys(\"numeric_only\", bool_arg_keys)\n )\n def test_max(self, request, data, axis, skipna, numeric_only):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.max(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n except Exception:\n with pytest.raises(TypeError):\n modin_df.max(axis=axis, skipna=skipna, numeric_only=numeric_only)\n else:\n modin_result = modin_df.max(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.T.max(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n except Exception:\n with pytest.raises(TypeError):\n modin_df.T.max(axis=axis, skipna=skipna, numeric_only=numeric_only)\n else:\n modin_result = modin_df.T.max(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"numeric_only\", bool_arg_values, ids=arg_keys(\"numeric_only\", bool_arg_keys)\n )\n def test_mean(self, request, data, axis, skipna, numeric_only):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.mean(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.mean(axis=axis, skipna=skipna, numeric_only=numeric_only)\n else:\n modin_result = modin_df.mean(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.T.mean(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.T.mean(axis=axis, skipna=skipna, numeric_only=numeric_only)\n else:\n modin_result = modin_df.T.mean(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\n \"index\", bool_arg_values, ids=arg_keys(\"index\", bool_arg_keys)\n )\n def test_memory_usage(self, data, index):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data) # noqa F841\n\n modin_result = modin_df.memory_usage(index=index)\n pandas_result = pandas_df.memory_usage(index=index)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"numeric_only\", bool_arg_values, ids=arg_keys(\"numeric_only\", bool_arg_keys)\n )\n def test_min(self, data, axis, skipna, numeric_only):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.min(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n except Exception:\n with pytest.raises(TypeError):\n modin_df.min(axis=axis, skipna=skipna, numeric_only=numeric_only)\n else:\n modin_result = modin_df.min(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.T.min(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n except Exception:\n with pytest.raises(TypeError):\n modin_df.T.min(axis=axis, skipna=skipna, numeric_only=numeric_only)\n else:\n modin_result = modin_df.T.min(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"numeric_only\", bool_arg_values, ids=arg_keys(\"numeric_only\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"min_count\", int_arg_values, ids=arg_keys(\"min_count\", int_arg_keys)\n )\n def test_prod(self, request, data, axis, skipna, numeric_only, min_count):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.prod(\n axis=axis, skipna=skipna, numeric_only=numeric_only, min_count=min_count\n )\n except Exception:\n with pytest.raises(TypeError):\n modin_df.prod(\n axis=axis,\n skipna=skipna,\n numeric_only=numeric_only,\n min_count=min_count,\n )\n else:\n modin_result = modin_df.prod(\n axis=axis, skipna=skipna, numeric_only=numeric_only, min_count=min_count\n )\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.T.prod(\n axis=axis, skipna=skipna, numeric_only=numeric_only, min_count=min_count\n )\n except Exception:\n with pytest.raises(TypeError):\n modin_df.T.prod(\n axis=axis,\n skipna=skipna,\n numeric_only=numeric_only,\n min_count=min_count,\n )\n else:\n modin_result = modin_df.T.prod(\n axis=axis, skipna=skipna, numeric_only=numeric_only, min_count=min_count\n )\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"numeric_only\", bool_arg_values, ids=arg_keys(\"numeric_only\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"min_count\", int_arg_values, ids=arg_keys(\"min_count\", int_arg_keys)\n )\n def test_product(self, request, data, axis, skipna, numeric_only, min_count):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.product(\n axis=axis, skipna=skipna, numeric_only=numeric_only, min_count=min_count\n )\n except Exception:\n with pytest.raises(TypeError):\n modin_df.product(\n axis=axis,\n skipna=skipna,\n numeric_only=numeric_only,\n min_count=min_count,\n )\n else:\n modin_result = modin_df.product(\n axis=axis, skipna=skipna, numeric_only=numeric_only, min_count=min_count\n )\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"numeric_only\", bool_arg_values, ids=arg_keys(\"numeric_only\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"min_count\", int_arg_values, ids=arg_keys(\"min_count\", int_arg_keys)\n )\n def test_sum(self, request, data, axis, skipna, numeric_only, min_count):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.sum(\n axis=axis, skipna=skipna, numeric_only=numeric_only, min_count=min_count\n )\n except Exception:\n with pytest.raises(TypeError):\n modin_df.sum(\n axis=axis,\n skipna=skipna,\n numeric_only=numeric_only,\n min_count=min_count,\n )\n else:\n modin_result = modin_df.sum(\n axis=axis, skipna=skipna, numeric_only=numeric_only, min_count=min_count\n )\n df_equals(modin_result, pandas_result)\n try:\n pandas_result = pandas_df.T.sum(\n axis=axis, skipna=skipna, numeric_only=numeric_only, min_count=min_count\n )\n except Exception:\n with pytest.raises(TypeError):\n modin_df.T.sum(\n axis=axis,\n skipna=skipna,\n numeric_only=numeric_only,\n min_count=min_count,\n )\n else:\n modin_result = modin_df.T.sum(\n axis=axis, skipna=skipna, numeric_only=numeric_only, min_count=min_count\n )\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_sum_single_column(self, data):\n modin_df = pd.DataFrame(data).iloc[:, [0]]\n pandas_df = pandas.DataFrame(data).iloc[:, [0]]\n df_equals(modin_df.sum(), pandas_df.sum())\n df_equals(modin_df.sum(axis=1), pandas_df.sum(axis=1))\n\n\nclass TestDataFrameWindow:\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n def test_cummax(self, request, data, axis, skipna):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.cummax(axis=axis, skipna=skipna)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.cummax(axis=axis, skipna=skipna)\n else:\n modin_result = modin_df.cummax(axis=axis, skipna=skipna)\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.T.cummax(axis=axis, skipna=skipna)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.T.cummax(axis=axis, skipna=skipna)\n else:\n modin_result = modin_df.T.cummax(axis=axis, skipna=skipna)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n def test_cummax_int_and_float(self, axis):\n data = {\"col1\": list(range(1000)), \"col2\": [i * 0.1 for i in range(1000)]}\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n df_equals(modin_df.cummax(axis=axis), pandas_df.cummax(axis=axis))\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n def test_cummin(self, request, data, axis, skipna):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.cummin(axis=axis, skipna=skipna)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.cummin(axis=axis, skipna=skipna)\n else:\n modin_result = modin_df.cummin(axis=axis, skipna=skipna)\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.T.cummin(axis=axis, skipna=skipna)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.T.cummin(axis=axis, skipna=skipna)\n else:\n modin_result = modin_df.T.cummin(axis=axis, skipna=skipna)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n def test_cummin_int_and_float(self, axis):\n data = {\"col1\": list(range(1000)), \"col2\": [i * 0.1 for i in range(1000)]}\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n df_equals(modin_df.cummin(axis=axis), pandas_df.cummin(axis=axis))\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n def test_cumprod(self, request, data, axis, skipna):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.cumprod(axis=axis, skipna=skipna)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.cumprod(axis=axis, skipna=skipna)\n else:\n modin_result = modin_df.cumprod(axis=axis, skipna=skipna)\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.T.cumprod(axis=axis, skipna=skipna)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.T.cumprod(axis=axis, skipna=skipna)\n else:\n modin_result = modin_df.T.cumprod(axis=axis, skipna=skipna)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n def test_cumsum(self, request, data, axis, skipna):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n # pandas exhibits weird behavior for this case\n # Remove this case when we can pull the error messages from backend\n if name_contains(request.node.name, [\"datetime_timedelta_data\"]) and (\n axis == 0 or axis == \"rows\"\n ):\n with pytest.raises(TypeError):\n modin_df.cumsum(axis=axis, skipna=skipna)\n else:\n try:\n pandas_result = pandas_df.cumsum(axis=axis, skipna=skipna)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.cumsum(axis=axis, skipna=skipna)\n else:\n modin_result = modin_df.cumsum(axis=axis, skipna=skipna)\n df_equals(modin_result, pandas_result)\n\n if name_contains(request.node.name, [\"datetime_timedelta_data\"]) and (\n axis == 0 or axis == \"rows\"\n ):\n with pytest.raises(TypeError):\n modin_df.T.cumsum(axis=axis, skipna=skipna)\n else:\n try:\n pandas_result = pandas_df.T.cumsum(axis=axis, skipna=skipna)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.T.cumsum(axis=axis, skipna=skipna)\n else:\n modin_result = modin_df.T.cumsum(axis=axis, skipna=skipna)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"periods\", int_arg_values, ids=arg_keys(\"periods\", int_arg_keys)\n )\n def test_diff(self, request, data, axis, periods):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.diff(axis=axis, periods=periods)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.diff(axis=axis, periods=periods)\n else:\n modin_result = modin_df.diff(axis=axis, periods=periods)\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.T.diff(axis=axis, periods=periods)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.T.diff(axis=axis, periods=periods)\n else:\n modin_result = modin_df.T.diff(axis=axis, periods=periods)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\n \"keep\", [\"last\", \"first\", False], ids=[\"last\", \"first\", \"False\"]\n )\n def test_duplicated(self, data, keep):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n pandas_result = pandas_df.duplicated(keep=keep)\n modin_result = modin_df.duplicated(keep=keep)\n df_equals(modin_result, pandas_result)\n\n import random\n\n subset = random.sample(\n list(pandas_df.columns), random.randint(1, len(pandas_df.columns))\n )\n pandas_result = pandas_df.duplicated(keep=keep, subset=subset)\n modin_result = modin_df.duplicated(keep=keep, subset=subset)\n\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_ffill(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n df_equals(modin_df.ffill(), pandas_df.ffill())\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\n \"method\",\n [\"backfill\", \"bfill\", \"pad\", \"ffill\", None],\n ids=[\"backfill\", \"bfill\", \"pad\", \"ffill\", \"None\"],\n )\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\"limit\", int_arg_values, ids=int_arg_keys)\n def test_fillna(self, data, method, axis, limit):\n # We are not testing when limit is not positive until pandas-27042 gets fixed.\n # We are not testing when axis is over rows until pandas-17399 gets fixed.\n if limit > 0 and axis != 1 and axis != \"columns\":\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.fillna(\n 0, method=method, axis=axis, limit=limit\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.fillna(0, method=method, axis=axis, limit=limit)\n else:\n modin_result = modin_df.fillna(0, method=method, axis=axis, limit=limit)\n df_equals(modin_result, pandas_result)\n\n def test_fillna_sanity(self):\n # with different dtype\n frame_data = [\n [\"a\", \"a\", np.nan, \"a\"],\n [\"b\", \"b\", np.nan, \"b\"],\n [\"c\", \"c\", np.nan, \"c\"],\n ]\n df = pandas.DataFrame(frame_data)\n\n result = df.fillna({2: \"foo\"})\n modin_df = pd.DataFrame(frame_data).fillna({2: \"foo\"})\n\n df_equals(modin_df, result)\n\n modin_df = pd.DataFrame(df)\n df.fillna({2: \"foo\"}, inplace=True)\n modin_df.fillna({2: \"foo\"}, inplace=True)\n df_equals(modin_df, result)\n\n frame_data = {\n \"Date\": [pandas.NaT, pandas.Timestamp(\"2014-1-1\")],\n \"Date2\": [pandas.Timestamp(\"2013-1-1\"), pandas.NaT],\n }\n df = pandas.DataFrame(frame_data)\n result = df.fillna(value={\"Date\": df[\"Date2\"]})\n modin_df = pd.DataFrame(frame_data).fillna(value={\"Date\": df[\"Date2\"]})\n df_equals(modin_df, result)\n\n frame_data = {\"A\": [pandas.Timestamp(\"2012-11-11 00:00:00+01:00\"), pandas.NaT]}\n df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data)\n df_equals(modin_df.fillna(method=\"pad\"), df.fillna(method=\"pad\"))\n\n frame_data = {\"A\": [pandas.NaT, pandas.Timestamp(\"2012-11-11 00:00:00+01:00\")]}\n df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data).fillna(method=\"bfill\")\n df_equals(modin_df, df.fillna(method=\"bfill\"))\n\n def test_fillna_downcast(self):\n # infer int64 from float64\n frame_data = {\"a\": [1.0, np.nan]}\n df = pandas.DataFrame(frame_data)\n result = df.fillna(0, downcast=\"infer\")\n modin_df = pd.DataFrame(frame_data).fillna(0, downcast=\"infer\")\n df_equals(modin_df, result)\n\n # infer int64 from float64 when fillna value is a dict\n df = pandas.DataFrame(frame_data)\n result = df.fillna({\"a\": 0}, downcast=\"infer\")\n modin_df = pd.DataFrame(frame_data).fillna({\"a\": 0}, downcast=\"infer\")\n df_equals(modin_df, result)\n\n def test_fillna_inplace(self):\n frame_data = random_state.randn(10, 4)\n df = pandas.DataFrame(frame_data)\n df[1][:4] = np.nan\n df[3][-4:] = np.nan\n\n modin_df = pd.DataFrame(df)\n df.fillna(value=0, inplace=True)\n try:\n df_equals(modin_df, df)\n except AssertionError:\n pass\n else:\n assert False\n\n modin_df.fillna(value=0, inplace=True)\n df_equals(modin_df, df)\n\n modin_df = pd.DataFrame(df).fillna(value={0: 0}, inplace=True)\n assert modin_df is None\n\n df[1][:4] = np.nan\n df[3][-4:] = np.nan\n modin_df = pd.DataFrame(df)\n df.fillna(method=\"ffill\", inplace=True)\n try:\n df_equals(modin_df, df)\n except AssertionError:\n pass\n else:\n assert False\n\n modin_df.fillna(method=\"ffill\", inplace=True)\n df_equals(modin_df, df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_frame_fillna_limit(self, data):\n pandas_df = pandas.DataFrame(data)\n\n index = pandas_df.index\n\n result = pandas_df[:2].reindex(index)\n modin_df = pd.DataFrame(result)\n df_equals(\n modin_df.fillna(method=\"pad\", limit=2), result.fillna(method=\"pad\", limit=2)\n )\n\n result = pandas_df[-2:].reindex(index)\n modin_df = pd.DataFrame(result)\n df_equals(\n modin_df.fillna(method=\"backfill\", limit=2),\n result.fillna(method=\"backfill\", limit=2),\n )\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_frame_pad_backfill_limit(self, data):\n pandas_df = pandas.DataFrame(data)\n\n index = pandas_df.index\n\n result = pandas_df[:2].reindex(index)\n modin_df = pd.DataFrame(result)\n df_equals(\n modin_df.fillna(method=\"pad\", limit=2), result.fillna(method=\"pad\", limit=2)\n )\n\n result = pandas_df[-2:].reindex(index)\n modin_df = pd.DataFrame(result)\n df_equals(\n modin_df.fillna(method=\"backfill\", limit=2),\n result.fillna(method=\"backfill\", limit=2),\n )\n\n def test_fillna_dtype_conversion(self):\n # make sure that fillna on an empty frame works\n df = pandas.DataFrame(index=range(3), columns=[\"A\", \"B\"], dtype=\"float64\")\n modin_df = pd.DataFrame(index=range(3), columns=[\"A\", \"B\"], dtype=\"float64\")\n df_equals(modin_df.fillna(\"nan\"), df.fillna(\"nan\"))\n\n frame_data = {\"A\": [1, np.nan], \"B\": [1.0, 2.0]}\n df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data)\n for v in [\"\", 1, np.nan, 1.0]:\n df_equals(modin_df.fillna(v), df.fillna(v))\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_fillna_skip_certain_blocks(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n # don't try to fill boolean, int blocks\n df_equals(modin_df.fillna(np.nan), pandas_df.fillna(np.nan))\n\n def test_fillna_dict_series(self):\n frame_data = {\n \"a\": [np.nan, 1, 2, np.nan, np.nan],\n \"b\": [1, 2, 3, np.nan, np.nan],\n \"c\": [np.nan, 1, 2, 3, 4],\n }\n df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data)\n\n df_equals(modin_df.fillna({\"a\": 0, \"b\": 5}), df.fillna({\"a\": 0, \"b\": 5}))\n\n df_equals(\n modin_df.fillna({\"a\": 0, \"b\": 5, \"d\": 7}),\n df.fillna({\"a\": 0, \"b\": 5, \"d\": 7}),\n )\n\n # Series treated same as dict\n df_equals(modin_df.fillna(modin_df.max()), df.fillna(df.max()))\n\n def test_fillna_dataframe(self):\n frame_data = {\n \"a\": [np.nan, 1, 2, np.nan, np.nan],\n \"b\": [1, 2, 3, np.nan, np.nan],\n \"c\": [np.nan, 1, 2, 3, 4],\n }\n df = pandas.DataFrame(frame_data, index=list(\"VWXYZ\"))\n modin_df = pd.DataFrame(frame_data, index=list(\"VWXYZ\"))\n\n # df2 may have different index and columns\n df2 = pandas.DataFrame(\n {\n \"a\": [np.nan, 10, 20, 30, 40],\n \"b\": [50, 60, 70, 80, 90],\n \"foo\": [\"bar\"] * 5,\n },\n index=list(\"VWXuZ\"),\n )\n modin_df2 = pd.DataFrame(df2)\n\n # only those columns and indices which are shared get filled\n df_equals(modin_df.fillna(modin_df2), df.fillna(df2))\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_fillna_columns(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(\n modin_df.fillna(method=\"ffill\", axis=1),\n pandas_df.fillna(method=\"ffill\", axis=1),\n )\n\n df_equals(\n modin_df.fillna(method=\"ffill\", axis=1),\n pandas_df.fillna(method=\"ffill\", axis=1),\n )\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_fillna_invalid_method(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data) # noqa F841\n\n with pytest.raises(ValueError):\n modin_df.fillna(method=\"ffil\")\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_fillna_invalid_value(self, data):\n modin_df = pd.DataFrame(data)\n # list\n pytest.raises(TypeError, modin_df.fillna, [1, 2])\n # tuple\n pytest.raises(TypeError, modin_df.fillna, (1, 2))\n # frame with series\n pytest.raises(TypeError, modin_df.iloc[:, 0].fillna, modin_df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_fillna_col_reordering(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.fillna(method=\"ffill\"), pandas_df.fillna(method=\"ffill\"))\n\n def test_fillna_datetime_columns(self):\n frame_data = {\n \"A\": [-1, -2, np.nan],\n \"B\": pd.date_range(\"20130101\", periods=3),\n \"C\": [\"foo\", \"bar\", None],\n \"D\": [\"foo2\", \"bar2\", None],\n }\n df = pandas.DataFrame(frame_data, index=pd.date_range(\"20130110\", periods=3))\n modin_df = pd.DataFrame(frame_data, index=pd.date_range(\"20130110\", periods=3))\n df_equals(modin_df.fillna(\"?\"), df.fillna(\"?\"))\n\n frame_data = {\n \"A\": [-1, -2, np.nan],\n \"B\": [\n pandas.Timestamp(\"2013-01-01\"),\n pandas.Timestamp(\"2013-01-02\"),\n pandas.NaT,\n ],\n \"C\": [\"foo\", \"bar\", None],\n \"D\": [\"foo2\", \"bar2\", None],\n }\n df = pandas.DataFrame(frame_data, index=pd.date_range(\"20130110\", periods=3))\n modin_df = pd.DataFrame(frame_data, index=pd.date_range(\"20130110\", periods=3))\n df_equals(modin_df.fillna(\"?\"), df.fillna(\"?\"))\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"numeric_only\", bool_arg_values, ids=arg_keys(\"numeric_only\", bool_arg_keys)\n )\n def test_median(self, request, data, axis, skipna, numeric_only):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.median(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n except Exception:\n with pytest.raises(TypeError):\n modin_df.median(axis=axis, skipna=skipna, numeric_only=numeric_only)\n else:\n modin_result = modin_df.median(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.T.median(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n except Exception:\n with pytest.raises(TypeError):\n modin_df.T.median(axis=axis, skipna=skipna, numeric_only=numeric_only)\n else:\n modin_result = modin_df.T.median(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"numeric_only\", bool_arg_values, ids=arg_keys(\"numeric_only\", bool_arg_keys)\n )\n def test_mode(self, request, data, axis, numeric_only):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.mode(axis=axis, numeric_only=numeric_only)\n except Exception:\n with pytest.raises(TypeError):\n modin_df.mode(axis=axis, numeric_only=numeric_only)\n else:\n modin_result = modin_df.mode(axis=axis, numeric_only=numeric_only)\n df_equals(modin_result, pandas_result)\n\n def test_nlargest(self):\n data = {\n \"population\": [\n 59000000,\n 65000000,\n 434000,\n 434000,\n 434000,\n 337000,\n 11300,\n 11300,\n 11300,\n ],\n \"GDP\": [1937894, 2583560, 12011, 4520, 12128, 17036, 182, 38, 311],\n \"alpha-2\": [\"IT\", \"FR\", \"MT\", \"MV\", \"BN\", \"IS\", \"NR\", \"TV\", \"AI\"],\n }\n index = [\n \"Italy\",\n \"France\",\n \"Malta\",\n \"Maldives\",\n \"Brunei\",\n \"Iceland\",\n \"Nauru\",\n \"Tuvalu\",\n \"Anguilla\",\n ]\n modin_df = pd.DataFrame(data=data, index=index)\n pandas_df = pandas.DataFrame(data=data, index=index)\n df_equals(\n modin_df.nlargest(3, \"population\"), pandas_df.nlargest(3, \"population\")\n )\n\n def test_nsmallest(self):\n data = {\n \"population\": [\n 59000000,\n 65000000,\n 434000,\n 434000,\n 434000,\n 337000,\n 11300,\n 11300,\n 11300,\n ],\n \"GDP\": [1937894, 2583560, 12011, 4520, 12128, 17036, 182, 38, 311],\n \"alpha-2\": [\"IT\", \"FR\", \"MT\", \"MV\", \"BN\", \"IS\", \"NR\", \"TV\", \"AI\"],\n }\n index = [\n \"Italy\",\n \"France\",\n \"Malta\",\n \"Maldives\",\n \"Brunei\",\n \"Iceland\",\n \"Nauru\",\n \"Tuvalu\",\n \"Anguilla\",\n ]\n modin_df = pd.DataFrame(data=data, index=index)\n pandas_df = pandas.DataFrame(data=data, index=index)\n df_equals(\n modin_df.nsmallest(n=3, columns=\"population\"),\n pandas_df.nsmallest(n=3, columns=\"population\"),\n )\n df_equals(\n modin_df.nsmallest(n=2, columns=[\"population\", \"GDP\"], keep=\"all\"),\n pandas_df.nsmallest(n=2, columns=[\"population\", \"GDP\"], keep=\"all\"),\n )\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"dropna\", bool_arg_values, ids=arg_keys(\"dropna\", bool_arg_keys)\n )\n def test_nunique(self, data, axis, dropna):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n modin_result = modin_df.nunique(axis=axis, dropna=dropna)\n pandas_result = pandas_df.nunique(axis=axis, dropna=dropna)\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.T.nunique(axis=axis, dropna=dropna)\n pandas_result = pandas_df.T.nunique(axis=axis, dropna=dropna)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"q\", quantiles_values, ids=quantiles_keys)\n def test_quantile(self, request, data, q):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if not name_contains(request.node.name, no_numeric_dfs):\n df_equals(modin_df.quantile(q), pandas_df.quantile(q))\n df_equals(modin_df.quantile(q, axis=1), pandas_df.quantile(q, axis=1))\n\n try:\n pandas_result = pandas_df.quantile(q, axis=1, numeric_only=False)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.quantile(q, axis=1, numeric_only=False)\n else:\n modin_result = modin_df.quantile(q, axis=1, numeric_only=False)\n df_equals(modin_result, pandas_result)\n else:\n with pytest.raises(ValueError):\n modin_df.quantile(q)\n\n if not name_contains(request.node.name, no_numeric_dfs):\n df_equals(modin_df.T.quantile(q), pandas_df.T.quantile(q))\n df_equals(modin_df.T.quantile(q, axis=1), pandas_df.T.quantile(q, axis=1))\n\n try:\n pandas_result = pandas_df.T.quantile(q, axis=1, numeric_only=False)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.T.quantile(q, axis=1, numeric_only=False)\n else:\n modin_result = modin_df.T.quantile(q, axis=1, numeric_only=False)\n df_equals(modin_result, pandas_result)\n else:\n with pytest.raises(ValueError):\n modin_df.T.quantile(q)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"numeric_only\", bool_arg_values, ids=arg_keys(\"numeric_only\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"na_option\", [\"keep\", \"top\", \"bottom\"], ids=[\"keep\", \"top\", \"bottom\"]\n )\n def test_rank(self, data, axis, numeric_only, na_option):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.rank(\n axis=axis, numeric_only=numeric_only, na_option=na_option\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.rank(axis=axis, numeric_only=numeric_only, na_option=na_option)\n else:\n modin_result = modin_df.rank(\n axis=axis, numeric_only=numeric_only, na_option=na_option\n )\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"numeric_only\", bool_arg_values, ids=arg_keys(\"numeric_only\", bool_arg_keys)\n )\n def test_skew(self, request, data, axis, skipna, numeric_only):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.skew(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n except Exception:\n with pytest.raises(TypeError):\n modin_df.skew(axis=axis, skipna=skipna, numeric_only=numeric_only)\n else:\n modin_result = modin_df.skew(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.T.skew(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n except Exception:\n with pytest.raises(TypeError):\n modin_df.T.skew(axis=axis, skipna=skipna, numeric_only=numeric_only)\n else:\n modin_result = modin_df.T.skew(\n axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"numeric_only\", bool_arg_values, ids=arg_keys(\"numeric_only\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\"ddof\", int_arg_values, ids=arg_keys(\"ddof\", int_arg_keys))\n def test_std(self, request, data, axis, skipna, numeric_only, ddof):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.std(\n axis=axis, skipna=skipna, numeric_only=numeric_only, ddof=ddof\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.std(\n axis=axis, skipna=skipna, numeric_only=numeric_only, ddof=ddof\n )\n else:\n modin_result = modin_df.std(\n axis=axis, skipna=skipna, numeric_only=numeric_only, ddof=ddof\n )\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.T.std(\n axis=axis, skipna=skipna, numeric_only=numeric_only, ddof=ddof\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.T.std(\n axis=axis, skipna=skipna, numeric_only=numeric_only, ddof=ddof\n )\n else:\n modin_result = modin_df.T.std(\n axis=axis, skipna=skipna, numeric_only=numeric_only, ddof=ddof\n )\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_values(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n np.testing.assert_equal(modin_df.values, pandas_df.values)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"skipna\", bool_arg_values, ids=arg_keys(\"skipna\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\n \"numeric_only\", bool_arg_values, ids=arg_keys(\"numeric_only\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\"ddof\", int_arg_values, ids=arg_keys(\"ddof\", int_arg_keys))\n def test_var(self, request, data, axis, skipna, numeric_only, ddof):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.var(\n axis=axis, skipna=skipna, numeric_only=numeric_only, ddof=ddof\n )\n except Exception:\n with pytest.raises(TypeError):\n modin_df.var(\n axis=axis, skipna=skipna, numeric_only=numeric_only, ddof=ddof\n )\n else:\n modin_result = modin_df.var(\n axis=axis, skipna=skipna, numeric_only=numeric_only, ddof=ddof\n )\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.T.var(\n axis=axis, skipna=skipna, numeric_only=numeric_only, ddof=ddof\n )\n except Exception:\n with pytest.raises(TypeError):\n modin_df.T.var(\n axis=axis, skipna=skipna, numeric_only=numeric_only, ddof=ddof\n )\n else:\n modin_result = modin_df.T.var(\n axis=axis, skipna=skipna, numeric_only=numeric_only, ddof=ddof\n )\n df_equals(modin_result, pandas_result)\n\n\nclass TestDataFrameIndexing:\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_first_valid_index(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n assert modin_df.first_valid_index() == (pandas_df.first_valid_index())\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"n\", int_arg_values, ids=arg_keys(\"n\", int_arg_keys))\n def test_head(self, data, n):\n # Test normal dataframe head\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n df_equals(modin_df.head(n), pandas_df.head(n))\n df_equals(modin_df.head(len(modin_df) + 1), pandas_df.head(len(pandas_df) + 1))\n\n # Test head when we call it from a QueryCompilerView\n modin_result = modin_df.loc[:, [\"col1\", \"col3\", \"col3\"]].head(n)\n pandas_result = pandas_df.loc[:, [\"col1\", \"col3\", \"col3\"]].head(n)\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.skip(reason=\"Defaulting to Pandas\")\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_iat(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data) # noqa F841\n\n with pytest.raises(NotImplementedError):\n modin_df.iat()\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_iloc(self, request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if not name_contains(request.node.name, [\"empty_data\"]):\n # Scaler\n np.testing.assert_equal(modin_df.iloc[0, 1], pandas_df.iloc[0, 1])\n\n # Series\n df_equals(modin_df.iloc[0], pandas_df.iloc[0])\n df_equals(modin_df.iloc[1:, 0], pandas_df.iloc[1:, 0])\n df_equals(modin_df.iloc[1:2, 0], pandas_df.iloc[1:2, 0])\n\n # DataFrame\n df_equals(modin_df.iloc[[1, 2]], pandas_df.iloc[[1, 2]])\n # See issue #80\n # df_equals(modin_df.iloc[[1, 2], [1, 0]], pandas_df.iloc[[1, 2], [1, 0]])\n df_equals(modin_df.iloc[1:2, 0:2], pandas_df.iloc[1:2, 0:2])\n\n # Issue #43\n modin_df.iloc[0:3, :]\n\n # Write Item\n modin_df.iloc[[1, 2]] = 42\n pandas_df.iloc[[1, 2]] = 42\n df_equals(modin_df, pandas_df)\n\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n modin_df.iloc[0] = modin_df.iloc[1]\n pandas_df.iloc[0] = pandas_df.iloc[1]\n df_equals(modin_df, pandas_df)\n\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n modin_df.iloc[:, 0] = modin_df.iloc[:, 1]\n pandas_df.iloc[:, 0] = pandas_df.iloc[:, 1]\n df_equals(modin_df, pandas_df)\n\n # From issue #1775\n df_equals(\n modin_df.iloc[lambda df: df.index.get_indexer_for(df.index[:5])],\n pandas_df.iloc[lambda df: df.index.get_indexer_for(df.index[:5])],\n )\n else:\n with pytest.raises(IndexError):\n modin_df.iloc[0, 1]\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_index(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.index, pandas_df.index)\n modin_df_cp = modin_df.copy()\n pandas_df_cp = pandas_df.copy()\n\n modin_df_cp.index = [str(i) for i in modin_df_cp.index]\n pandas_df_cp.index = [str(i) for i in pandas_df_cp.index]\n df_equals(modin_df_cp.index, pandas_df_cp.index)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_indexing_duplicate_axis(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n modin_df.index = pandas_df.index = [i // 3 for i in range(len(modin_df))]\n assert any(modin_df.index.duplicated())\n assert any(pandas_df.index.duplicated())\n\n df_equals(modin_df.iloc[0], pandas_df.iloc[0])\n df_equals(modin_df.loc[0], pandas_df.loc[0])\n df_equals(modin_df.iloc[0, 0:4], pandas_df.iloc[0, 0:4])\n df_equals(\n modin_df.loc[0, modin_df.columns[0:4]],\n pandas_df.loc[0, pandas_df.columns[0:4]],\n )\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_keys(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.keys(), pandas_df.keys())\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_loc(self, request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n # We skip nan datasets because nan != nan\n if \"nan\" not in request.node.name:\n key1 = modin_df.columns[0]\n key2 = modin_df.columns[1]\n # Scaler\n assert modin_df.loc[0, key1] == pandas_df.loc[0, key1]\n\n # Series\n df_equals(modin_df.loc[0], pandas_df.loc[0])\n df_equals(modin_df.loc[1:, key1], pandas_df.loc[1:, key1])\n df_equals(modin_df.loc[1:2, key1], pandas_df.loc[1:2, key1])\n\n # DataFrame\n df_equals(modin_df.loc[[1, 2]], pandas_df.loc[[1, 2]])\n\n # List-like of booleans\n indices = [i % 3 == 0 for i in range(len(modin_df.index))]\n columns = [i % 5 == 0 for i in range(len(modin_df.columns))]\n modin_result = modin_df.loc[indices, columns]\n pandas_result = pandas_df.loc[indices, columns]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[:, columns]\n pandas_result = pandas_df.loc[:, columns]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[indices]\n pandas_result = pandas_df.loc[indices]\n df_equals(modin_result, pandas_result)\n\n # See issue #80\n # df_equals(modin_df.loc[[1, 2], ['col1']], pandas_df.loc[[1, 2], ['col1']])\n df_equals(modin_df.loc[1:2, key1:key2], pandas_df.loc[1:2, key1:key2])\n\n # From issue #421\n df_equals(modin_df.loc[:, [key2, key1]], pandas_df.loc[:, [key2, key1]])\n df_equals(modin_df.loc[[2, 1], :], pandas_df.loc[[2, 1], :])\n\n # From issue #1023\n key1 = modin_df.columns[0]\n key2 = modin_df.columns[-2]\n df_equals(modin_df.loc[:, key1:key2], pandas_df.loc[:, key1:key2])\n\n # Write Item\n modin_df_copy = modin_df.copy()\n pandas_df_copy = pandas_df.copy()\n modin_df_copy.loc[[1, 2]] = 42\n pandas_df_copy.loc[[1, 2]] = 42\n df_equals(modin_df_copy, pandas_df_copy)\n\n # From issue #1775\n df_equals(\n modin_df.loc[lambda df: df.iloc[:, 0].isin(list(range(1000)))],\n pandas_df.loc[lambda df: df.iloc[:, 0].isin(list(range(1000)))],\n )\n\n # From issue #1374\n with pytest.raises(KeyError):\n modin_df.loc[\"NO_EXIST\"]\n\n def test_loc_multi_index(self):\n modin_df = pd.read_csv(\n \"modin/pandas/test/data/blah.csv\", header=[0, 1, 2, 3], index_col=0\n )\n pandas_df = pandas.read_csv(\n \"modin/pandas/test/data/blah.csv\", header=[0, 1, 2, 3], index_col=0\n )\n\n df_equals(modin_df.loc[1], pandas_df.loc[1])\n df_equals(modin_df.loc[1, \"Presidents\"], pandas_df.loc[1, \"Presidents\"])\n df_equals(\n modin_df.loc[1, (\"Presidents\", \"Pure mentions\")],\n pandas_df.loc[1, (\"Presidents\", \"Pure mentions\")],\n )\n assert (\n modin_df.loc[1, (\"Presidents\", \"Pure mentions\", \"IND\", \"all\")]\n == pandas_df.loc[1, (\"Presidents\", \"Pure mentions\", \"IND\", \"all\")]\n )\n df_equals(\n modin_df.loc[(1, 2), \"Presidents\"], pandas_df.loc[(1, 2), \"Presidents\"]\n )\n\n tuples = [\n (\"bar\", \"one\"),\n (\"bar\", \"two\"),\n (\"bar\", \"three\"),\n (\"bar\", \"four\"),\n (\"baz\", \"one\"),\n (\"baz\", \"two\"),\n (\"baz\", \"three\"),\n (\"baz\", \"four\"),\n (\"foo\", \"one\"),\n (\"foo\", \"two\"),\n (\"foo\", \"three\"),\n (\"foo\", \"four\"),\n (\"qux\", \"one\"),\n (\"qux\", \"two\"),\n (\"qux\", \"three\"),\n (\"qux\", \"four\"),\n ]\n\n modin_index = pd.MultiIndex.from_tuples(tuples, names=[\"first\", \"second\"])\n pandas_index = pandas.MultiIndex.from_tuples(tuples, names=[\"first\", \"second\"])\n frame_data = np.random.randint(0, 100, size=(16, 100))\n modin_df = pd.DataFrame(\n frame_data,\n index=modin_index,\n columns=[\"col{}\".format(i) for i in range(100)],\n )\n pandas_df = pandas.DataFrame(\n frame_data,\n index=pandas_index,\n columns=[\"col{}\".format(i) for i in range(100)],\n )\n df_equals(modin_df.loc[\"bar\", \"col1\"], pandas_df.loc[\"bar\", \"col1\"])\n assert (\n modin_df.loc[(\"bar\", \"one\"), \"col1\"]\n == pandas_df.loc[(\"bar\", \"one\"), \"col1\"]\n )\n df_equals(\n modin_df.loc[\"bar\", (\"col1\", \"col2\")],\n pandas_df.loc[\"bar\", (\"col1\", \"col2\")],\n )\n\n # From issue #1456\n transposed_modin = modin_df.T\n transposed_pandas = pandas_df.T\n df_equals(\n transposed_modin.loc[transposed_modin.index[:-2], :],\n transposed_pandas.loc[transposed_pandas.index[:-2], :],\n )\n\n # From issue #1610\n df_equals(modin_df.loc[modin_df.index], pandas_df.loc[pandas_df.index])\n df_equals(modin_df.loc[modin_df.index[:7]], pandas_df.loc[pandas_df.index[:7]])\n\n def test_loc_assignment(self):\n modin_df = pd.DataFrame(\n index=[\"row1\", \"row2\", \"row3\"], columns=[\"col1\", \"col2\"]\n )\n pandas_df = pandas.DataFrame(\n index=[\"row1\", \"row2\", \"row3\"], columns=[\"col1\", \"col2\"]\n )\n modin_df.loc[\"row1\"][\"col1\"] = 11\n modin_df.loc[\"row2\"][\"col1\"] = 21\n modin_df.loc[\"row3\"][\"col1\"] = 31\n modin_df.loc[\"row1\"][\"col2\"] = 12\n modin_df.loc[\"row2\"][\"col2\"] = 22\n modin_df.loc[\"row3\"][\"col2\"] = 32\n pandas_df.loc[\"row1\"][\"col1\"] = 11\n pandas_df.loc[\"row2\"][\"col1\"] = 21\n pandas_df.loc[\"row3\"][\"col1\"] = 31\n pandas_df.loc[\"row1\"][\"col2\"] = 12\n pandas_df.loc[\"row2\"][\"col2\"] = 22\n pandas_df.loc[\"row3\"][\"col2\"] = 32\n df_equals(modin_df, pandas_df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_loc_nested_assignment(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n key1 = modin_df.columns[0]\n key2 = modin_df.columns[1]\n\n modin_df[key1].loc[0] = 500\n pandas_df[key1].loc[0] = 500\n df_equals(modin_df, pandas_df)\n\n modin_df[key2].loc[0] = None\n pandas_df[key2].loc[0] = None\n df_equals(modin_df, pandas_df)\n\n def test_iloc_assignment(self):\n modin_df = pd.DataFrame(\n index=[\"row1\", \"row2\", \"row3\"], columns=[\"col1\", \"col2\"]\n )\n pandas_df = pandas.DataFrame(\n index=[\"row1\", \"row2\", \"row3\"], columns=[\"col1\", \"col2\"]\n )\n modin_df.iloc[0][\"col1\"] = 11\n modin_df.iloc[1][\"col1\"] = 21\n modin_df.iloc[2][\"col1\"] = 31\n modin_df.iloc[0][\"col2\"] = 12\n modin_df.iloc[1][\"col2\"] = 22\n modin_df.iloc[2][\"col2\"] = 32\n pandas_df.iloc[0][\"col1\"] = 11\n pandas_df.iloc[1][\"col1\"] = 21\n pandas_df.iloc[2][\"col1\"] = 31\n pandas_df.iloc[0][\"col2\"] = 12\n pandas_df.iloc[1][\"col2\"] = 22\n pandas_df.iloc[2][\"col2\"] = 32\n df_equals(modin_df, pandas_df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_iloc_nested_assignment(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n key1 = modin_df.columns[0]\n key2 = modin_df.columns[1]\n\n modin_df[key1].iloc[0] = 500\n pandas_df[key1].iloc[0] = 500\n df_equals(modin_df, pandas_df)\n\n modin_df[key2].iloc[0] = None\n pandas_df[key2].iloc[0] = None\n df_equals(modin_df, pandas_df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_pop(self, request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if \"empty_data\" not in request.node.name:\n key = modin_df.columns[0]\n temp_modin_df = modin_df.copy()\n temp_pandas_df = pandas_df.copy()\n modin_popped = temp_modin_df.pop(key)\n pandas_popped = temp_pandas_df.pop(key)\n df_equals(modin_popped, pandas_popped)\n df_equals(temp_modin_df, temp_pandas_df)\n\n def test_reindex(self):\n frame_data = {\n \"col1\": [0, 1, 2, 3],\n \"col2\": [4, 5, 6, 7],\n \"col3\": [8, 9, 10, 11],\n \"col4\": [12, 13, 14, 15],\n \"col5\": [0, 0, 0, 0],\n }\n pandas_df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data)\n\n df_equals(modin_df.reindex([0, 3, 2, 1]), pandas_df.reindex([0, 3, 2, 1]))\n df_equals(modin_df.reindex([0, 6, 2]), pandas_df.reindex([0, 6, 2]))\n df_equals(\n modin_df.reindex([\"col1\", \"col3\", \"col4\", \"col2\"], axis=1),\n pandas_df.reindex([\"col1\", \"col3\", \"col4\", \"col2\"], axis=1),\n )\n df_equals(\n modin_df.reindex([\"col1\", \"col7\", \"col4\", \"col8\"], axis=1),\n pandas_df.reindex([\"col1\", \"col7\", \"col4\", \"col8\"], axis=1),\n )\n df_equals(\n modin_df.reindex(index=[0, 1, 5], columns=[\"col1\", \"col7\", \"col4\", \"col8\"]),\n pandas_df.reindex(\n index=[0, 1, 5], columns=[\"col1\", \"col7\", \"col4\", \"col8\"]\n ),\n )\n df_equals(\n modin_df.T.reindex([\"col1\", \"col7\", \"col4\", \"col8\"], axis=0),\n pandas_df.T.reindex([\"col1\", \"col7\", \"col4\", \"col8\"], axis=0),\n )\n\n def test_reindex_like(self):\n df1 = pd.DataFrame(\n [\n [24.3, 75.7, \"high\"],\n [31, 87.8, \"high\"],\n [22, 71.6, \"medium\"],\n [35, 95, \"medium\"],\n ],\n columns=[\"temp_celsius\", \"temp_fahrenheit\", \"windspeed\"],\n index=pd.date_range(start=\"2014-02-12\", end=\"2014-02-15\", freq=\"D\"),\n )\n df2 = pd.DataFrame(\n [[28, \"low\"], [30, \"low\"], [35.1, \"medium\"]],\n columns=[\"temp_celsius\", \"windspeed\"],\n index=pd.DatetimeIndex([\"2014-02-12\", \"2014-02-13\", \"2014-02-15\"]),\n )\n with pytest.warns(UserWarning):\n df2.reindex_like(df1)\n\n def test_rename_sanity(self):\n test_data = pandas.DataFrame(tm.getSeriesData())\n mapping = {\"A\": \"a\", \"B\": \"b\", \"C\": \"c\", \"D\": \"d\"}\n\n modin_df = pd.DataFrame(test_data)\n df_equals(modin_df.rename(columns=mapping), test_data.rename(columns=mapping))\n\n renamed2 = test_data.rename(columns=str.lower)\n df_equals(modin_df.rename(columns=str.lower), renamed2)\n\n modin_df = pd.DataFrame(renamed2)\n df_equals(\n modin_df.rename(columns=str.upper), renamed2.rename(columns=str.upper)\n )\n\n # index\n data = {\"A\": {\"foo\": 0, \"bar\": 1}}\n\n # gets sorted alphabetical\n df = pandas.DataFrame(data)\n modin_df = pd.DataFrame(data)\n tm.assert_index_equal(\n modin_df.rename(index={\"foo\": \"bar\", \"bar\": \"foo\"}).index,\n df.rename(index={\"foo\": \"bar\", \"bar\": \"foo\"}).index,\n )\n\n tm.assert_index_equal(\n modin_df.rename(index=str.upper).index, df.rename(index=str.upper).index\n )\n\n # Using the `mapper` functionality with `axis`\n tm.assert_index_equal(\n modin_df.rename(str.upper, axis=0).index, df.rename(str.upper, axis=0).index\n )\n tm.assert_index_equal(\n modin_df.rename(str.upper, axis=1).columns,\n df.rename(str.upper, axis=1).columns,\n )\n\n # have to pass something\n with pytest.raises(TypeError):\n modin_df.rename()\n\n # partial columns\n renamed = test_data.rename(columns={\"C\": \"foo\", \"D\": \"bar\"})\n modin_df = pd.DataFrame(test_data)\n tm.assert_index_equal(\n modin_df.rename(columns={\"C\": \"foo\", \"D\": \"bar\"}).index,\n test_data.rename(columns={\"C\": \"foo\", \"D\": \"bar\"}).index,\n )\n\n # other axis\n renamed = test_data.T.rename(index={\"C\": \"foo\", \"D\": \"bar\"})\n tm.assert_index_equal(\n test_data.T.rename(index={\"C\": \"foo\", \"D\": \"bar\"}).index,\n modin_df.T.rename(index={\"C\": \"foo\", \"D\": \"bar\"}).index,\n )\n\n # index with name\n index = pandas.Index([\"foo\", \"bar\"], name=\"name\")\n renamer = pandas.DataFrame(data, index=index)\n modin_df = pd.DataFrame(data, index=index)\n\n renamed = renamer.rename(index={\"foo\": \"bar\", \"bar\": \"foo\"})\n modin_renamed = modin_df.rename(index={\"foo\": \"bar\", \"bar\": \"foo\"})\n tm.assert_index_equal(renamed.index, modin_renamed.index)\n\n assert renamed.index.name == modin_renamed.index.name\n\n def test_rename_multiindex(self):\n tuples_index = [(\"foo1\", \"bar1\"), (\"foo2\", \"bar2\")]\n tuples_columns = [(\"fizz1\", \"buzz1\"), (\"fizz2\", \"buzz2\")]\n index = pandas.MultiIndex.from_tuples(tuples_index, names=[\"foo\", \"bar\"])\n columns = pandas.MultiIndex.from_tuples(tuples_columns, names=[\"fizz\", \"buzz\"])\n\n frame_data = [(0, 0), (1, 1)]\n df = pandas.DataFrame(frame_data, index=index, columns=columns)\n modin_df = pd.DataFrame(frame_data, index=index, columns=columns)\n\n #\n # without specifying level -> accross all levels\n renamed = df.rename(\n index={\"foo1\": \"foo3\", \"bar2\": \"bar3\"},\n columns={\"fizz1\": \"fizz3\", \"buzz2\": \"buzz3\"},\n )\n modin_renamed = modin_df.rename(\n index={\"foo1\": \"foo3\", \"bar2\": \"bar3\"},\n columns={\"fizz1\": \"fizz3\", \"buzz2\": \"buzz3\"},\n )\n tm.assert_index_equal(renamed.index, modin_renamed.index)\n\n renamed = df.rename(\n index={\"foo1\": \"foo3\", \"bar2\": \"bar3\"},\n columns={\"fizz1\": \"fizz3\", \"buzz2\": \"buzz3\"},\n )\n tm.assert_index_equal(renamed.columns, modin_renamed.columns)\n assert renamed.index.names == modin_renamed.index.names\n assert renamed.columns.names == modin_renamed.columns.names\n\n #\n # with specifying a level\n\n # dict\n renamed = df.rename(columns={\"fizz1\": \"fizz3\", \"buzz2\": \"buzz3\"}, level=0)\n modin_renamed = modin_df.rename(\n columns={\"fizz1\": \"fizz3\", \"buzz2\": \"buzz3\"}, level=0\n )\n tm.assert_index_equal(renamed.columns, modin_renamed.columns)\n renamed = df.rename(columns={\"fizz1\": \"fizz3\", \"buzz2\": \"buzz3\"}, level=\"fizz\")\n modin_renamed = modin_df.rename(\n columns={\"fizz1\": \"fizz3\", \"buzz2\": \"buzz3\"}, level=\"fizz\"\n )\n tm.assert_index_equal(renamed.columns, modin_renamed.columns)\n\n renamed = df.rename(columns={\"fizz1\": \"fizz3\", \"buzz2\": \"buzz3\"}, level=1)\n modin_renamed = modin_df.rename(\n columns={\"fizz1\": \"fizz3\", \"buzz2\": \"buzz3\"}, level=1\n )\n tm.assert_index_equal(renamed.columns, modin_renamed.columns)\n renamed = df.rename(columns={\"fizz1\": \"fizz3\", \"buzz2\": \"buzz3\"}, level=\"buzz\")\n modin_renamed = modin_df.rename(\n columns={\"fizz1\": \"fizz3\", \"buzz2\": \"buzz3\"}, level=\"buzz\"\n )\n tm.assert_index_equal(renamed.columns, modin_renamed.columns)\n\n # function\n func = str.upper\n renamed = df.rename(columns=func, level=0)\n modin_renamed = modin_df.rename(columns=func, level=0)\n tm.assert_index_equal(renamed.columns, modin_renamed.columns)\n renamed = df.rename(columns=func, level=\"fizz\")\n modin_renamed = modin_df.rename(columns=func, level=\"fizz\")\n tm.assert_index_equal(renamed.columns, modin_renamed.columns)\n\n renamed = df.rename(columns=func, level=1)\n modin_renamed = modin_df.rename(columns=func, level=1)\n tm.assert_index_equal(renamed.columns, modin_renamed.columns)\n renamed = df.rename(columns=func, level=\"buzz\")\n modin_renamed = modin_df.rename(columns=func, level=\"buzz\")\n tm.assert_index_equal(renamed.columns, modin_renamed.columns)\n\n # index\n renamed = df.rename(index={\"foo1\": \"foo3\", \"bar2\": \"bar3\"}, level=0)\n modin_renamed = modin_df.rename(index={\"foo1\": \"foo3\", \"bar2\": \"bar3\"}, level=0)\n tm.assert_index_equal(modin_renamed.index, renamed.index)\n\n @pytest.mark.skip(reason=\"Pandas does not pass this test\")\n def test_rename_nocopy(self):\n test_data = pandas.DataFrame(tm.getSeriesData())\n modin_df = pd.DataFrame(test_data)\n modin_renamed = modin_df.rename(columns={\"C\": \"foo\"}, copy=False)\n modin_renamed[\"foo\"] = 1\n assert (modin_df[\"C\"] == 1).all()\n\n def test_rename_inplace(self):\n test_data = pandas.DataFrame(tm.getSeriesData())\n modin_df = pd.DataFrame(test_data)\n\n df_equals(\n modin_df.rename(columns={\"C\": \"foo\"}),\n test_data.rename(columns={\"C\": \"foo\"}),\n )\n\n frame = test_data.copy()\n modin_frame = modin_df.copy()\n frame.rename(columns={\"C\": \"foo\"}, inplace=True)\n modin_frame.rename(columns={\"C\": \"foo\"}, inplace=True)\n\n df_equals(modin_frame, frame)\n\n def test_rename_bug(self):\n # rename set ref_locs, and set_index was not resetting\n frame_data = {0: [\"foo\", \"bar\"], 1: [\"bah\", \"bas\"], 2: [1, 2]}\n df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data)\n df = df.rename(columns={0: \"a\"})\n df = df.rename(columns={1: \"b\"})\n df = df.set_index([\"a\", \"b\"])\n df.columns = [\"2001-01-01\"]\n\n modin_df = modin_df.rename(columns={0: \"a\"})\n modin_df = modin_df.rename(columns={1: \"b\"})\n modin_df = modin_df.set_index([\"a\", \"b\"])\n modin_df.columns = [\"2001-01-01\"]\n\n df_equals(modin_df, df)\n\n def test_rename_axis(self):\n data = {\"num_legs\": [4, 4, 2], \"num_arms\": [0, 0, 2]}\n index = [\"dog\", \"cat\", \"monkey\"]\n modin_df = pd.DataFrame(data, index)\n pandas_df = pandas.DataFrame(data, index)\n df_equals(modin_df.rename_axis(\"animal\"), pandas_df.rename_axis(\"animal\"))\n df_equals(\n modin_df.rename_axis(\"limbs\", axis=\"columns\"),\n pandas_df.rename_axis(\"limbs\", axis=\"columns\"),\n )\n\n modin_df.rename_axis(\"limbs\", axis=\"columns\", inplace=True)\n pandas_df.rename_axis(\"limbs\", axis=\"columns\", inplace=True)\n df_equals(modin_df, pandas_df)\n\n new_index = pd.MultiIndex.from_product(\n [[\"mammal\"], [\"dog\", \"cat\", \"monkey\"]], names=[\"type\", \"name\"]\n )\n modin_df.index = new_index\n pandas_df.index = new_index\n\n df_equals(\n modin_df.rename_axis(index={\"type\": \"class\"}),\n pandas_df.rename_axis(index={\"type\": \"class\"}),\n )\n df_equals(\n modin_df.rename_axis(columns=str.upper),\n pandas_df.rename_axis(columns=str.upper),\n )\n df_equals(\n modin_df.rename_axis(\n columns=[str.upper(o) for o in modin_df.columns.names]\n ),\n pandas_df.rename_axis(\n columns=[str.upper(o) for o in pandas_df.columns.names]\n ),\n )\n\n with pytest.raises(ValueError):\n df_equals(\n modin_df.rename_axis(str.upper, axis=1),\n pandas_df.rename_axis(str.upper, axis=1),\n )\n\n def test_rename_axis_inplace(self):\n test_frame = pandas.DataFrame(tm.getSeriesData())\n modin_df = pd.DataFrame(test_frame)\n\n result = test_frame.copy()\n modin_result = modin_df.copy()\n no_return = result.rename_axis(\"foo\", inplace=True)\n modin_no_return = modin_result.rename_axis(\"foo\", inplace=True)\n\n assert no_return is modin_no_return\n df_equals(modin_result, result)\n\n result = test_frame.copy()\n modin_result = modin_df.copy()\n no_return = result.rename_axis(\"bar\", axis=1, inplace=True)\n modin_no_return = modin_result.rename_axis(\"bar\", axis=1, inplace=True)\n\n assert no_return is modin_no_return\n df_equals(modin_result, result)\n\n def test_reorder_levels(self):\n data = np.random.randint(1, 100, 12)\n modin_df = pd.DataFrame(\n data,\n index=pd.MultiIndex.from_tuples(\n [\n (num, letter, color)\n for num in range(1, 3)\n for letter in [\"a\", \"b\", \"c\"]\n for color in [\"Red\", \"Green\"]\n ],\n names=[\"Number\", \"Letter\", \"Color\"],\n ),\n )\n pandas_df = pandas.DataFrame(\n data,\n index=pandas.MultiIndex.from_tuples(\n [\n (num, letter, color)\n for num in range(1, 3)\n for letter in [\"a\", \"b\", \"c\"]\n for color in [\"Red\", \"Green\"]\n ],\n names=[\"Number\", \"Letter\", \"Color\"],\n ),\n )\n df_equals(\n modin_df.reorder_levels([\"Letter\", \"Color\", \"Number\"]),\n pandas_df.reorder_levels([\"Letter\", \"Color\", \"Number\"]),\n )\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_reset_index(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n modin_result = modin_df.reset_index(inplace=False)\n pandas_result = pandas_df.reset_index(inplace=False)\n df_equals(modin_result, pandas_result)\n\n modin_df_cp = modin_df.copy()\n pd_df_cp = pandas_df.copy()\n modin_df_cp.reset_index(inplace=True)\n pd_df_cp.reset_index(inplace=True)\n df_equals(modin_df_cp, pd_df_cp)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n def test_sample(self, data, axis):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n with pytest.raises(ValueError):\n modin_df.sample(n=3, frac=0.4, axis=axis)\n\n with pytest.raises(KeyError):\n modin_df.sample(frac=0.5, weights=\"CoLuMn_No_ExIsT\", axis=0)\n\n with pytest.raises(ValueError):\n modin_df.sample(frac=0.5, weights=modin_df.columns[0], axis=1)\n\n with pytest.raises(ValueError):\n modin_df.sample(\n frac=0.5, weights=[0.5 for _ in range(len(modin_df.index[:-1]))], axis=0\n )\n\n with pytest.raises(ValueError):\n modin_df.sample(\n frac=0.5,\n weights=[0.5 for _ in range(len(modin_df.columns[:-1]))],\n axis=1,\n )\n\n with pytest.raises(ValueError):\n modin_df.sample(n=-3, axis=axis)\n\n with pytest.raises(ValueError):\n modin_df.sample(frac=0.2, weights=pandas.Series(), axis=axis)\n\n if isinstance(axis, str):\n num_axis = pandas.DataFrame()._get_axis_number(axis)\n else:\n num_axis = axis\n\n # weights that sum to 1\n sums = sum(i % 2 for i in range(len(modin_df.axes[num_axis])))\n weights = [i % 2 / sums for i in range(len(modin_df.axes[num_axis]))]\n\n modin_result = modin_df.sample(\n frac=0.5, random_state=42, weights=weights, axis=axis\n )\n pandas_result = pandas_df.sample(\n frac=0.5, random_state=42, weights=weights, axis=axis\n )\n df_equals(modin_result, pandas_result)\n\n # weights that don't sum to 1\n weights = [i % 2 for i in range(len(modin_df.axes[num_axis]))]\n modin_result = modin_df.sample(\n frac=0.5, random_state=42, weights=weights, axis=axis\n )\n pandas_result = pandas_df.sample(\n frac=0.5, random_state=42, weights=weights, axis=axis\n )\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.sample(n=0, axis=axis)\n pandas_result = pandas_df.sample(n=0, axis=axis)\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.sample(frac=0.5, random_state=42, axis=axis)\n pandas_result = pandas_df.sample(frac=0.5, random_state=42, axis=axis)\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.sample(n=2, random_state=42, axis=axis)\n pandas_result = pandas_df.sample(n=2, random_state=42, axis=axis)\n df_equals(modin_result, pandas_result)\n\n # issue #1692, numpy RandomState object\n # We must create a new random state for each iteration because the values that\n # are selected will be impacted if the object has already been used.\n random_state = np.random.RandomState(42)\n modin_result = modin_df.sample(frac=0.5, random_state=random_state, axis=axis)\n\n random_state = np.random.RandomState(42)\n pandas_result = pandas_df.sample(frac=0.5, random_state=random_state, axis=axis)\n df_equals(modin_result, pandas_result)\n\n def test_select_dtypes(self):\n frame_data = {\n \"test1\": list(\"abc\"),\n \"test2\": np.arange(3, 6).astype(\"u1\"),\n \"test3\": np.arange(8.0, 11.0, dtype=\"float64\"),\n \"test4\": [True, False, True],\n \"test5\": pandas.date_range(\"now\", periods=3).values,\n \"test6\": list(range(5, 8)),\n }\n df = pandas.DataFrame(frame_data)\n rd = pd.DataFrame(frame_data)\n\n include = np.float, \"integer\"\n exclude = (np.bool_,)\n r = rd.select_dtypes(include=include, exclude=exclude)\n\n e = df[[\"test2\", \"test3\", \"test6\"]]\n df_equals(r, e)\n\n r = rd.select_dtypes(include=np.bool_)\n e = df[[\"test4\"]]\n df_equals(r, e)\n\n r = rd.select_dtypes(exclude=np.bool_)\n e = df[[\"test1\", \"test2\", \"test3\", \"test5\", \"test6\"]]\n df_equals(r, e)\n\n try:\n pd.DataFrame().select_dtypes()\n assert False\n except ValueError:\n assert True\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"n\", int_arg_values, ids=arg_keys(\"n\", int_arg_keys))\n def test_tail(self, data, n):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.tail(n), pandas_df.tail(n))\n df_equals(modin_df.tail(len(modin_df)), pandas_df.tail(len(pandas_df)))\n\n def test_xs(self):\n d = {\n \"num_legs\": [4, 4, 2, 2],\n \"num_wings\": [0, 0, 2, 2],\n \"class\": [\"mammal\", \"mammal\", \"mammal\", \"bird\"],\n \"animal\": [\"cat\", \"dog\", \"bat\", \"penguin\"],\n \"locomotion\": [\"walks\", \"walks\", \"flies\", \"walks\"],\n }\n df = pd.DataFrame(data=d)\n df = df.set_index([\"class\", \"animal\", \"locomotion\"])\n with pytest.warns(UserWarning):\n df.xs(\"mammal\")\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___getitem__(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n key = modin_df.columns[0]\n modin_col = modin_df.__getitem__(key)\n assert isinstance(modin_col, pd.Series)\n\n pd_col = pandas_df[key]\n df_equals(pd_col, modin_col)\n\n slices = [\n (None, -1),\n (-1, None),\n (1, 2),\n (1, None),\n (None, 1),\n (1, -1),\n (-3, -1),\n (1, -1, 2),\n ]\n\n # slice test\n for slice_param in slices:\n s = slice(*slice_param)\n df_equals(modin_df[s], pandas_df[s])\n\n # Test empty\n df_equals(pd.DataFrame([])[:10], pandas.DataFrame([])[:10])\n\n def test_getitem_empty_mask(self):\n # modin-project/modin#517\n modin_frames = []\n pandas_frames = []\n data1 = np.random.randint(0, 100, size=(100, 4))\n mdf1 = pd.DataFrame(data1, columns=list(\"ABCD\"))\n pdf1 = pandas.DataFrame(data1, columns=list(\"ABCD\"))\n modin_frames.append(mdf1)\n pandas_frames.append(pdf1)\n\n data2 = np.random.randint(0, 100, size=(100, 4))\n mdf2 = pd.DataFrame(data2, columns=list(\"ABCD\"))\n pdf2 = pandas.DataFrame(data2, columns=list(\"ABCD\"))\n modin_frames.append(mdf2)\n pandas_frames.append(pdf2)\n\n data3 = np.random.randint(0, 100, size=(100, 4))\n mdf3 = pd.DataFrame(data3, columns=list(\"ABCD\"))\n pdf3 = pandas.DataFrame(data3, columns=list(\"ABCD\"))\n modin_frames.append(mdf3)\n pandas_frames.append(pdf3)\n\n modin_data = pd.concat(modin_frames)\n pandas_data = pandas.concat(pandas_frames)\n df_equals(\n modin_data[[False for _ in modin_data.index]],\n pandas_data[[False for _ in modin_data.index]],\n )\n\n def test_getitem_datetime_slice(self):\n data = {\"data\": range(1000)}\n index = pd.date_range(\"2017/1/4\", periods=1000)\n modin_df = pd.DataFrame(data=data, index=index)\n pandas_df = pandas.DataFrame(data=data, index=index)\n\n s = slice(\"2017-01-06\", \"2017-01-09\")\n df_equals(modin_df[s], pandas_df[s])\n\n def test_getitem_same_name(self):\n data = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n [17, 18, 19, 20],\n ]\n columns = [\"c1\", \"c2\", \"c1\", \"c3\"]\n modin_df = pd.DataFrame(data, columns=columns)\n pandas_df = pandas.DataFrame(data, columns=columns)\n df_equals(modin_df[\"c1\"], pandas_df[\"c1\"])\n df_equals(modin_df[\"c2\"], pandas_df[\"c2\"])\n df_equals(modin_df[[\"c1\", \"c2\"]], pandas_df[[\"c1\", \"c2\"]])\n df_equals(modin_df[\"c3\"], pandas_df[\"c3\"])\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___getattr__(self, request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data) # noqa F841\n\n if \"empty_data\" not in request.node.name:\n key = modin_df.columns[0]\n col = modin_df.__getattr__(key)\n\n col = modin_df.__getattr__(\"col1\")\n assert isinstance(col, pd.Series)\n\n col = getattr(modin_df, \"col1\")\n assert isinstance(col, pd.Series)\n\n # Check that lookup in column doesn't override other attributes\n df2 = modin_df.rename(index=str, columns={key: \"columns\"})\n assert isinstance(df2.columns, pandas.Index)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___setitem__(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n modin_df.__setitem__(modin_df.columns[-1], 1)\n pandas_df.__setitem__(pandas_df.columns[-1], 1)\n df_equals(modin_df, pandas_df)\n\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n modin_df[modin_df.columns[-1]] = pd.DataFrame(modin_df[modin_df.columns[0]])\n pandas_df[pandas_df.columns[-1]] = pandas.DataFrame(\n pandas_df[pandas_df.columns[0]]\n )\n df_equals(modin_df, pandas_df)\n\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n rows = len(modin_df)\n arr = np.arange(rows * 2).reshape(-1, 2)\n modin_df[modin_df.columns[-1]] = arr\n pandas_df[pandas_df.columns[-1]] = arr\n df_equals(pandas_df, modin_df)\n\n with pytest.raises(ValueError, match=r\"Wrong number of items passed\"):\n modin_df[\"___NON EXISTENT COLUMN\"] = arr\n\n modin_df[modin_df.columns[0]] = np.arange(len(modin_df))\n pandas_df[pandas_df.columns[0]] = np.arange(len(pandas_df))\n df_equals(modin_df, pandas_df)\n\n modin_df = pd.DataFrame(columns=modin_df.columns)\n pandas_df = pandas.DataFrame(columns=pandas_df.columns)\n\n for col in modin_df.columns:\n modin_df[col] = np.arange(1000)\n\n for col in pandas_df.columns:\n pandas_df[col] = np.arange(1000)\n\n df_equals(modin_df, pandas_df)\n\n # Test series assignment to column\n modin_df = pd.DataFrame(columns=modin_df.columns)\n pandas_df = pandas.DataFrame(columns=pandas_df.columns)\n modin_df[modin_df.columns[-1]] = modin_df[modin_df.columns[0]]\n pandas_df[pandas_df.columns[-1]] = pandas_df[pandas_df.columns[0]]\n df_equals(modin_df, pandas_df)\n\n if not sys.version_info.major == 3 and sys.version_info.minor > 6:\n # This test doesn't work correctly on Python 3.6\n # Test 2d ndarray assignment to column\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n modin_df[\"new_col\"] = modin_df[[modin_df.columns[0]]].values\n pandas_df[\"new_col\"] = pandas_df[[pandas_df.columns[0]]].values\n df_equals(modin_df, pandas_df)\n assert isinstance(modin_df[\"new_col\"][0], type(pandas_df[\"new_col\"][0]))\n\n # Transpose test\n modin_df = pd.DataFrame(data).T\n pandas_df = pandas.DataFrame(data).T\n\n # We default to pandas on non-string column names\n if not all(isinstance(c, str) for c in modin_df.columns):\n with pytest.warns(UserWarning):\n modin_df[modin_df.columns[0]] = 0\n else:\n modin_df[modin_df.columns[0]] = 0\n\n pandas_df[pandas_df.columns[0]] = 0\n\n df_equals(modin_df, pandas_df)\n\n modin_df.columns = [str(i) for i in modin_df.columns]\n pandas_df.columns = [str(i) for i in pandas_df.columns]\n\n modin_df[modin_df.columns[0]] = 0\n pandas_df[pandas_df.columns[0]] = 0\n\n df_equals(modin_df, pandas_df)\n\n modin_df[modin_df.columns[0]][modin_df.index[0]] = 12345\n pandas_df[pandas_df.columns[0]][pandas_df.index[0]] = 12345\n\n df_equals(modin_df, pandas_df)\n\n @pytest.mark.parametrize(\n \"data\",\n [\n {},\n pytest.param(\n {\"id\": [], \"max_speed\": [], \"health\": []},\n marks=pytest.mark.xfail(\n reason=\"Throws an exception because generally assigning Series or other objects of length different from DataFrame does not work right now\"\n ),\n ),\n ],\n ids=[\"empty\", \"empty_columns\"],\n )\n @pytest.mark.parametrize(\n \"value\", [np.array([\"one\", \"two\"]), [11, 22]], ids=[\"ndarray\", \"list\"],\n )\n @pytest.mark.parametrize(\"convert_to_series\", [False, True])\n @pytest.mark.parametrize(\"new_col_id\", [123, \"new_col\"], ids=[\"integer\", \"string\"])\n def test_setitem_on_empty_df(self, data, value, convert_to_series, new_col_id):\n pandas_df = pandas.DataFrame(data)\n modin_df = pd.DataFrame(data)\n\n pandas_df[new_col_id] = pandas.Series(value) if convert_to_series else value\n modin_df[new_col_id] = pd.Series(value) if convert_to_series else value\n df_equals(modin_df, pandas_df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___len__(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n assert len(modin_df) == len(pandas_df)\n\n\nclass TestDataFrameIter:\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_items(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n modin_items = modin_df.items()\n pandas_items = pandas_df.items()\n for modin_item, pandas_item in zip(modin_items, pandas_items):\n modin_index, modin_series = modin_item\n pandas_index, pandas_series = pandas_item\n df_equals(pandas_series, modin_series)\n assert pandas_index == modin_index\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_iteritems(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n modin_items = modin_df.iteritems()\n pandas_items = pandas_df.iteritems()\n for modin_item, pandas_item in zip(modin_items, pandas_items):\n modin_index, modin_series = modin_item\n pandas_index, pandas_series = pandas_item\n df_equals(pandas_series, modin_series)\n assert pandas_index == modin_index\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_iterrows(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n modin_iterrows = modin_df.iterrows()\n pandas_iterrows = pandas_df.iterrows()\n for modin_row, pandas_row in zip(modin_iterrows, pandas_iterrows):\n modin_index, modin_series = modin_row\n pandas_index, pandas_series = pandas_row\n df_equals(pandas_series, modin_series)\n assert pandas_index == modin_index\n\n @pytest.mark.parametrize(\"name\", [None, \"NotPandas\", \"Pandas\"])\n @pytest.mark.parametrize(\"index\", [True, False])\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_itertuples(self, name, index, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n # test default\n modin_it_default = modin_df.itertuples()\n pandas_it_default = pandas_df.itertuples()\n for modin_row, pandas_row in zip(modin_it_default, pandas_it_default):\n np.testing.assert_equal(modin_row, pandas_row)\n\n modin_it_custom = modin_df.itertuples(index=index, name=name)\n pandas_it_custom = pandas_df.itertuples(index=index, name=name)\n for modin_row, pandas_row in zip(modin_it_custom, pandas_it_custom):\n np.testing.assert_equal(modin_row, pandas_row)\n\n mi_index_modin = pd.MultiIndex.from_tuples(\n [(i // 4, i // 2, i) for i in range(len(modin_df.columns))]\n )\n mi_index_pandas = pandas.MultiIndex.from_tuples(\n [(i // 4, i // 2, i) for i in range(len(pandas_df.columns))]\n )\n modin_df.columns = mi_index_modin\n pandas_df.columns = mi_index_pandas\n modin_it_default = modin_df.itertuples()\n pandas_it_default = pandas_df.itertuples()\n for modin_row, pandas_row in zip(modin_it_default, pandas_it_default):\n np.testing.assert_equal(modin_row, pandas_row)\n\n modin_it_custom = modin_df.itertuples(index=index, name=name)\n pandas_it_custom = pandas_df.itertuples(index=index, name=name)\n for modin_row, pandas_row in zip(modin_it_custom, pandas_it_custom):\n np.testing.assert_equal(modin_row, pandas_row)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___iter__(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n modin_iterator = modin_df.__iter__()\n\n # Check that modin_iterator implements the iterator interface\n assert hasattr(modin_iterator, \"__iter__\")\n assert hasattr(modin_iterator, \"next\") or hasattr(modin_iterator, \"__next__\")\n\n pd_iterator = pandas_df.__iter__()\n assert list(modin_iterator) == list(pd_iterator)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___contains__(self, request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n result = False\n key = \"Not Exist\"\n assert result == modin_df.__contains__(key)\n assert result == (key in modin_df)\n\n if \"empty_data\" not in request.node.name:\n result = True\n key = pandas_df.columns[0]\n assert result == modin_df.__contains__(key)\n assert result == (key in modin_df)\n\n def test__options_display(self):\n frame_data = random_state.randint(RAND_LOW, RAND_HIGH, size=(1000, 102))\n pandas_df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data)\n\n pandas.options.display.max_rows = 10\n pandas.options.display.max_columns = 10\n x = repr(pandas_df)\n pd.options.display.max_rows = 5\n pd.options.display.max_columns = 5\n y = repr(modin_df)\n assert x != y\n pd.options.display.max_rows = 10\n pd.options.display.max_columns = 10\n y = repr(modin_df)\n assert x == y\n\n # test for old fixed max values\n pandas.options.display.max_rows = 75\n pandas.options.display.max_columns = 75\n x = repr(pandas_df)\n pd.options.display.max_rows = 75\n pd.options.display.max_columns = 75\n y = repr(modin_df)\n assert x == y\n\n def test___finalize__(self):\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).__finalize__(None)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___copy__(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n modin_df_copy, pandas_df_copy = modin_df.__copy__(), pandas_df.__copy__()\n df_equals(modin_df_copy, pandas_df_copy)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test___deepcopy__(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n modin_df_copy, pandas_df_copy = (\n modin_df.__deepcopy__(),\n pandas_df.__deepcopy__(),\n )\n df_equals(modin_df_copy, pandas_df_copy)\n\n def test___repr__(self):\n frame_data = random_state.randint(RAND_LOW, RAND_HIGH, size=(1000, 100))\n pandas_df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data)\n assert repr(pandas_df) == repr(modin_df)\n\n frame_data = random_state.randint(RAND_LOW, RAND_HIGH, size=(1000, 99))\n pandas_df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data)\n assert repr(pandas_df) == repr(modin_df)\n\n frame_data = random_state.randint(RAND_LOW, RAND_HIGH, size=(1000, 101))\n pandas_df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data)\n assert repr(pandas_df) == repr(modin_df)\n\n frame_data = random_state.randint(RAND_LOW, RAND_HIGH, size=(1000, 102))\n pandas_df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data)\n assert repr(pandas_df) == repr(modin_df)\n\n # ___repr___ method has a different code path depending on\n # whether the number of rows is >60; and a different code path\n # depending on the number of columns is >20.\n # Previous test cases already check the case when cols>20\n # and rows>60. The cases that follow exercise the other three\n # combinations.\n # rows <= 60, cols > 20\n frame_data = random_state.randint(RAND_LOW, RAND_HIGH, size=(10, 100))\n pandas_df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data)\n\n assert repr(pandas_df) == repr(modin_df)\n\n # rows <= 60, cols <= 20\n frame_data = random_state.randint(RAND_LOW, RAND_HIGH, size=(10, 10))\n pandas_df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data)\n\n assert repr(pandas_df) == repr(modin_df)\n\n # rows > 60, cols <= 20\n frame_data = random_state.randint(RAND_LOW, RAND_HIGH, size=(100, 10))\n pandas_df = pandas.DataFrame(frame_data)\n modin_df = pd.DataFrame(frame_data)\n\n assert repr(pandas_df) == repr(modin_df)\n\n # Empty\n pandas_df = pandas.DataFrame(columns=[\"col{}\".format(i) for i in range(100)])\n modin_df = pd.DataFrame(columns=[\"col{}\".format(i) for i in range(100)])\n\n assert repr(pandas_df) == repr(modin_df)\n\n # From Issue #1705\n string_data = \"\"\"\"time\",\"device_id\",\"lat\",\"lng\",\"accuracy\",\"activity_1\",\"activity_1_conf\",\"activity_2\",\"activity_2_conf\",\"activity_3\",\"activity_3_conf\"\n\"2016-08-26 09:00:00.206\",2,60.186805,24.821049,33.6080017089844,\"STILL\",75,\"IN_VEHICLE\",5,\"ON_BICYCLE\",5\n\"2016-08-26 09:00:05.428\",5,60.192928,24.767222,5,\"WALKING\",62,\"ON_BICYCLE\",29,\"RUNNING\",6\n\"2016-08-26 09:00:05.818\",1,60.166382,24.700443,3,\"WALKING\",75,\"IN_VEHICLE\",5,\"ON_BICYCLE\",5\n\"2016-08-26 09:00:15.816\",1,60.166254,24.700671,3,\"WALKING\",75,\"IN_VEHICLE\",5,\"ON_BICYCLE\",5\n\"2016-08-26 09:00:16.413\",5,60.193055,24.767427,5,\"WALKING\",85,\"ON_BICYCLE\",15,\"UNKNOWN\",0\n\"2016-08-26 09:00:20.578\",3,60.152996,24.745216,3.90000009536743,\"STILL\",69,\"IN_VEHICLE\",31,\"UNKNOWN\",0\"\"\"\n pandas_df = pandas.read_csv(io.StringIO(string_data))\n modin_df = pd.read_csv(io.StringIO(string_data))\n assert repr(pandas_df) == repr(modin_df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_reset_index_with_multi_index(self, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if len(modin_df.columns) > len(pandas_df.columns):\n col0 = modin_df.columns[0]\n col1 = modin_df.columns[1]\n modin_cols = modin_df.groupby([col0, col1]).count().reset_index().columns\n pandas_cols = pandas_df.groupby([col0, col1]).count().reset_index().columns\n\n assert modin_cols.equals(pandas_cols)\n\n def test_reset_index_with_named_index(self):\n modin_df = pd.DataFrame(test_data_values[0])\n pandas_df = pandas.DataFrame(test_data_values[0])\n\n modin_df.index.name = pandas_df.index.name = \"NAME_OF_INDEX\"\n df_equals(modin_df, pandas_df)\n df_equals(modin_df.reset_index(drop=False), pandas_df.reset_index(drop=False))\n\n modin_df.reset_index(drop=True, inplace=True)\n pandas_df.reset_index(drop=True, inplace=True)\n df_equals(modin_df, pandas_df)\n\n modin_df = pd.DataFrame(test_data_values[0])\n pandas_df = pandas.DataFrame(test_data_values[0])\n modin_df.index.name = pandas_df.index.name = \"NEW_NAME\"\n df_equals(modin_df.reset_index(drop=False), pandas_df.reset_index(drop=False))\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_inplace_series_ops(self, data):\n pandas_df = pandas.DataFrame(data)\n modin_df = pd.DataFrame(data)\n\n if len(modin_df.columns) > len(pandas_df.columns):\n col0 = modin_df.columns[0]\n col1 = modin_df.columns[1]\n pandas_df[col1].dropna(inplace=True)\n modin_df[col1].dropna(inplace=True)\n df_equals(modin_df, pandas_df)\n\n pandas_df[col0].fillna(0, inplace=True)\n modin_df[col0].fillna(0, inplace=True)\n df_equals(modin_df, pandas_df)\n\n def test___setattr__(self,):\n pandas_df = pandas.DataFrame([1, 2, 3])\n modin_df = pd.DataFrame([1, 2, 3])\n\n pandas_df.new_col = [4, 5, 6]\n modin_df.new_col = [4, 5, 6]\n\n df_equals(modin_df, pandas_df)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_isin(self, data):\n pandas_df = pandas.DataFrame(data)\n modin_df = pd.DataFrame(data)\n\n val = [1, 2, 3, 4]\n pandas_result = pandas_df.isin(val)\n modin_result = modin_df.isin(val)\n\n df_equals(modin_result, pandas_result)\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_constructor(self, data):\n pandas_df = pandas.DataFrame(data)\n modin_df = pd.DataFrame(data)\n df_equals(pandas_df, modin_df)\n\n pandas_df = pandas.DataFrame({k: pandas.Series(v) for k, v in data.items()})\n modin_df = pd.DataFrame({k: pd.Series(v) for k, v in data.items()})\n df_equals(pandas_df, modin_df)\n\n @pytest.mark.parametrize(\n \"data\",\n [\n np.arange(1, 10000, dtype=np.float32),\n [\n pd.Series([1, 2, 3], dtype=\"int32\"),\n pandas.Series([4, 5, 6], dtype=\"int64\"),\n np.array([7, 8, 9], dtype=np.float32),\n ],\n pandas.Categorical([1, 2, 3, 4, 5]),\n ],\n )\n def test_constructor_dtypes(self, data):\n md_df, pd_df = create_test_dfs(data)\n df_equals(md_df, pd_df)\n\n def test_constructor_columns_and_index(self):\n modin_df = pd.DataFrame(\n [[1, 1, 10], [2, 4, 20], [3, 7, 30]],\n index=[1, 2, 3],\n columns=[\"id\", \"max_speed\", \"health\"],\n )\n pandas_df = pandas.DataFrame(\n [[1, 1, 10], [2, 4, 20], [3, 7, 30]],\n index=[1, 2, 3],\n columns=[\"id\", \"max_speed\", \"health\"],\n )\n df_equals(modin_df, pandas_df)\n df_equals(pd.DataFrame(modin_df), pandas.DataFrame(pandas_df))\n df_equals(\n pd.DataFrame(modin_df, columns=[\"max_speed\", \"health\"]),\n pandas.DataFrame(pandas_df, columns=[\"max_speed\", \"health\"]),\n )\n df_equals(\n pd.DataFrame(modin_df, index=[1, 2]),\n pandas.DataFrame(pandas_df, index=[1, 2]),\n )\n df_equals(\n pd.DataFrame(modin_df, index=[1, 2], columns=[\"health\"]),\n pandas.DataFrame(pandas_df, index=[1, 2], columns=[\"health\"]),\n )\n df_equals(\n pd.DataFrame(modin_df.iloc[:, 0], index=[1, 2, 3]),\n pandas.DataFrame(pandas_df.iloc[:, 0], index=[1, 2, 3]),\n )\n df_equals(\n pd.DataFrame(modin_df.iloc[:, 0], columns=[\"NO_EXIST\"]),\n pandas.DataFrame(pandas_df.iloc[:, 0], columns=[\"NO_EXIST\"]),\n )\n with pytest.raises(NotImplementedError):\n pd.DataFrame(modin_df, index=[1, 2, 99999])\n with pytest.raises(NotImplementedError):\n pd.DataFrame(modin_df, columns=[\"NO_EXIST\"])\n\n\nclass TestDataFrameJoinSort:\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n def test_combine(self, data):\n pandas_df = pandas.DataFrame(data)\n modin_df = pd.DataFrame(data)\n\n modin_df.combine(\n modin_df + 1, lambda s1, s2: s1 if s1.count() < s2.count() else s2\n )\n pandas_df.combine(\n pandas_df + 1, lambda s1, s2: s1 if s1.count() < s2.count() else s2\n )\n\n def test_join(self):\n frame_data = {\n \"col1\": [0, 1, 2, 3],\n \"col2\": [4, 5, 6, 7],\n \"col3\": [8, 9, 0, 1],\n \"col4\": [2, 4, 5, 6],\n }\n\n modin_df = pd.DataFrame(frame_data)\n pandas_df = pandas.DataFrame(frame_data)\n\n frame_data2 = {\"col5\": [0], \"col6\": [1]}\n modin_df2 = pd.DataFrame(frame_data2)\n pandas_df2 = pandas.DataFrame(frame_data2)\n\n join_types = [\"left\", \"right\", \"outer\", \"inner\"]\n for how in join_types:\n modin_join = modin_df.join(modin_df2, how=how)\n pandas_join = pandas_df.join(pandas_df2, how=how)\n df_equals(modin_join, pandas_join)\n\n frame_data3 = {\"col7\": [1, 2, 3, 5, 6, 7, 8]}\n\n modin_df3 = pd.DataFrame(frame_data3)\n pandas_df3 = pandas.DataFrame(frame_data3)\n\n join_types = [\"left\", \"outer\", \"inner\"]\n for how in join_types:\n modin_join = modin_df.join([modin_df2, modin_df3], how=how)\n pandas_join = pandas_df.join([pandas_df2, pandas_df3], how=how)\n df_equals(modin_join, pandas_join)\n\n @pytest.mark.parametrize(\n \"test_data, test_data2\",\n [\n (\n np.random.uniform(0, 100, size=(2 ** 6, 2 ** 6)),\n np.random.uniform(0, 100, size=(2 ** 7, 2 ** 6)),\n ),\n (\n np.random.uniform(0, 100, size=(2 ** 7, 2 ** 6)),\n np.random.uniform(0, 100, size=(2 ** 6, 2 ** 6)),\n ),\n (\n np.random.uniform(0, 100, size=(2 ** 6, 2 ** 6)),\n np.random.uniform(0, 100, size=(2 ** 6, 2 ** 7)),\n ),\n (\n np.random.uniform(0, 100, size=(2 ** 6, 2 ** 7)),\n np.random.uniform(0, 100, size=(2 ** 6, 2 ** 6)),\n ),\n ],\n )\n def test_merge(self, test_data, test_data2):\n modin_df = pd.DataFrame(\n test_data,\n columns=[\"col{}\".format(i) for i in range(test_data.shape[1])],\n index=pd.Index([i for i in range(1, test_data.shape[0] + 1)], name=\"key\"),\n )\n pandas_df = pandas.DataFrame(\n test_data,\n columns=[\"col{}\".format(i) for i in range(test_data.shape[1])],\n index=pandas.Index(\n [i for i in range(1, test_data.shape[0] + 1)], name=\"key\"\n ),\n )\n modin_df2 = pd.DataFrame(\n test_data2,\n columns=[\"col{}\".format(i) for i in range(test_data2.shape[1])],\n index=pd.Index([i for i in range(1, test_data2.shape[0] + 1)], name=\"key\"),\n )\n pandas_df2 = pandas.DataFrame(\n test_data2,\n columns=[\"col{}\".format(i) for i in range(test_data2.shape[1])],\n index=pandas.Index(\n [i for i in range(1, test_data2.shape[0] + 1)], name=\"key\"\n ),\n )\n\n hows = [\"left\", \"inner\"]\n ons = [\"col33\", [\"col33\", \"col34\"]]\n sorts = [False, True]\n for i in range(2):\n for j in range(2):\n modin_result = modin_df.merge(\n modin_df2, how=hows[i], on=ons[j], sort=sorts[j]\n )\n pandas_result = pandas_df.merge(\n pandas_df2, how=hows[i], on=ons[j], sort=sorts[j]\n )\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.merge(\n modin_df2,\n how=hows[i],\n left_on=\"key\",\n right_on=\"key\",\n sort=sorts[j],\n )\n pandas_result = pandas_df.merge(\n pandas_df2,\n how=hows[i],\n left_on=\"key\",\n right_on=\"key\",\n sort=sorts[j],\n )\n df_equals(modin_result, pandas_result)\n\n # Test for issue #1771\n modin_df = pd.DataFrame({\"name\": np.arange(40)})\n modin_df2 = pd.DataFrame({\"name\": [39], \"position\": [0]})\n pandas_df = pandas.DataFrame({\"name\": np.arange(40)})\n pandas_df2 = pandas.DataFrame({\"name\": [39], \"position\": [0]})\n modin_result = modin_df.merge(modin_df2, on=\"name\", how=\"inner\")\n pandas_result = pandas_df.merge(pandas_df2, on=\"name\", how=\"inner\")\n df_equals(modin_result, pandas_result)\n\n frame_data = {\n \"col1\": [0, 1, 2, 3],\n \"col2\": [4, 5, 6, 7],\n \"col3\": [8, 9, 0, 1],\n \"col4\": [2, 4, 5, 6],\n }\n\n modin_df = pd.DataFrame(frame_data)\n pandas_df = pandas.DataFrame(frame_data)\n\n frame_data2 = {\"col1\": [0, 1, 2], \"col2\": [1, 5, 6]}\n modin_df2 = pd.DataFrame(frame_data2)\n pandas_df2 = pandas.DataFrame(frame_data2)\n\n join_types = [\"outer\", \"inner\"]\n for how in join_types:\n # Defaults\n modin_result = modin_df.merge(modin_df2, how=how)\n pandas_result = pandas_df.merge(pandas_df2, how=how)\n df_equals(modin_result, pandas_result)\n\n # left_on and right_index\n modin_result = modin_df.merge(\n modin_df2, how=how, left_on=\"col1\", right_index=True\n )\n pandas_result = pandas_df.merge(\n pandas_df2, how=how, left_on=\"col1\", right_index=True\n )\n df_equals(modin_result, pandas_result)\n\n # left_index and right_on\n modin_result = modin_df.merge(\n modin_df2, how=how, left_index=True, right_on=\"col1\"\n )\n pandas_result = pandas_df.merge(\n pandas_df2, how=how, left_index=True, right_on=\"col1\"\n )\n df_equals(modin_result, pandas_result)\n\n # left_on and right_on col1\n modin_result = modin_df.merge(\n modin_df2, how=how, left_on=\"col1\", right_on=\"col1\"\n )\n pandas_result = pandas_df.merge(\n pandas_df2, how=how, left_on=\"col1\", right_on=\"col1\"\n )\n df_equals(modin_result, pandas_result)\n\n # left_on and right_on col2\n modin_result = modin_df.merge(\n modin_df2, how=how, left_on=\"col2\", right_on=\"col2\"\n )\n pandas_result = pandas_df.merge(\n pandas_df2, how=how, left_on=\"col2\", right_on=\"col2\"\n )\n df_equals(modin_result, pandas_result)\n\n # left_index and right_index\n modin_result = modin_df.merge(\n modin_df2, how=how, left_index=True, right_index=True\n )\n pandas_result = pandas_df.merge(\n pandas_df2, how=how, left_index=True, right_index=True\n )\n df_equals(modin_result, pandas_result)\n\n # Named Series promoted to DF\n s = pd.Series(frame_data2.get(\"col1\"))\n with pytest.raises(ValueError):\n modin_df.merge(s)\n\n s = pd.Series(frame_data2.get(\"col1\"), name=\"col1\")\n df_equals(modin_df.merge(s), modin_df.merge(modin_df2[[\"col1\"]]))\n\n with pytest.raises(TypeError):\n modin_df.merge(\"Non-valid type\")\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"ascending\", bool_arg_values, ids=arg_keys(\"ascending\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\"na_position\", [\"first\", \"last\"], ids=[\"first\", \"last\"])\n @pytest.mark.parametrize(\n \"sort_remaining\", bool_arg_values, ids=arg_keys(\"sort_remaining\", bool_arg_keys)\n )\n def test_sort_index(self, data, axis, ascending, na_position, sort_remaining):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n # Change index value so sorting will actually make a difference\n if axis == \"rows\" or axis == 0:\n length = len(modin_df.index)\n modin_df.index = [(i - length / 2) % length for i in range(length)]\n pandas_df.index = [(i - length / 2) % length for i in range(length)]\n # Add NaNs to sorted index\n if axis == \"rows\" or axis == 0:\n length = len(modin_df.index)\n modin_df.index = [\n np.nan if i % 2 == 0 else modin_df.index[i] for i in range(length)\n ]\n pandas_df.index = [\n np.nan if i % 2 == 0 else pandas_df.index[i] for i in range(length)\n ]\n else:\n length = len(modin_df.columns)\n modin_df.columns = [\n np.nan if i % 2 == 0 else modin_df.columns[i] for i in range(length)\n ]\n pandas_df.columns = [\n np.nan if i % 2 == 0 else pandas_df.columns[i] for i in range(length)\n ]\n\n modin_result = modin_df.sort_index(\n axis=axis, ascending=ascending, na_position=na_position, inplace=False\n )\n pandas_result = pandas_df.sort_index(\n axis=axis, ascending=ascending, na_position=na_position, inplace=False\n )\n df_equals(modin_result, pandas_result)\n\n modin_df_cp = modin_df.copy()\n pandas_df_cp = pandas_df.copy()\n modin_df_cp.sort_index(\n axis=axis, ascending=ascending, na_position=na_position, inplace=True\n )\n pandas_df_cp.sort_index(\n axis=axis, ascending=ascending, na_position=na_position, inplace=True\n )\n df_equals(modin_df_cp, pandas_df_cp)\n\n # MultiIndex\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n modin_df.index = pd.MultiIndex.from_tuples(\n [(i // 10, i // 5, i) for i in range(len(modin_df))]\n )\n pandas_df.index = pandas.MultiIndex.from_tuples(\n [(i // 10, i // 5, i) for i in range(len(pandas_df))]\n )\n\n with pytest.warns(UserWarning):\n df_equals(modin_df.sort_index(level=0), pandas_df.sort_index(level=0))\n with pytest.warns(UserWarning):\n df_equals(modin_df.sort_index(axis=0), pandas_df.sort_index(axis=0))\n\n @pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\n @pytest.mark.parametrize(\"axis\", axis_values, ids=axis_keys)\n @pytest.mark.parametrize(\n \"ascending\", bool_arg_values, ids=arg_keys(\"ascending\", bool_arg_keys)\n )\n @pytest.mark.parametrize(\"na_position\", [\"first\", \"last\"], ids=[\"first\", \"last\"])\n def test_sort_values(self, request, data, axis, ascending, na_position):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if \"empty_data\" not in request.node.name and (\n (axis == 0 or axis == \"over rows\")\n or name_contains(request.node.name, numeric_dfs)\n ):\n index = (\n modin_df.index if axis == 1 or axis == \"columns\" else modin_df.columns\n )\n key = index[0]\n modin_result = modin_df.sort_values(\n key,\n axis=axis,\n ascending=ascending,\n na_position=na_position,\n inplace=False,\n )\n pandas_result = pandas_df.sort_values(\n key,\n axis=axis,\n ascending=ascending,\n na_position=na_position,\n inplace=False,\n )\n df_equals(modin_result, pandas_result)\n\n modin_df_cp = modin_df.copy()\n pandas_df_cp = pandas_df.copy()\n modin_df_cp.sort_values(\n key,\n axis=axis,\n ascending=ascending,\n na_position=na_position,\n inplace=True,\n )\n pandas_df_cp.sort_values(\n key,\n axis=axis,\n ascending=ascending,\n na_position=na_position,\n inplace=True,\n )\n df_equals(modin_df_cp, pandas_df_cp)\n\n keys = [key, index[-1]]\n modin_result = modin_df.sort_values(\n keys,\n axis=axis,\n ascending=ascending,\n na_position=na_position,\n inplace=False,\n )\n pandas_result = pandas_df.sort_values(\n keys,\n axis=axis,\n ascending=ascending,\n na_position=na_position,\n inplace=False,\n )\n df_equals(modin_result, pandas_result)\n\n modin_df_cp = modin_df.copy()\n pandas_df_cp = pandas_df.copy()\n modin_df_cp.sort_values(\n keys,\n axis=axis,\n ascending=ascending,\n na_position=na_position,\n inplace=True,\n )\n pandas_df_cp.sort_values(\n keys,\n axis=axis,\n ascending=ascending,\n na_position=na_position,\n inplace=True,\n )\n df_equals(modin_df_cp, pandas_df_cp)\n\n def test_sort_values_with_duplicates(self):\n modin_df = pd.DataFrame({\"col\": [2, 1, 1]}, index=[1, 1, 0])\n pandas_df = pandas.DataFrame({\"col\": [2, 1, 1]}, index=[1, 1, 0])\n\n key = modin_df.columns[0]\n modin_result = modin_df.sort_values(key, inplace=False)\n pandas_result = pandas_df.sort_values(key, inplace=False)\n df_equals(modin_result, pandas_result)\n\n modin_df.sort_values(key, inplace=True)\n pandas_df.sort_values(key, inplace=True)\n df_equals(modin_df, pandas_df)\n\n def test_sort_values_with_string_index(self):\n modin_df = pd.DataFrame({\"col\": [25, 17, 1]}, index=[\"ccc\", \"bbb\", \"aaa\"])\n pandas_df = pandas.DataFrame({\"col\": [25, 17, 1]}, index=[\"ccc\", \"bbb\", \"aaa\"])\n\n key = modin_df.columns[0]\n modin_result = modin_df.sort_values(key, inplace=False)\n pandas_result = pandas_df.sort_values(key, inplace=False)\n df_equals(modin_result, pandas_result)\n\n modin_df.sort_values(key, inplace=True)\n pandas_df.sort_values(key, inplace=True)\n df_equals(modin_df, pandas_df)\n\n def test_where(self):\n frame_data = random_state.randn(100, 10)\n pandas_df = pandas.DataFrame(frame_data, columns=list(\"abcdefghij\"))\n modin_df = pd.DataFrame(frame_data, columns=list(\"abcdefghij\"))\n pandas_cond_df = pandas_df % 5 < 2\n modin_cond_df = modin_df % 5 < 2\n\n pandas_result = pandas_df.where(pandas_cond_df, -pandas_df)\n modin_result = modin_df.where(modin_cond_df, -modin_df)\n assert all((to_pandas(modin_result) == pandas_result).all())\n\n other = pandas_df.loc[3]\n pandas_result = pandas_df.where(pandas_cond_df, other, axis=1)\n modin_result = modin_df.where(modin_cond_df, other, axis=1)\n assert all((to_pandas(modin_result) == pandas_result).all())\n\n other = pandas_df[\"e\"]\n pandas_result = pandas_df.where(pandas_cond_df, other, axis=0)\n modin_result = modin_df.where(modin_cond_df, other, axis=0)\n assert all((to_pandas(modin_result) == pandas_result).all())\n\n pandas_result = pandas_df.where(pandas_df < 2, True)\n modin_result = modin_df.where(modin_df < 2, True)\n assert all((to_pandas(modin_result) == pandas_result).all())\n" ]
[ [ "pandas.core.dtypes.common.is_list_like", "pandas.Series", "pandas.MultiIndex.from_tuples", "pandas.DataFrame", "numpy.all" ], [ "pandas.read_excel", "pandas.read_clipboard", "pandas.DataFrame", "pandas.read_html", "pandas.read_parquet", "numpy.random.randn", "pandas.ExcelWriter", "numpy.random.randint", "pandas.read_csv", "numpy.arange", "pandas.to_pickle", "pandas.read_stata", "pandas.read_sql", "pandas.read_hdf", "pandas.read_fwf", "pandas.read_table", "pandas.read_sas", "pandas.read_json", "pandas.date_range", "pandas.HDFStore", "pandas.ExcelFile", "pandas.read_feather", "pandas.read_pickle" ], [ "pandas.Series", "pandas.MultiIndex.from_tuples", "pandas.DataFrame", "pandas.util.testing.assert_index_equal", "numpy.random.randint", "numpy.testing.assert_equal", "pandas.read_csv", "pandas.Timestamp", "numpy.arange", "pandas.Index", "pandas.concat", "numpy.random.choice", "pandas.Categorical", "pandas.util.testing.getSeriesData", "pandas.date_range", "numpy.random.RandomState", "numpy.array", "numpy.array_equal", "matplotlib.use", "numpy.testing.assert_array_equal", "numpy.random.uniform", "pandas.offsets.Hour", "pandas.get_dummies" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.24" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
michaelJwilson/legacypipe
[ "47d005356cbd0c9fb864c960ee7bbf800e543cad", "47d005356cbd0c9fb864c960ee7bbf800e543cad" ]
[ "py/legacypipe/forced_photom_merge.py", "py/test/rex.py" ]
[ "'''\nAfter running forced_photom.py on a set of CCDs, this script merges\nthe results back into a catalog.\n'''\nfrom astrometry.util.fits import *\nimport numpy as np\nfrom glob import glob\nfrom collections import Counter\n\nfrom legacypipe.survey import LegacySurveyData\n\nfns = glob('forced/*/*/forced-*.fits')\nF = merge_tables([fits_table(fn) for fn in fns])\n\ndr6 = LegacySurveyData('/project/projectdirs/cosmo/data/legacysurvey/dr6')\nB = dr6.get_bricks_readonly()\n\nI = np.flatnonzero((B.ra1 < F.ra.max()) * (B.ra2 > F.ra.min()) * (B.dec1 < F.dec.max()) * (B.dec2 > F.dec.min()))\nprint(len(I), 'bricks')\nT = merge_tables([fits_table(dr6.find_file('tractor', brick=B.brickname[i])) for i in I])\nprint(len(T), 'sources')\nT.cut(T.brick_primary)\nprint(len(T), 'primary')\n\n# map from F to T index\nimap = dict([((b,o),i) for i,(b,o) in enumerate(zip(T.brickid, T.objid))])\nF.tindex = np.array([imap[(b,o)] for b,o in zip(F.brickid, F.objid)])\nassert(np.all(T.brickid[F.tindex] == F.brickid))\nassert(np.all(T.objid[F.tindex] == F.objid))\n\nfcols = 'apflux apflux_ivar camera expnum ccdname exptime flux flux_ivar fracflux mask mjd rchi2 x y brickid objid'.split()\n\nbands = np.unique(F.filter)\nfor band in bands:\n Fb = F[F.filter == band]\n print(len(Fb), 'in band', band)\n c = Counter(zip(Fb.brickid, Fb.objid))\n NB = c.most_common()[0][1]\n print('Maximum of', NB, 'exposures per object')\n\n # we use uint8 below...\n assert(NB < 256)\n \n sourcearrays = []\n sourcearrays2 = []\n destarrays = []\n destarrays2 = []\n for c in fcols:\n src = Fb.get(c)\n if len(src.shape) == 2:\n narray = src.shape[1]\n dest = np.zeros((len(T), Nb, narray), src.dtype)\n T.set('forced_%s_%s' % (band, c), dest)\n sourcearrays2.append(src)\n destarrays2.append(dest)\n else:\n dest = np.zeros((len(T), Nb), src.dtype)\n T.set('forced_%s_%s' % (band, c), dest)\n sourcearrays.append(src)\n destarrays.append(dest)\n nf = np.zeros(len(T), np.uint8)\n T.set('forced_%s_n' % band, nf)\n for i,ti in enumerate(Fb.tindex):\n k = nf[ti]\n for src,dest in zip(sourcearrays, destarrays):\n dest[ti,k] = src[i]\n for src,dest in zip(sourcearrays2, destarrays2):\n dest[ti,k,:] = src[i,:]\n nf[ti] += 1\n\nfor band in bands:\n flux = T.get('forced_%s_flux' % band)\n ivar = T.get('forced_%s_flux_ivar' % band)\n miv = np.sum(ivar, axis=1)\n T.set('forced_%s_mean_flux' % band, np.sum(flux * ivar, axis=1) / np.maximum(1e-16, miv))\n T.set('forced_%s_mean_flux_ivar' % band, miv)\n\n#K = np.flatnonzero(np.logical_or(T.forced_mean_u_flux_ivar > 0, T.forced_mean_r_flux_ivar > 0))\n#T[K].writeto('forced/forced-cfis-deep2f2.fits')\n\nT.writeto('forced-merged.fits')\n\n", "from __future__ import print_function\nfrom __future__ import division\nfrom tractor import *\nfrom legacypipe.survey import RexGalaxy, LogRadius\nimport pylab as plt\nimport numpy as np\nfrom astrometry.util.plotutils import *\n\nps = PlotSequence('rex')\n#h,w = 100,100\n#h,w = 50,50\nh,w = 25,25\n\n#import tractor.galaxy\n#tractor.galaxy.debug_ps = PlotSequence('gal')\n\npsfh,psfw = 29,29\n#psf_sigma = 2.35\npsf_sigma = 3.\n#psfh,psfw = 31,31\nxx,yy = np.meshgrid(np.arange(psfw), np.arange(psfh))\npsfimg = np.exp((-0.5 * ((xx-psfw//2)**2 + (yy-psfh//2)**2) / psf_sigma**2))\npsfimg /= np.sum(psfimg)\n\nrow = psfimg[0,:]\nprint('Bottom row of PSF img: absmax', row[np.argmax(np.abs(row))], row)\n\npixpsf = PixelizedPSF(psfimg)\npsf = HybridPixelizedPSF(pixpsf)\n\ntim = Image(data=np.zeros((h,w)), invvar=np.ones((h,w)), psf=psf)\n\npos = PixPos(h//2, w//2)\nflux = 100.\nbright = Flux(flux)\nrex = RexGalaxy(pos, bright, LogRadius(0.))\npsf = PointSource(pos, bright)\n\ntractor = Tractor([tim], [rex])\ncat = tractor.getCatalog()\n\nmask = ModelMask(0, 0, w, h)\nmm = [{rex:mask, psf:mask}]\ntractor.setModelMasks(mm)\n\n\nplt.clf()\nrow = psfimg[:,psfw//2] * flux\nrow = np.hstack((row, np.zeros(5)))\nplt.plot(row, 'k.-')\n\nfrom astrometry.util.miscutils import lanczos_filter\nfrom scipy.ndimage.filters import correlate1d\nfor mux in [0.1, 0.25, 0.5]:\n L = 3\n Lx = lanczos_filter(L, np.arange(-L, L+1) + mux)\n Lx /= Lx.sum()\n cx = correlate1d(row, Lx, mode='constant')\n plt.plot(cx, '.-')\nplt.yscale('symlog', linthreshy=1e-10)\nps.savefig()\n\nfor re in [10., 1, 1e-1, 1e-2, 1e-3, 1e-4, 1e-6, 1e-10]:\n#for re in [2e-3, 1.05e-3, 1e-3, 0.95e-3, 5e-4]:\n#for re in np.linspace(0.9e-3, 1.1e-3, 25):\n rex.pos.x = psf.pos.x = 12.\n rex.pos.y = psf.pos.y = 16.\n rex.shape.logre = np.log(re)\n print('Rex:', rex)\n cat[0] = rex\n rexmod = tractor.getModelImage(0)\n cat[0] = psf\n psfmod = tractor.getModelImage(0)\n\n rex.pos.x = psf.pos.x = 12.5\n rex.pos.y = psf.pos.y = 15.75\n\n cat[0] = rex\n rexmod2 = tractor.getModelImage(0)\n cat[0] = psf\n psfmod2 = tractor.getModelImage(0)\n\n mx = psfmod.max()\n dmx = np.abs(rexmod - psfmod).max()\n\n dmx2 = np.abs(rexmod2 - psfmod2).max()\n\n doff = max(dmx, dmx2)\n \n plt.clf()\n #ima = dict(vmin=-0.1*mx, vmax=mx, ticks=False)\n ima = dict(vmin=-6+np.log10(mx), vmax=np.log10(mx), ticks=False)\n plt.subplot(2,3,1)\n #dimshow(rexmod, **ima)\n dimshow(np.log10(rexmod + doff), **ima)\n plt.title('REX (centered)')\n plt.subplot(2,3,2)\n #dimshow(psfmod, **ima)\n dimshow(np.log10(psfmod + doff), **ima)\n plt.title('PSF (centered)')\n plt.subplot(2,3,3)\n dimshow(rexmod - psfmod, vmin=-dmx, vmax=dmx, cmap='RdBu', ticks=False)\n plt.title('diff: %.3g' % dmx)\n\n row = rexmod2[2,:]\n print('REX (shifted) 3rd-bottom:', row[np.argmax(np.abs(row))], row)\n row = psfmod2[2,:]\n print('PSF (shifted) 3rd-bottom:', row[np.argmax(np.abs(row))], row)\n \n row = rexmod2[1,:]\n print('REX (shifted) 2nd-bottom:', row[np.argmax(np.abs(row))], row)\n row = psfmod2[1,:]\n print('PSF (shifted) 2nd-bottom:', row[np.argmax(np.abs(row))], row)\n\n row = rexmod2[0,:]\n print('REX (shifted) bottom:', row[np.argmax(np.abs(row))], row)\n row = psfmod2[0,:]\n print('PSF (shifted) bottom:', row[np.argmax(np.abs(row))], row)\n\n plt.subplot(2,3,4)\n #dimshow(rexmod2, **ima)\n dimshow(np.log10(rexmod2 + doff), **ima)\n plt.title('REX (shifted)')\n plt.subplot(2,3,5)\n #dimshow(psfmod2, **ima)\n dimshow(np.log10(psfmod2 + doff), **ima)\n plt.title('PSF (shifted)')\n plt.subplot(2,3,6)\n dimshow(rexmod2 - psfmod2, vmin=-dmx, vmax=dmx, cmap='RdBu', ticks=False)\n plt.title('diff: %.3g' % dmx2)\n\n plt.suptitle('R_e = %g' % re)\n ps.savefig()\n\n print('Centered diff:', dmx, 'vs shifted diff:', dmx2)\n" ]
[ [ "numpy.all", "numpy.maximum", "numpy.sum", "numpy.unique" ], [ "numpy.log", "numpy.abs", "numpy.arange", "numpy.ones", "numpy.log10", "scipy.ndimage.filters.correlate1d", "numpy.exp", "numpy.zeros", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "0.15", "1.4", "0.16", "1.0", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "0.10", "0.17", "1.3" ], "tensorflow": [] } ]
Novakasa/pybricks-micropython
[ "4cb036fdcdcf1240576efae772375a6b37e8a7ba" ]
[ "tests/motors/run_test.py" ]
[ "#!/usr/bin/env python\n\nimport argparse\nimport asyncio\nimport csv\nimport datetime\nimport matplotlib\nimport matplotlib.pyplot\nimport numpy\nimport os\nimport pathlib\nimport shutil\nimport subprocess\n\nfrom pybricksdev.connections.pybricks import PybricksHub\nfrom pybricksdev.connections.lego import REPLHub\n\nfrom pybricksdev.ble import find_device\n\n\nasync def run_pybricks_script(script_name):\n \"\"\"Runs a script on a hub with Pybricks firmware and awaits result.\"\"\"\n\n # Connect to the hub.\n print(\"Searching for a hub.\")\n hub = PybricksHub()\n address = await find_device()\n await hub.connect(address)\n print(\"Connected!\")\n\n # Run the script and disconnect.\n await hub.run(script_name)\n await hub.disconnect()\n\n return hub.output\n\n\nasync def run_usb_repl_script(script_name):\n \"\"\"Runs a script on a generic MicroPython REPL and awaits result.\"\"\"\n\n # Connect to the hub.\n print(\"Searching for a hub via USB.\")\n hub = REPLHub()\n await hub.connect()\n await hub.reset_hub()\n print(\"Entered REPL Mode.\")\n\n # Run the script and disconnect.\n await hub.run(script_name)\n await hub.disconnect()\n return hub.output\n\n\ndef get_data(path):\n \"\"\"Gets data columns from a comma separated file.\"\"\"\n with open(path) as f:\n reader = csv.reader(f, delimiter=\",\")\n data = numpy.array([[int(x) for x in rec] for rec in reader])\n time = data[:, 0]\n return time, data\n\n\ndef gradient(data, time, smooth=8):\n \"\"\"Computes a simple gradient from sampled data.\"\"\"\n speed = []\n for i, t in enumerate(time):\n start = max(i - smooth, 0)\n end = min(i + smooth, len(time) - 1)\n speed.append((data[end] - data[start]) / (time[end] - time[start]))\n return numpy.array(speed)\n\n\ndef plot_servo_data(time, data, build_dir, subtitle=None):\n \"\"\"Plots data for a servo motor.\"\"\"\n # Get loop time.\n wall_time = data[:, 1]\n wall_time_shifted = numpy.append(2 * wall_time[0] - wall_time[1], wall_time[0:-1])\n loop_time = wall_time - wall_time_shifted\n\n # Read state columns.\n count = data[:, 2]\n rate = data[:, 3]\n voltage = data[:, 5]\n count_est = data[:, 6]\n rate_est = data[:, 7]\n torque_feedback = data[:, 8]\n torque_feedforward = data[:, 9]\n\n title = \"servo\" if subtitle is None else \"servo_\" + subtitle\n\n figure, axes = matplotlib.pyplot.subplots(nrows=5, ncols=1, figsize=(15, 15))\n figure.suptitle(title, fontsize=20)\n\n position_axis, speed_axis, torque_axis, duty_axis, time_axis = axes\n\n position_axis.plot(time, count, drawstyle=\"steps-post\", label=\"Reported count\")\n position_axis.plot(time, count_est, drawstyle=\"steps-post\", label=\"Observer\")\n position_axis.set_ylabel(\"angle (deg)\")\n\n speed_axis.plot(time, rate, drawstyle=\"steps-post\", label=\"Reported rate\")\n speed_axis.plot(time, rate_est, drawstyle=\"steps-post\", label=\"Observer\")\n speed_axis.plot(\n time, gradient(count, time / 1000), drawstyle=\"steps-post\", label=\"Future count derivative\"\n )\n speed_axis.set_ylabel(\"speed (deg/s)\")\n\n torque_axis.plot(time, torque_feedback, label=\"Feedback\", drawstyle=\"steps-post\")\n torque_axis.plot(time, torque_feedforward, label=\"Feedforward\", drawstyle=\"steps-post\")\n torque_axis.set_ylabel(\"Torque\")\n\n duty_axis.plot(time, voltage, label=\"Voltage\", drawstyle=\"steps-post\")\n duty_axis.set_ylabel(\"Motor voltage (mV)\")\n duty_axis.set_ylim([-10000, 10000])\n\n time_axis.plot(time, loop_time, label=\"Loop time\", drawstyle=\"steps-post\")\n time_axis.set_ylabel(\"Time (us)\")\n time_axis.set_xlabel(\"time (ms)\")\n\n for axis in axes:\n axis.grid(True)\n axis.set_xlim([time[0], time[-1]])\n axis.legend()\n\n figure.savefig(build_dir / (title + \".png\"))\n\n\ndef plot_control_data(time, data, build_dir, subtitle=None):\n \"\"\"Plots data for the controller.\"\"\"\n maneuver_time = data[:, 1]\n count = data[:, 2]\n rate = data[:, 3]\n actuation_type = data[:, 4]\n torque_total = data[:, 5]\n count_ref = data[:, 6]\n rate_ref = data[:, 7]\n count_est = data[:, 8]\n rate_est = data[:, 9]\n torque_p = data[:, 10]\n torque_i = data[:, 11]\n torque_d = data[:, 12]\n\n title = \"control\" if subtitle is None else \"control_\" + subtitle\n\n figure, axes = matplotlib.pyplot.subplots(nrows=5, ncols=1, figsize=(15, 15))\n figure.suptitle(title, fontsize=20)\n\n position_axis, error_axis, speed_axis, torque_axis, time_axis = axes\n\n position_axis.plot(time, count, drawstyle=\"steps-post\", label=\"Reported count\")\n position_axis.plot(time, count_est, drawstyle=\"steps-post\", label=\"Observer\")\n position_axis.plot(time, count_ref, drawstyle=\"steps-post\", label=\"Reference\")\n position_axis.set_ylabel(\"angle (deg)\")\n\n error_axis.plot(time, count_ref - count, drawstyle=\"steps-post\", label=\"Reported error\")\n error_axis.plot(time, count_ref - count_est, drawstyle=\"steps-post\", label=\"Estimated error\")\n error_axis.plot(time, count_est - count, drawstyle=\"steps-post\", label=\"Estimation error\")\n error_axis.set_ylabel(\"angle error (deg)\")\n\n speed_axis.plot(time, rate, drawstyle=\"steps-post\", label=\"Reported rate\")\n speed_axis.plot(time, rate_est, drawstyle=\"steps-post\", label=\"Observer\")\n speed_axis.plot(\n time, gradient(count, time / 1000), drawstyle=\"steps-post\", label=\"Future count derivative\"\n )\n speed_axis.plot(time, rate_ref, drawstyle=\"steps-post\", label=\"Reference\")\n speed_axis.set_ylabel(\"speed (deg/s)\")\n\n torque_axis.plot(time, torque_p, label=\"P\", drawstyle=\"steps-post\")\n torque_axis.plot(time, torque_i, label=\"I\", drawstyle=\"steps-post\")\n torque_axis.plot(time, torque_d, label=\"D\", drawstyle=\"steps-post\")\n torque_axis.plot(time, torque_total, label=\"Total\", drawstyle=\"steps-post\")\n torque_axis.set_ylabel(\"torque\")\n\n time_axis.plot(time, maneuver_time / 1000, label=\"t - t_0\", drawstyle=\"steps-post\")\n time_axis.set_ylabel(\"Maneuver time (ms)\")\n time_axis.set_xlabel(\"time (ms)\")\n\n for axis in axes:\n axis.grid(True)\n axis.set_xlim([time[0], time[-1]])\n axis.legend()\n\n figure.savefig(build_dir / (title + \".png\"))\n\n\n# Parse user argument.\nparser = argparse.ArgumentParser(description=\"Run motor script and show log.\")\nparser.add_argument(\"file\", help=\"Script to run\")\nparser.add_argument(\"--show\", dest=\"show\", default=False, action=\"store_true\")\nparser.add_argument(\n \"--target\",\n dest=\"target\",\n help=\"target type: %(choices)s\",\n choices=[\"ble\", \"usb\", \"virtual\"],\n default=\"ble\",\n)\nargs = parser.parse_args()\n\n# Local paths and data directories.\ntime_string = datetime.datetime.now().strftime(\"-%Y-%m-%d-%H%M-%S\")\nscript_base_name, _ = os.path.splitext(os.path.split(args.file)[-1])\ntest_dir = pathlib.Path(__file__).parent\nbuild_dir = test_dir / \"build\" / (script_base_name + time_string)\npathlib.Path(build_dir).mkdir(parents=True, exist_ok=True)\n\n# Copy script to data directory to archive experiment.\nscript_archive = build_dir / (script_base_name + \".py\")\nshutil.copyfile(args.file, script_archive)\n\n# Configure matplotlib.\nmatplotlib.use(\"TkAgg\")\nmatplotlib.interactive(True)\n\n# Run the script on physical or virtual platform.\nif args.target == \"usb\":\n hub_output = asyncio.run(run_usb_repl_script(script_archive))\nelif args.target == \"ble\":\n hub_output = asyncio.run(run_pybricks_script(script_archive))\nelse:\n top_path = (test_dir / \"../..\").absolute()\n bin_path = top_path / \"bricks/virtualhub/build/virtualhub-micropython\"\n if \"PYTHONPATH\" not in os.environ:\n os.environ[\"PYTHONPATH\"] = str(top_path / \"lib/pbio/cpython\")\n if \"PBIO_VIRTUAL_PLATFORM_MODULE\" not in os.environ:\n os.environ[\"PBIO_VIRTUAL_PLATFORM_MODULE\"] = \"pbio_virtual.platform.turtle\"\n result = subprocess.run(\n [bin_path, script_archive.absolute()], capture_output=True, cwd=build_dir.absolute()\n )\n hub_output = (result.stdout or result.stderr).split(b\"\\n\")\n for line in hub_output:\n print(line.decode())\n\n# Save its standard output.\nwith open(build_dir / \"hub_output.txt\", \"wb\") as f:\n for line in hub_output:\n f.write(line + b\"\\n\")\n\n# Plot single motor data if available.\ntry:\n servo_time, servo_data = get_data(build_dir / \"servo.txt\")\n plot_servo_data(servo_time, servo_data, build_dir)\nexcept FileNotFoundError:\n pass\n\n# Plot control data if available.\ntry:\n control_time, control_data = get_data(build_dir / \"control.txt\")\n plot_control_data(control_time, control_data, build_dir)\nexcept (IndexError, FileNotFoundError):\n pass\n\n# Plot drive base data if available.\ntry:\n # Drive base case\n servo_time, servo_data = get_data(build_dir / \"servo_left.txt\")\n plot_servo_data(servo_time, servo_data, build_dir, \"left\")\n\n servo_time, servo_data = get_data(build_dir / \"servo_right.txt\")\n plot_servo_data(servo_time, servo_data, build_dir, \"right\")\n\n control_time, control_data = get_data(build_dir / \"control_distance.txt\")\n plot_control_data(control_time, control_data, build_dir, \"distance\")\n\n control_time, control_data = get_data(build_dir / \"control_heading.txt\")\n plot_control_data(control_time, control_data, build_dir, \"heading\")\nexcept FileNotFoundError:\n pass\n\n# If requested, show blocking windows with plots.\nif args.show:\n matplotlib.pyplot.show(block=True)\n" ]
[ [ "matplotlib.use", "matplotlib.pyplot.subplots", "numpy.append", "matplotlib.interactive", "numpy.array", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
SorooshMani-NOAA/pyschism
[ "df803edb53184625b12399f38a8bd26a022abbc1" ]
[ "pyschism/forcing/hycom/hycom2schism.py" ]
[ "import os\nimport sys\nfrom datetime import datetime,timedelta\nimport logging\nimport pathlib\nimport tempfile\nimport subprocess\nimport shutil\nfrom typing import Union\nfrom time import time\n\nimport numpy as np\nimport scipy as sp\nfrom numba import jit, prange\nimport netCDF4 as nc\nfrom netCDF4 import Dataset\nfrom matplotlib.transforms import Bbox\nimport seawater as sw\nimport xarray as xr\n\nfrom pyschism.mesh.base import Nodes, Elements\nfrom pyschism.mesh.vgrid import Vgrid\n\nlogger = logging.getLogger(__name__)\n\ndef get_database(date, Bbox=None):\n if date >= datetime(2018, 12, 4):\n database = f'GLBy0.08/expt_93.0'\n elif date >= datetime(2018, 1, 1) and date < datetime(2018, 12, 4):\n database = f'GLBv0.08/expt_93.0'\n elif date >= datetime(2017, 10, 1) and date < datetime(2018, 1, 1):\n database = f'GLBv0.08/expt_92.9'\n elif date >= datetime(2017, 6, 1) and date < datetime(2017, 10, 1):\n database = f'GLBv0.08/expt_57.7'\n elif date >= datetime(2017, 2, 1) and date < datetime(2017, 6, 1):\n database = f'GLBv0.08/expt_92.8'\n elif date >= datetime(2016, 5, 1) and date < datetime(2017, 2, 1):\n database = f'GLBv0.08/expt_57.2'\n elif date >= datetime(2016, 1, 1) and date < datetime(2016, 5, 1):\n database = f'GLBv0.08/expt_56.3'\n elif date >= datetime(1994, 1, 1) and date < datetime(2016, 1, 1):\n database = f'GLBv0.08/expt_53.X/data/{date.year}'\n else:\n logger.info('No data for {date}')\n return database\n\ndef get_idxs(date, database, bbox):\n\n if date.strftime(\"%Y-%m-%d\") >= datetime.now().strftime(\"%Y-%m-%d\"):\n date2 = datetime.now() - timedelta(days=1)\n baseurl = f'https://tds.hycom.org/thredds/dodsC/{database}/FMRC/runs/GLBy0.08_930_FMRC_RUN_{date2.strftime(\"%Y-%m-%dT12:00:00Z\")}?depth[0:1:-1],lat[0:1:-1],lon[0:1:-1],time[0:1:-1]'\n else:\n baseurl=f'https://tds.hycom.org/thredds/dodsC/{database}?lat[0:1:-1],lon[0:1:-1],time[0:1:-1],depth[0:1:-1]'\n\n ds=Dataset(baseurl)\n time1=ds['time']\n times=nc.num2date(time1,units=time1.units,only_use_cftime_datetimes=False)\n \n lon=ds['lon'][:]\n lat=ds['lat'][:]\n dep=ds['depth'][:]\n lat_idxs=np.where((lat>=bbox.ymin-2.0)&(lat<=bbox.ymax+2.0))[0]\n lon_idxs=np.where((lon>=bbox.xmin-2.0) & (lon<=bbox.xmax+2.0))[0]\n lon=lon[lon_idxs]\n lat=lat[lat_idxs]\n #logger.info(lon_idxs)\n #logger.info(lat_idxs)\n lon_idx1=lon_idxs[0].item()\n lon_idx2=lon_idxs[-1].item()\n #logger.info(f'lon_idx1 is {lon_idx1}, lon_idx2 is {lon_idx2}')\n lat_idx1=lat_idxs[0].item()\n lat_idx2=lat_idxs[-1].item()\n #logger.info(f'lat_idx1 is {lat_idx1}, lat_idx2 is {lat_idx2}')\n \n for ilon in np.arange(len(lon)):\n if lon[ilon] > 180:\n lon[ilon] = lon[ilon]-360.\n #lonc=(np.max(lon)+np.min(lon))/2.0\n #logger.info(f'lonc is {lonc}')\n #latc=(np.max(lat)+np.min(lat))/2.0\n #logger.info(f'latc is {latc}')\n x2, y2=transform_ll_to_cpp(lon, lat)\n\n idxs=np.where( date == times)[0]\n #check if time_idx is empty\n if len(idxs) == 0:\n #If there is missing data, use the data from the next days, the maximum searching days is 3. Otherwise, stop.\n for i in np.arange(0,3):\n date_before=(date + timedelta(days=int(i)+1)) #.astype(datetime)\n logger.info(f'Try replacing the missing data from {date_before}')\n idxs=np.where(date_before == times)[0]\n if len(idxs) == 0:\n continue\n else:\n break\n if len(idxs) ==0:\n logger.info(f'No date for date {date}')\n sys.exit()\n time_idx=idxs.item() \n\n ds.close()\n\n return time_idx, lon_idx1, lon_idx2, lat_idx1, lat_idx2, x2, y2\n\ndef transform_ll_to_cpp(lon, lat, lonc=-77.07, latc=24.0):\n #lonc=(np.max(lon)+np.min(lon))/2.0\n #logger.info(f'lonc is {lonc}')\n #latc=(np.max(lat)+np.min(lat))/2.0\n #logger.info(f'latc is {latc}')\n longitude=lon/180*np.pi\n latitude=lat/180*np.pi\n radius=6378206.4\n loncc=lonc/180*np.pi\n latcc=latc/180*np.pi\n lon_new=[radius*(longitude[i]-loncc)*np.cos(latcc) for i in np.arange(len(longitude))]\n lat_new=[radius*latitude[i] for i in np.arange(len(latitude))]\n\n return np.array(lon_new), np.array(lat_new)\n\ndef interp_to_points_3d(dep, y2, x2, bxyz, val):\n idxs = np.where(abs(val) > 10000)\n val[idxs] = float('nan')\n\n val_fd = sp.interpolate.RegularGridInterpolator((dep,y2,x2),np.squeeze(val),'linear', bounds_error=False, fill_value = float('nan'))\n val_int = val_fd(bxyz)\n idxs = np.isnan(val_int)\n if np.sum(idxs) != 0:\n val_int[idxs] = sp.interpolate.griddata(bxyz[~idxs,:], val_int[~idxs], bxyz[idxs,:],'nearest')\n idxs = np.isnan(val_int)\n if np.sum(idxs) != 0:\n logger.info(f'There is still missing value for {val}')\n sys.exit()\n return val_int\n\ndef interp_to_points_2d(y2, x2, bxy, val):\n idxs = np.where(abs(val) > 10000)\n val[idxs] = float('nan')\n\n val_fd = sp.interpolate.RegularGridInterpolator((y2,x2),np.squeeze(val),'linear', bounds_error=False, fill_value = float('nan'))\n val_int = val_fd(bxy)\n idxs = np.isnan(val_int)\n if np.sum(idxs) != 0:\n val_int[idxs] = sp.interpolate.griddata(bxy[~idxs,:], val_int[~idxs], bxy[idxs,:],'nearest')\n idxs = np.isnan(val_int)\n if np.sum(idxs) != 0:\n logger.info(f'There is still missing value for {val}')\n sys.exit()\n return val_int\n\ndef ConvertTemp(salt, temp, dep):\n nz = temp.shape[0]\n ny = temp.shape[1]\n nx = temp.shape[2]\n pr = np.ones(temp.shape)\n pre = pr*dep[:,None, None]\n Pr = np.zeros(temp.shape)\n ptemp = sw.ptmp(salt, temp, pre, Pr)*1.00024\n return ptemp\n\nclass OpenBoundaryInventory:\n\n def __init__(self, hgrid, vgrid=None):\n self.hgrid = hgrid\n self.vgrid = Vgrid.default() if vgrid is None else vgrid\n\n def fetch_data(self, outdir: Union[str, os.PathLike], start_date, rnday, elev2D=True, TS=True, UV=True, adjust2D=False, lats=None, msl_shifts=None): \n outdir = pathlib.Path(outdir)\n\n self.start_date = start_date\n self.rnday=rnday\n self.timevector=np.arange(\n self.start_date,\n self.start_date + timedelta(days=self.rnday+1),\n timedelta(days=1)).astype(datetime)\n\n #Get open boundary \n gdf=self.hgrid.boundaries.open.copy()\n opbd=[]\n for boundary in gdf.itertuples():\n opbd.extend(list(boundary.indexes))\n blon = self.hgrid.coords[opbd,0]\n blat = self.hgrid.coords[opbd,1]\n #logger.info(f'blon min {np.min(blon)}, max {np.max(blon)}')\n NOP = len(blon)\n\n #calculate zcor for 3D\n if TS or UV:\n vd=Vgrid.open(self.vgrid)\n sigma=vd.sigma\n\n #get bathymetry\n depth = self.hgrid.values\n\n #compute zcor\n zcor = depth[:,None]*sigma\n nvrt=zcor.shape[1]\n\n #zcor2=zcor[opbd,:]\n #idxs=np.where(zcor2 > 5000)\n #zcor2[idxs]=5000.0-1.0e-6\n\n #construct schism grid\n #x2i=np.tile(xi,[nvrt,1]).T\n #y2i=np.tile(yi,[nvrt,1]).T\n #bxyz=np.c_[zcor2.reshape(np.size(zcor2)),y2i.reshape(np.size(y2i)),x2i.reshape(np.size(x2i))]\n #logger.info('Computing SCHISM zcor is done!')\n\n #create netcdf\n ntimes=self.rnday+1\n nComp1=1\n nComp2=2\n one=1\n #ndt=np.zeros([ntimes])\n\n if elev2D:\n #timeseries_el=np.zeros([ntimes,NOP,nComp1])\n #create netcdf \n dst_elev = Dataset(outdir / 'elev2D.th.nc', 'w', format='NETCDF4')\n #dimensions\n dst_elev.createDimension('nOpenBndNodes', NOP)\n dst_elev.createDimension('one', one)\n dst_elev.createDimension('time', None)\n dst_elev.createDimension('nLevels', one)\n dst_elev.createDimension('nComponents', nComp1)\n\n #variables\n dst_elev.createVariable('time_step', 'f', ('one',))\n dst_elev['time_step'][:] = 86400\n\n dst_elev.createVariable('time', 'f', ('time',))\n #dst_elev['time'][:] = ndt\n\n dst_elev.createVariable('time_series', 'f', ('time', 'nOpenBndNodes', 'nLevels', 'nComponents'))\n #dst_elev['time_series'][:,:,:,:] = timeseries_el\n\n if TS:\n #timeseries_s=np.zeros([ntimes,NOP,nvrt,nComp1])\n dst_salt = Dataset(outdir / 'SAL_3D.th.nc', 'w', format='NETCDF4')\n #dimensions\n dst_salt.createDimension('nOpenBndNodes', NOP)\n dst_salt.createDimension('one', one)\n dst_salt.createDimension('time', None)\n dst_salt.createDimension('nLevels', nvrt)\n dst_salt.createDimension('nComponents', nComp1)\n #variables\n dst_salt.createVariable('time_step', 'f', ('one',))\n dst_salt['time_step'][:] = 86400\n\n dst_salt.createVariable('time', 'f', ('time',))\n #dst_salt['time'][:] = ndt\n\n dst_salt.createVariable('time_series', 'f', ('time', 'nOpenBndNodes', 'nLevels', 'nComponents'))\n\n #temp\n #timeseries_t=np.zeros([ntimes,NOP,nvrt,nComp1])\n\n dst_temp = Dataset(outdir / 'TEM_3D.th.nc', 'w', format='NETCDF4')\n #dimensions\n dst_temp.createDimension('nOpenBndNodes', NOP)\n dst_temp.createDimension('one', one)\n dst_temp.createDimension('time', None)\n dst_temp.createDimension('nLevels', nvrt)\n dst_temp.createDimension('nComponents', nComp1)\n #variables\n dst_temp.createVariable('time_step', 'f', ('one',))\n dst_temp['time_step'][:] = 86400\n\n dst_temp.createVariable('time', 'f', ('time',))\n #dst_temp['time'][:] = ndt\n\n dst_temp.createVariable('time_series', 'f', ('time', 'nOpenBndNodes', 'nLevels', 'nComponents'))\n #dst_temp['time_series'][:,:,:,:] = timeseries_t\n\n if UV:\n #timeseries_uv=np.zeros([ntimes,NOP,nvrt,nComp2])\n dst_uv = Dataset(outdir / 'uv3D.th.nc', 'w', format='NETCDF4')\n #dimensions\n dst_uv.createDimension('nOpenBndNodes', NOP)\n dst_uv.createDimension('one', one)\n dst_uv.createDimension('time', None)\n dst_uv.createDimension('nLevels', nvrt)\n dst_uv.createDimension('nComponents', nComp2)\n #variables\n dst_uv.createVariable('time_step', 'f', ('one',))\n dst_uv['time_step'][:] = 86400\n\n dst_uv.createVariable('time', 'f', ('time',))\n #dst_uv['time'][:] = ndt\n \n dst_uv.createVariable('time_series', 'f', ('time', 'nOpenBndNodes', 'nLevels', 'nComponents'))\n #dst_uv['time_series'][:,:,:,:] = timeseries_uv\n\n logger.info('**** Accessing GOFS data*****')\n t0=time()\n for it, date in enumerate(self.timevector):\n\n database=get_database(date)\n logger.info(f'Fetching data for {date} from database {database}')\n\n #loop over each open boundary\n ind1 = 0\n ind2 = 0\n for boundary in gdf.itertuples():\n\n opbd = list(boundary.indexes)\n ind1 = ind2\n ind2 = ind1 + len(opbd)\n #logger.info(f'ind1 = {ind1}, ind2 = {ind2}')\n blon = self.hgrid.coords[opbd,0]\n blat = self.hgrid.coords[opbd,1]\n xi,yi = transform_ll_to_cpp(blon, blat)\n bxy = np.c_[yi, xi]\n\n if TS or UV:\n zcor2=zcor[opbd,:]\n idxs=np.where(zcor2 > 5000)\n zcor2[idxs]=5000.0-1.0e-6\n\n #construct schism grid\n x2i=np.tile(xi,[nvrt,1]).T\n y2i=np.tile(yi,[nvrt,1]).T\n bxyz=np.c_[zcor2.reshape(np.size(zcor2)),y2i.reshape(np.size(y2i)),x2i.reshape(np.size(x2i))]\n\n xmin, xmax = np.min(blon), np.max(blon)\n ymin, ymax = np.min(blat), np.max(blat)\n\n if date.strftime(\"%Y-%m-%d\") >= datetime(2017, 2, 1).strftime(\"%Y-%m-%d\") and \\\n date.strftime(\"%Y-%m-%d\") < datetime(2017, 6, 1).strftime(\"%Y-%m-%d\") or \\\n date.strftime(\"%Y-%m-%d\") >= datetime(2017, 10, 1).strftime(\"%Y-%m-%d\"):\n xmin = xmin + 360. if xmin < 0 else xmin\n xmax = xmax + 360. if xmax < 0 else xmax\n bbox = Bbox.from_extents(xmin, ymin, xmax, ymax)\n else:\n bbox = Bbox.from_extents(xmin, ymin, xmax, ymax)\n #logger.info(f'xmin is {xmin}, xmax is {xmax}')\n\n time_idx, lon_idx1, lon_idx2, lat_idx1, lat_idx2, x2, y2 = get_idxs(date, database, bbox)\n\n if date.strftime(\"%Y-%m-%d\") >= datetime.now().strftime(\"%Y-%m-%d\"):\n date2 = datetime.now() - timedelta(days=1)\n url = f'https://tds.hycom.org/thredds/dodsC/{database}/FMRC/runs/GLBy0.08_930_FMRC_RUN_' + \\\n f'{date2.strftime(\"%Y-%m-%dT12:00:00Z\")}?depth[0:1:-1],lat[{lat_idx1}:1:{lat_idx2}],' + \\\n f'lon[{lon_idx1}:1:{lon_idx2}],time[{time_idx}],' + \\\n f'surf_el[{time_idx}][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}],' + \\\n f'water_temp[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}],' + \\\n f'salinity[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}],' + \\\n f'water_u[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}],' + \\\n f'water_v[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}]'\n \n else:\n url=f'https://tds.hycom.org/thredds/dodsC/{database}?lat[{lat_idx1}:1:{lat_idx2}],' + \\\n f'lon[{lon_idx1}:1:{lon_idx2}],depth[0:1:-1],time[{time_idx}],' + \\\n f'surf_el[{time_idx}][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}],' + \\\n f'water_temp[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}],' + \\\n f'salinity[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}],' + \\\n f'water_u[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}],' + \\\n f'water_v[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}]'\n #logger.info(url)\n \n ds=Dataset(url)\n dep=ds['depth'][:]\n\n logger.info('****Interpolation starts****')\n\n #ndt[it]=it*24*3600.\n\n if elev2D:\n #ssh\n ssh=np.squeeze(ds['surf_el'][:,:])\n\n ssh_int = interp_to_points_2d(y2, x2, bxy, ssh)\n dst_elev['time'][it] = it*24*3600.\n if adjust2D:\n elev_adjust = np.interp(blat, lats, msl_shifts)\n dst_elev['time_series'][it,ind1:ind2,0,0] = ssh_int + elev_adjust\n else:\n dst_elev['time_series'][it,ind1:ind2,0,0] = ssh_int \n\n if TS:\n #salt\n salt = np.squeeze(ds['salinity'][:,:,:])\n\n salt_int = interp_to_points_3d(dep, y2, x2, bxyz, salt)\n salt_int = salt_int.reshape(zcor2.shape)\n #timeseries_s[it,:,:,0]=salt_int\n dst_salt['time'][it] = it*24*3600.\n dst_salt['time_series'][it,ind1:ind2,:,0] = salt_int\n\n #temp\n temp = np.squeeze(ds['water_temp'][:,:,:])\n\n #Convert temp to potential temp\n ptemp = ConvertTemp(salt, temp, dep)\n\n temp_int = interp_to_points_3d(dep, y2, x2, bxyz, ptemp)\n temp_int = temp_int.reshape(zcor2.shape)\n #timeseries_t[it,:,:,0]=temp_int\n dst_temp['time'][it] = it*24*3600.\n dst_temp['time_series'][it,ind1:ind2,:,0] = temp_int\n\n if UV:\n uvel=np.squeeze(ds['water_u'][:,:,:])\n vvel=np.squeeze(ds['water_v'][:,:,:])\n\n dst_uv['time'][it] = it*24*3600.\n #uvel\n uvel_int = interp_to_points_3d(dep, y2, x2, bxyz, uvel)\n uvel_int = uvel_int.reshape(zcor2.shape)\n dst_uv['time_series'][it,ind1:ind2,:,0] = uvel_int\n\n #vvel\n vvel_int = interp_to_points_3d(dep, y2, x2, bxyz, vvel)\n vvel_int = vvel_int.reshape(zcor2.shape)\n dst_uv['time_series'][it,ind1:ind2,:,1] = vvel_int\n #timeseries_uv[it,:,:,1]=vvel_int\n\n logger.info(f'Writing *th.nc takes {time()-t0} seconds')\n\nclass Nudge:\n\n def __init__(self):\n\n self.include = None\n\n\n def gen_nudge(self, outdir: Union[str, os.PathLike], hgrid, rlmax = 1.5, rnu_day=0.25):\n\n @jit(nopython=True, parallel=True)\n def compute_nudge(lon, lat, nnode, opbd, out):\n \n rnu_max = 1.0 / rnu_day / 86400.0\n rnu = 0\n\n for idn in prange(nnode):\n if idn in opbd:\n rnu = rnu_max\n distmin = 0.\n else:\n distmin = np.finfo(np.float64).max\n for j in opbd:\n tmp = np.square(lon[idn]-lon[j]) + np.square(lat[idn]-lat[j])\n rl2 = np.sqrt(tmp)\n if rl2 < distmin:\n distmin=rl2\n rnu = 0.\n if distmin <= rlmax:\n rnu = (1-distmin/rlmax)*rnu_max\n #idxs_nudge[idn]=1 #idn\n out[idn] = rnu\n\n outdir = pathlib.Path(outdir)\n\n #get nudge zone\n lon=hgrid.coords[:,0]\n lat=hgrid.coords[:,1]\n\n #Get open boundary \n gdf=hgrid.boundaries.open.copy()\n opbd=[]\n for boundary in gdf.itertuples():\n opbd.extend(list(boundary.indexes))\n opbd = np.array(opbd)\n\n elnode=hgrid.elements.array\n NE, NP = len(elnode), len(lon)\n\n out = np.zeros([NP])\n idxs_nudge=np.zeros(NP, dtype=int)\n t0 = time()\n #compute_nudge(lon, lat, NP, opbd2, idxs_nudge, out)\n compute_nudge(lon, lat, NP, opbd, out)\n\n idxs=np.where(out > 0)[0]\n idxs_nudge[idxs]=1\n #expand nudging marker to neighbor nodes\n idxs=np.where(np.max(out[elnode], axis=1) > 0)[0]\n fp=elnode[idxs,-1] < 0\n idxs_nudge[elnode[idxs[fp],:3]]=1\n idxs_nudge[elnode[idxs[~fp],:]]=1\n\n #idxs_nudge=np.delete(idxs_nudge, np.where(idxs_nudge == -99))\n idxs=np.where(idxs_nudge == 1)[0]\n self.include=idxs\n #logger.info(f'len of nudge idxs is {len(idxs)}')\n logger.info(f'It took {time() -t0} sencods to calcuate nudge coefficient')\n\n nudge = [f\"{rlmax}, {rnu_day}\"]\n nudge.extend(\"\\n\")\n nudge.append(f\"{NE} {NP}\")\n nudge.extend(\"\\n\")\n hgrid = hgrid.to_dict()\n nodes = hgrid['nodes']\n elements = hgrid['elements']\n for idn, (coords, values) in nodes.items():\n line = [f\"{idn}\"]\n line.extend([f\"{x:<.7e}\" for x in coords])\n line.extend([f\"{out[int(idn)-1]:<.7e}\"])\n line.extend(\"\\n\")\n nudge.append(\" \".join(line))\n\n for id, element in elements.items():\n line = [f\"{id}\"]\n line.append(f\"{len(element)}\")\n line.extend([f\"{e}\" for e in element])\n line.extend(\"\\n\")\n nudge.append(\" \".join(line))\n\n with open(outdir / 'TEM_nudge.gr3','w+') as fid:\n fid.writelines(nudge)\n\n shutil.copy2(outdir / 'TEM_nudge.gr3', outdir / 'SAL_nudge.gr3')\n\n return self.include\n\n def fetch_data(self, outdir: Union[str, os.PathLike], hgrid, vgrid, start_date, rnday):\n\n outdir = pathlib.Path(outdir)\n\n self.start_date = start_date\n self.rnday=rnday\n self.timevector=np.arange(\n self.start_date,\n self.start_date + timedelta(days=self.rnday+1),\n timedelta(days=1)).astype(datetime)\n\n vd=Vgrid.open(vgrid)\n sigma=vd.sigma\n\n #Get the index for nudge\n include = self.gen_nudge(outdir,hgrid)\n\n #get coords of SCHISM\n loni=hgrid.nodes.coords[:,0]\n lati=hgrid.nodes.coords[:,1]\n\n #get bathymetry\n depth = hgrid.values\n\n #compute zcor\n zcor = depth[:,None]*sigma\n nvrt=zcor.shape[1]\n #logger.info(f'zcor at node 1098677 is {zcor[1098676,:]}')\n\n #Get open nudge array \n nlon = hgrid.coords[include, 0]\n nlat = hgrid.coords[include, 1]\n xi,yi = transform_ll_to_cpp(nlon, nlat)\n bxy = np.c_[yi, xi]\n\n zcor2=zcor[include,:]\n idxs=np.where(zcor2 > 5000)\n #logger.info(idxs)\n zcor2[idxs]=5000.0-1.0e-6\n #logger.info(f'zcor2 at node 200 is {zcor2[199,:]}')\n\n #construct schism grid\n x2i=np.tile(xi,[nvrt,1]).T\n y2i=np.tile(yi,[nvrt,1]).T\n bxyz=np.c_[zcor2.reshape(np.size(zcor2)),y2i.reshape(np.size(y2i)),x2i.reshape(np.size(x2i))]\n logger.info('Computing SCHISM zcor is done!')\n\n #allocate output variables\n nNode=len(include)\n one=1\n ntimes=self.rnday+1\n\n timeseries_s=np.zeros([ntimes,nNode,nvrt,one])\n timeseries_t=np.zeros([ntimes,nNode,nvrt,one])\n ndt=np.zeros([ntimes])\n\n logger.info('**** Accessing GOFS data*****')\n t0=time()\n for it, date in enumerate(self.timevector):\n\n database=get_database(date)\n logger.info(f'Fetching data for {date} from database {database}')\n\n xmin, xmax = np.min(nlon), np.max(nlon)\n ymin, ymax = np.min(nlat), np.max(nlat)\n\n if date.strftime(\"%Y-%m-%d\") >= datetime(2017, 2, 1).strftime(\"%Y-%m-%d\") and \\\n date.strftime(\"%Y-%m-%d\") < datetime(2017, 6, 1).strftime(\"%Y-%m-%d\") or \\\n date.strftime(\"%Y-%m-%d\") >= datetime(2017, 10, 1).strftime(\"%Y-%m-%d\"):\n logger.info('Convert xmin and xmax')\n xmin = xmin + 360. if xmin < 0 else xmin\n xmax = xmax + 360. if xmax < 0 else xmax\n bbox = Bbox.from_extents(xmin, ymin, xmax, ymax)\n else:\n bbox = Bbox.from_extents(xmin, ymin, xmax, ymax)\n #logger.info(f'xmin is {xmin}, xmax is {xmax}')\n\n time_idx, lon_idx1, lon_idx2, lat_idx1, lat_idx2, x2, y2 = get_idxs(date, database, bbox)\n\n if date.strftime(\"%Y-%m-%d\") >= datetime.now().strftime(\"%Y-%m-%d\"):\n date2 = datetime.now() - timedelta(days=1)\n url = f'https://tds.hycom.org/thredds/dodsC/{database}/FMRC/runs/GLBy0.08_930_FMRC_RUN_' + \\\n f'{date2.strftime(\"%Y-%m-%dT12:00:00Z\")}?depth[0:1:-1],lat[{lat_idx1}:1:{lat_idx2}],' + \\\n f'lon[{lon_idx1}:1:{lon_idx2}],time[{time_idx}],' + \\\n f'water_temp[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}],' + \\\n f'salinity[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}]'\n\n else:\n url=f'https://tds.hycom.org/thredds/dodsC/{database}?lat[{lat_idx1}:1:{lat_idx2}],' + \\\n f'lon[{lon_idx1}:1:{lon_idx2}],depth[0:1:-1],time[{time_idx}],' + \\\n f'water_temp[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}],' + \\\n f'salinity[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}]'\n #logger.info(url)\n\n ds=Dataset(url)\n salt=np.squeeze(ds['salinity'][:,:,:])\n temp=np.squeeze(ds['water_temp'][:,:,:])\n #logger.info(f'The shape of temp is {temp.shape}')\n\n #Convert temp to potential temp\n dep=ds['depth'][:]\n ptemp = ConvertTemp(salt, temp, dep)\n\n logger.info('****Interpolation starts****')\n\n ndt[it]=it\n #salt\n salt_int = interp_to_points_3d(dep, y2, x2, bxyz, salt)\n salt_int = salt_int.reshape(zcor2.shape)\n timeseries_s[it,:,:,0]=salt_int\n\n #temp\n temp_int = interp_to_points_3d(dep, y2, x2, bxyz, ptemp)\n temp_int = temp_int.reshape(zcor2.shape)\n timeseries_t[it,:,:,0]=temp_int\n \n with Dataset(outdir / 'TEM_nu.nc', 'w', format='NETCDF4') as dst:\n #dimensions\n dst.createDimension('node', nNode)\n dst.createDimension('nLevels', nvrt)\n dst.createDimension('one', one)\n dst.createDimension('time', None)\n #variables\n dst.createVariable('time', 'f', ('time',))\n dst['time'][:] = ndt\n\n dst.createVariable('map_to_global_node', 'i4', ('node',))\n dst['map_to_global_node'][:] = include+1\n\n dst.createVariable('tracer_concentration', 'f', ('time', 'node', 'nLevels', 'one'))\n dst['tracer_concentration'][:,:,:,:] = timeseries_t\n\n with Dataset(outdir / 'SAL_nu.nc', 'w', format='NETCDF4') as dst:\n #dimensions\n dst.createDimension('node', nNode)\n dst.createDimension('nLevels', nvrt)\n dst.createDimension('one', one)\n dst.createDimension('time', None)\n #variables\n dst.createVariable('time', 'f', ('time',))\n dst['time'][:] = ndt\n\n dst.createVariable('map_to_global_node', 'i4', ('node',))\n dst['map_to_global_node'][:] = include+1\n\n dst.createVariable('tracer_concentration', 'f', ('time', 'node', 'nLevels', 'one'))\n dst['tracer_concentration'][:,:,:,:] = timeseries_s\n\n\n logger.info(f'Writing *_nu.nc takes {time()-t0} seconds')\n\nclass DownloadHycom:\n\n def __init__(self, hgrid):\n\n self.bbox = hgrid.bbox\n\n def fetch_data(self, date):\n\n database=get_database(date)\n logger.info(f'Fetching data for {date} from database {database}')\n\n time_idx, lon_idx1, lon_idx2, lat_idx1, lat_idx2, x2, y2 = get_idxs(date, database, self.bbox)\n\n url_ssh = f'https://tds.hycom.org/thredds/dodsC/{database}?lat[{lat_idx1}:1:{lat_idx2}],' + \\\n f'lon[{lon_idx1}:1:{lon_idx2}],depth[0:1:-1],time[{time_idx}],' + \\\n f'surf_el[{time_idx}][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}]'\n foutname = f'SSH_{date.strftime(\"%Y%m%d\")}.nc'\n logger.info(f'filename is {foutname}')\n ds = xr.open_dataset(url_ssh)\n ds1 = ds.rename_dims({'lon':'xlon'})\n ds2 = ds1.rename_dims({'lat':'ylat'})\n ds3 = ds2.rename_vars({'lat':'ylat'})\n ds4 = ds3.rename_vars({'lon':'xlon'})\n ds4.to_netcdf(foutname, 'w', 'NETCDF3_CLASSIC', unlimited_dims='time')\n ds.close()\n ds1.close()\n ds2.close()\n ds3.close()\n ds4.close()\n\n url_uv = f'https://tds.hycom.org/thredds/dodsC/{database}?lat[{lat_idx1}:1:{lat_idx2}],' + \\\n f'lon[{lon_idx1}:1:{lon_idx2}],depth[0:1:-1],time[{time_idx}],' + \\\n f'water_u[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}],' + \\\n f'water_v[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}]'\n\n foutname = f'UV_{date.strftime(\"%Y%m%d\")}.nc'\n logger.info(f'filename is {foutname}')\n ds = xr.open_dataset(url_uv)\n ds1 = ds.rename_dims({'lon':'xlon'})\n ds2 = ds1.rename_dims({'lat':'ylat'})\n ds3 = ds2.rename_vars({'lat':'ylat'})\n ds4 = ds3.rename_vars({'lon':'xlon'})\n ds4.to_netcdf(foutname, 'w', 'NETCDF3_CLASSIC', unlimited_dims='time')\n ds.close()\n ds1.close()\n ds2.close()\n ds3.close()\n ds4.close()\n\n url_ts = f'https://tds.hycom.org/thredds/dodsC/{database}?lat[{lat_idx1}:1:{lat_idx2}],' + \\\n f'lon[{lon_idx1}:1:{lon_idx2}],depth[0:1:-1],time[{time_idx}],' + \\\n f'water_temp[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}],' + \\\n f'salinity[{time_idx}][0:1:39][{lat_idx1}:1:{lat_idx2}][{lon_idx1}:1:{lon_idx2}]'\n\n foutname = f'ST_{date.strftime(\"%Y%m%d\")}.nc'\n logger.info(f'filename is {foutname}')\n\n ds = xr.open_dataset(url_ts)\n temp = ds.water_temp.values\n salt = ds.salinity.values\n dep = ds.depth.values\n\n #convert in-situ temperature to potential temperature\n ptemp = ConvertTemp(salt, temp, dep)\n\n #drop water_temp variable and add new temperature variable\n ds1 = ds.drop('water_temp')\n ds1['temperature']=(['time','depth','lat','lon'], ptemp)\n ds1.temperature.attrs = {\n 'long_name': 'Sea water potential temperature',\n 'standard_name': 'sea_water_potential_temperature',\n 'units': 'degC'\n }\n\n #ds.assign(water_temp2=ptemp)\n #ds.assign.attrs = ds.water_temp.attrs\n\n ds2 = ds1.rename_dims({'lon':'xlon'})\n ds3 = ds2.rename_dims({'lat':'ylat'})\n ds4 = ds3.rename_vars({'lat':'ylat'})\n ds5 = ds4.rename_vars({'lon':'xlon'})\n ds5.to_netcdf(foutname, 'w', unlimited_dims='time', encoding={'temperature':{'dtype': 'h', '_FillValue': -30000.,'scale_factor': 0.001, 'add_offset': 20., 'missing_value': -30000.}})\n ds.close()\n ds1.close()\n ds2.close()\n ds3.close()\n ds4.close()\n ds5.close()\n" ]
[ [ "numpy.sqrt", "numpy.squeeze", "numpy.max", "scipy.interpolate.griddata", "numpy.where", "numpy.square", "numpy.arange", "matplotlib.transforms.Bbox.from_extents", "numpy.finfo", "numpy.size", "numpy.interp", "numpy.zeros", "numpy.min", "numpy.isnan", "numpy.array", "numpy.sum", "numpy.cos", "numpy.tile", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
MStarmans91/WORC
[ "14e8099835eccb35d49b52b97c0be64ecca3809c", "14e8099835eccb35d49b52b97c0be64ecca3809c", "14e8099835eccb35d49b52b97c0be64ecca3809c" ]
[ "WORC/resources/fastr_types/PyRadiomicsCSVFile.py", "WORC/facade/helpers/processing.py", "WORC/featureprocessing/StatisticalTestThreshold.py" ]
[ "# Copyright 2020-2020 Biomedical Imaging Group Rotterdam, Departments of\n# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands\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 os\nimport pandas as pd\nfrom fastr.datatypes import URLType\n\n\nclass PyRadiomicsCSVFile(URLType):\n description = 'PyRadiomics CSV file'\n extension = 'csv'\n\n def _validate(self):\n # Function to validate the filetype\n parsed_value = self.parsed_value\n\n if self.extension and not parsed_value.endswith(self.extension):\n return False\n\n if not os.path.isfile(parsed_value):\n return False\n\n try:\n # Read the file and extract features\n data = pd.read_csv(parsed_value)\n nrows, ncols = data.shape\n\n if ncols == 2:\n # Only mask and segmentation key, no valid feature file\n\n # As PyRadiomics cannot handle multiple exuctions well,\n # delete the file\n os.remove(parsed_value)\n\n return False\n\n if nrows != 1:\n # Ran multiple times, appended features, which is invalid\n\n # As PyRadiomics cannot handle multiple exuctions well,\n # delete the file\n os.remove(parsed_value)\n\n return False\n\n if ncols == 0 or nrows == 0:\n # No information, so invalid file\n\n # As PyRadiomics cannot handle multiple exuctions well,\n # delete the file\n os.remove(parsed_value)\n\n return False\n\n # No errors, so file is valid\n return True\n\n except OSError:\n # Not a valid feature file\n return False\n", "import pandas as pd\nimport os\nfrom WORC.addexceptions import WORCKeyError\n\n# All standard texture features accepted\ntexture_features = ['GLCM', 'GLDZM', 'GLRLM', 'GLSZM', 'NGLDM', 'NGTDM']\n\n\ndef convert_radiomix_features(input_file, output_folder):\n '''\n Convert .xlsx from RadiomiX to WORC compatible .hdf5 format\n\n Input:\n --------------\n\n input_file: .xlsx in which the feature are stored.\n output_folder: folder in which features are stored\n '''\n\n print('Converting .xlsx from RadiomiX to WORC compatible .hdf5 format...')\n # Check if output folder exists: otherwise create\n if not os.path.exists(output_folder):\n os.mkdir(output_folder)\n\n # Read the input file and extract relevant fields\n f = pd.read_excel(input_file)\n pids = f.values[:, 4]\n segs = f.values[:, 5]\n features = f.values[:, 10:]\n\n # Read the feature labels, and rename them according to the group they belong to\n feature_labels = list(f.keys()[10:])\n for i in range(0, len(feature_labels)):\n l = feature_labels[i]\n if any(l.startswith(j) for j in texture_features):\n # Texture feature\n feature_labels[i] = 'tf_' + 'RadiomiX_' + l\n elif any(l.startswith(j) for j in ['IH_', 'Stats_']):\n # Histogram feature\n feature_labels[i] = 'hf_' + 'RadiomiX_' + l\n elif l.startswith('Shape_'):\n # Shape feature\n feature_labels[i] = 'sf_' + 'RadiomiX_' + l\n elif l.startswith('LoG_'):\n # LoG feature\n feature_labels[i] = 'logf_' + 'RadiomiX_' + l\n elif l.startswith('Fractal_'):\n # Fractal feature\n feature_labels[i] = 'fracf_' + 'RadiomiX_' + l\n elif l.startswith('LocInt_'):\n # Location feature\n feature_labels[i] = 'locf_' + 'RadiomiX_' + l\n elif l.startswith('RGRD_'):\n # RGRD feature\n feature_labels[i] = 'rgrdf_' + 'RadiomiX_' + l\n elif l.startswith('Wavelet_'):\n # RGRD feature\n feature_labels[i] = 'waveletf_' + 'RadiomiX_' + l\n else:\n raise WORCKeyError(f'Unknown feature {l}.')\n\n # Initiate labels for pandas file\n panda_labels = ['feature_values',\n 'feature_labels']\n\n # For each patient, convert features\n for i_patient in range(0, len(pids)):\n feature_values = features[i_patient, :].tolist()\n\n # Make an output folder per patient, remove invalid symbols.\n output = pids[i_patient] + segs[i_patient]\n output = output.replace(' ', '_')\n output = output.replace('(', '_')\n output = output.replace(')', '_')\n output = os.path.join(output_folder, output)\n\n # Check if output folder exists: otherwise create\n if not os.path.exists(output):\n os.mkdir(output)\n\n output = os.path.join(output, 'features.hdf5')\n\n print(f'\\t Writing {output}')\n\n # Convert to pandas Series and save as hdf5\n panda_data = pd.Series([feature_values,\n feature_labels],\n index=panda_labels,\n name='Image features'\n )\n\n # Save the features to the .hdf5 file\n print('\\t Saving image features')\n panda_data.to_hdf(output, 'image_features')\n", "#!/usr/bin/env python\n\n# Copyright 2016-2019 Biomedical Imaging Group Rotterdam, Departments of\n# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands\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 sklearn.base import BaseEstimator\nfrom sklearn.feature_selection import SelectorMixin\nimport numpy as np\nfrom scipy.stats import ttest_ind, ranksums, mannwhitneyu\n\n\nclass StatisticalTestThreshold(BaseEstimator, SelectorMixin):\n '''\n Object to fit feature selection based on statistical tests.\n '''\n def __init__(self, metric='ttest', threshold=0.05):\n '''\n Parameters\n ----------\n metric: string, default 'ttest'\n Statistical test used for selection. Options are ttest,\n Welch, Wilcoxon, MannWhitneyU\n threshold: float, default 0.05\n Threshold for p-value in order for feature to be selected\n\n '''\n self.metric = metric\n self.threshold = threshold\n\n def fit(self, X_train, Y_train):\n '''\n Select only features specificed by the metric and threshold per patient.\n\n Parameters\n ----------\n X_train: numpy array, mandatory\n Array containing feature values used for model_selection.\n Number of objects on first axis, features on second axis.\n\n Y_train: numpy array, mandatory\n Array containing the binary labels for each object in X_train.\n '''\n\n self.selectrows = list()\n self.metric_values = list()\n\n # Set the metric function\n if self.metric == 'ttest':\n self.metric_function = ttest_ind\n self.parameters = {'equal_var': True}\n elif self.metric == 'Welch':\n self.metric_function = ttest_ind\n self.parameters = {'equal_var': False}\n elif self.metric == 'Wilcoxon':\n self.metric_function = ranksums\n self.parameters = {}\n elif self.metric == 'MannWhitneyU':\n self.metric_function = mannwhitneyu\n self.parameters = {}\n\n # Perform the statistical test for each feature\n multilabel = type(Y_train[0]) is np.ndarray\n for n_feat in range(0, X_train.shape[1]):\n # Select only this specific feature for all objects\n\n fv = X_train[:, n_feat]\n if multilabel:\n # print('Multilabel: take minimum p-value for all label tests.')\n # We do a statistical test per label and take the minimum p-value\n n_label = Y_train[0].shape[0]\n metric_values = list()\n for i in range(n_label):\n class1 = [i for j, i in enumerate(fv) if np.argmax(Y_train[j]) == n_label]\n class2 = [i for j, i in enumerate(fv) if np.argmax(Y_train[j]) != n_label]\n\n try:\n metric_value_temp = self.metric_function(class1, class2, **self.parameters)[1]\n except ValueError as e:\n print(\"[WORC Warning] \" + str(e) + '. Replacing metric value by 1.')\n metric_value_temp\n\n metric_values.append(metric_value_temp)\n\n metric_value = np.min(metric_values)\n\n else:\n # Singlelabel\n class1 = [i for j, i in enumerate(fv) if Y_train[j] == 1]\n class2 = [i for j, i in enumerate(fv) if Y_train[j] == 0]\n\n try:\n metric_value = self.metric_function(class1, class2, **self.parameters)[1]\n except ValueError as e:\n print(\"[WORC Warning] \" + str(e) + '. Replacing metric value by 1.')\n metric_value = 1\n\n self.metric_values.append(metric_value)\n if metric_value < self.threshold:\n self.selectrows.append(n_feat)\n\n def transform(self, inputarray):\n '''\n Transform the inputarray to select only the features based on the\n result from the fit function.\n\n Parameters\n ----------\n inputarray: numpy array, mandatory\n Array containing the items to use selection on. The type of\n item in this list does not matter, e.g. floats, strings etc.\n '''\n return np.asarray([np.asarray(x)[self.selectrows].tolist() for x in inputarray])\n\n def _get_support_mask(self):\n # NOTE: metric is required for the Selector class, but can be empty\n pass\n" ]
[ [ "pandas.read_csv" ], [ "pandas.read_excel", "pandas.Series" ], [ "numpy.asarray", "numpy.argmax", "numpy.min" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lhideki/text-vectorian
[ "24e9a2bc69a5c1a25ce4e1102c5c52e2a5a87a7d" ]
[ "text_vectorian/bases.py" ]
[ "from abc import ABC, abstractmethod\nimport numpy as np\n\nclass Vectorizer(ABC):\n @abstractmethod\n def _vectorize(self, token: str):\n pass\n @abstractmethod\n def _get_keras_layer(self, trainable):\n pass\nclass Token:\n def __init__(self, text: str, vectorizer: Vectorizer):\n self._text = text\n (self._index, self._vector) = vectorizer._vectorize(text)\n @property\n def text(self):\n return self._text\n @property\n def vector(self):\n return self._vector\n @property\n def index(self):\n return self._index\nclass Tokenizer(ABC):\n @abstractmethod\n def _tokenize(self, text: str):\n pass\n def _create_tokens(self, text: str, vectorizer: Vectorizer):\n tokens = self._tokenize(text)\n\n return [Token(token, vectorizer) for token in tokens]\nclass TextVectorian(ABC):\n @property\n @abstractmethod\n def tokenizer(self):\n pass\n @property\n @abstractmethod\n def vectorizer(self):\n pass\n @property\n def max_tokens_len(self):\n return self._max_tokens_len\n @property\n def samples_len(self):\n return self._samples_len\n def reset(self):\n self._max_tokens_len = 0\n self._samples_len = 0\n def fit(self, text: str):\n self._tokens = self.tokenizer._create_tokens(text, self.vectorizer)\n if hasattr(self, '_max_tokens_len'):\n self._max_tokens_len = max(len(self._tokens), self._max_tokens_len)\n else:\n self._max_tokens_len = len(self._tokens)\n self._vectors = []\n self._indices = []\n\n for token in self._tokens:\n self._vectors.append(token.vector)\n self._indices.append(token.index)\n if hasattr(self, '_samples_len'):\n self._samples_len += 1\n else:\n self._samples_len = 1\n\n return self\n @property\n def tokens(self):\n return self._tokens\n @property\n def vectors(self):\n return np.array(self._vectors)\n @property\n def indices(self):\n return np.array(self._indices)\n def get_keras_layer(self, trainable=False):\n return self.vectorizer._get_keras_layer(trainable)" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yuanx749/deep-vaccine
[ "11c2e7fbb1c89a08f96bada1153bd56577e592ff" ]
[ "api.py" ]
[ "import torch\nfrom torch.nn.utils.rnn import pad_sequence\nfrom torch.utils.data import DataLoader, Dataset\n\n\nclass _SequenceDataset(Dataset):\n def __init__(self, seqs, tokenizer):\n self.data = seqs\n self.tokenizer = tokenizer\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n seq = self.data[idx]\n return self.tokenizer.encode(seq)\n\n def collate_fn(self, batch):\n return pad_sequence(\n batch, batch_first=True, padding_value=self.tokenizer.stoi[\"<pad>\"]\n )\n\n\nclass Predictor:\n \"\"\"A predictor that predicts the probabilities of vaccine subunit candidates.\n\n Attributes:\n model: A trained model or a string representing the path of the model.\n \"\"\"\n\n def __init__(self, model):\n self._device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n if isinstance(model, str):\n self.model = torch.load(model, map_location=self._device)\n else:\n self.model = model.to(self._device)\n\n def predict_proba(self, seqs):\n \"\"\"Predicts the probabilities of inputs as vaccine subunit candidates.\n\n Args:\n seqs: A string list of aa sequence.\n\n Returns:\n A float array representing the probabilities.\n \"\"\"\n data = _SequenceDataset(seqs, self.model.tokenizer)\n data_loader = DataLoader(data, batch_size=1, collate_fn=data.collate_fn)\n\n torch.set_grad_enabled(False)\n self.model.eval()\n probs = []\n for inputs in data_loader:\n inputs = inputs.to(self._device)\n outputs = self.model(inputs)\n probs.append(torch.sigmoid(outputs[:, 1])) # label 1 is positive\n probs = torch.cat(probs).cpu().numpy()\n\n return probs\n\n def predict(self, seqs, threshold=0.5):\n \"\"\"Predicts the labels of inputs.\n\n Args:\n seqs: A string list of aa sequence.\n threshold: A float representing the prediction threshold.\n\n Returns:\n A boolean array indicating the vaccine subunit candidates.\n \"\"\"\n return self.predict_prob(seqs) > threshold\n" ]
[ [ "torch.sigmoid", "torch.load", "torch.cat", "torch.nn.utils.rnn.pad_sequence", "torch.utils.data.DataLoader", "torch.set_grad_enabled", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rush2406/OWOD
[ "f8ba612cf4d4969c36322c33d7d460e89958a487" ]
[ "detectron2/modeling/meta_arch/retinanet.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport logging\nimport math\nimport numpy as np\nfrom typing import List\nimport torch\nfrom fvcore.nn import giou_loss, sigmoid_focal_loss_jit, smooth_l1_loss\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom detectron2.config import configurable\nfrom detectron2.data.detection_utils import convert_image_to_rgb\nfrom detectron2.layers import ShapeSpec, batched_nms, cat, get_norm\nfrom detectron2.structures import Boxes, ImageList, Instances, pairwise_iou\nfrom detectron2.utils.events import get_event_storage\n\nfrom ..anchor_generator import build_anchor_generator\nfrom ..backbone import build_backbone\nfrom ..box_regression import Box2BoxTransform\nfrom ..matcher import Matcher\nfrom ..postprocessing import detector_postprocess\nfrom .build import META_ARCH_REGISTRY\n\n__all__ = [\"RetinaNet\"]\n\n\ndef permute_to_N_HWA_K(tensor, K):\n \"\"\"\n Transpose/reshape a tensor from (N, (Ai x K), H, W) to (N, (HxWxAi), K)\n \"\"\"\n assert tensor.dim() == 4, tensor.shape\n N, _, H, W = tensor.shape\n tensor = tensor.view(N, -1, K, H, W)\n tensor = tensor.permute(0, 3, 4, 1, 2)\n tensor = tensor.reshape(N, -1, K) # Size=(N,HWA,K)\n return tensor\n\n\n@META_ARCH_REGISTRY.register()\nclass RetinaNet(nn.Module):\n \"\"\"\n Implement RetinaNet in :paper:`RetinaNet`.\n \"\"\"\n\n def __init__(self, cfg):\n super().__init__()\n # fmt: off\n self.num_classes = cfg.MODEL.RETINANET.NUM_CLASSES\n self.in_features = cfg.MODEL.RETINANET.IN_FEATURES\n # Loss parameters:\n self.focal_loss_alpha = cfg.MODEL.RETINANET.FOCAL_LOSS_ALPHA\n self.focal_loss_gamma = cfg.MODEL.RETINANET.FOCAL_LOSS_GAMMA\n self.smooth_l1_loss_beta = cfg.MODEL.RETINANET.SMOOTH_L1_LOSS_BETA\n self.box_reg_loss_type = cfg.MODEL.RETINANET.BBOX_REG_LOSS_TYPE\n # Inference parameters:\n self.score_threshold = cfg.MODEL.RETINANET.SCORE_THRESH_TEST\n self.topk_candidates = cfg.MODEL.RETINANET.TOPK_CANDIDATES_TEST\n self.nms_threshold = cfg.MODEL.RETINANET.NMS_THRESH_TEST\n self.max_detections_per_image = cfg.TEST.DETECTIONS_PER_IMAGE\n # Vis parameters\n self.vis_period = cfg.VIS_PERIOD\n self.input_format = cfg.INPUT.FORMAT\n # fmt: on\n\n self.backbone = build_backbone(cfg)\n\n backbone_shape = self.backbone.output_shape()\n feature_shapes = [backbone_shape[f] for f in self.in_features]\n self.head = RetinaNetHead(cfg, feature_shapes)\n self.anchor_generator = build_anchor_generator(cfg, feature_shapes)\n\n # Matching and loss\n self.box2box_transform = Box2BoxTransform(weights=cfg.MODEL.RETINANET.BBOX_REG_WEIGHTS)\n self.anchor_matcher = Matcher(\n cfg.MODEL.RETINANET.IOU_THRESHOLDS,\n cfg.MODEL.RETINANET.IOU_LABELS,\n allow_low_quality_matches=True,\n )\n\n self.register_buffer(\"pixel_mean\", torch.Tensor(cfg.MODEL.PIXEL_MEAN).view(-1, 1, 1))\n self.register_buffer(\"pixel_std\", torch.Tensor(cfg.MODEL.PIXEL_STD).view(-1, 1, 1))\n\n \"\"\"\n In Detectron1, loss is normalized by number of foreground samples in the batch.\n When batch size is 1 per GPU, #foreground has a large variance and\n using it lead to lower performance. Here we maintain an EMA of #foreground to\n stabilize the normalizer.\n \"\"\"\n self.loss_normalizer = 100 # initialize with any reasonable #fg that's not too small\n self.loss_normalizer_momentum = 0.9\n\n @property\n def device(self):\n return self.pixel_mean.device\n\n def visualize_training(self, batched_inputs, results):\n \"\"\"\n A function used to visualize ground truth images and final network predictions.\n It shows ground truth bounding boxes on the original image and up to 20\n predicted object bounding boxes on the original image.\n\n Args:\n batched_inputs (list): a list that contains input to the model.\n results (List[Instances]): a list of #images elements.\n \"\"\"\n from detectron2.utils.visualizer import Visualizer\n\n assert len(batched_inputs) == len(\n results\n ), \"Cannot visualize inputs and results of different sizes\"\n storage = get_event_storage()\n max_boxes = 20\n\n image_index = 0 # only visualize a single image\n img = batched_inputs[image_index][\"image\"]\n img = convert_image_to_rgb(img.permute(1, 2, 0), self.input_format)\n v_gt = Visualizer(img, None)\n v_gt = v_gt.overlay_instances(boxes=batched_inputs[image_index][\"instances\"].gt_boxes)\n anno_img = v_gt.get_image()\n processed_results = detector_postprocess(results[image_index], img.shape[0], img.shape[1])\n predicted_boxes = processed_results.pred_boxes.tensor.detach().cpu().numpy()\n\n v_pred = Visualizer(img, None)\n v_pred = v_pred.overlay_instances(boxes=predicted_boxes[0:max_boxes])\n prop_img = v_pred.get_image()\n vis_img = np.vstack((anno_img, prop_img))\n vis_img = vis_img.transpose(2, 0, 1)\n vis_name = f\"Top: GT bounding boxes; Bottom: {max_boxes} Highest Scoring Results\"\n storage.put_image(vis_name, vis_img)\n\n def forward(self, batched_inputs):\n \"\"\"\n Args:\n batched_inputs: a list, batched outputs of :class:`DatasetMapper` .\n Each item in the list contains the inputs for one image.\n For now, each item in the list is a dict that contains:\n\n * image: Tensor, image in (C, H, W) format.\n * instances: Instances\n\n Other information that's included in the original dicts, such as:\n\n * \"height\", \"width\" (int): the output resolution of the model, used in inference.\n See :meth:`postprocess` for details.\n Returns:\n dict[str: Tensor]:\n mapping from a named loss to a tensor storing the loss. Used during training only.\n \"\"\"\n images = self.preprocess_image(batched_inputs)\n features = self.backbone(images.tensor)\n features = [features[f] for f in self.in_features]\n\n anchors = self.anchor_generator(features)\n pred_logits, pred_anchor_deltas = self.head(features)\n # Transpose the Hi*Wi*A dimension to the middle:\n pred_logits = [permute_to_N_HWA_K(x, self.num_classes) for x in pred_logits]\n pred_anchor_deltas = [permute_to_N_HWA_K(x, 4) for x in pred_anchor_deltas]\n\n if self.training:\n assert \"instances\" in batched_inputs[0], \"Instance annotations are missing in training!\"\n gt_instances = [x[\"instances\"].to(self.device) for x in batched_inputs]\n\n gt_labels, gt_boxes = self.label_anchors(anchors, gt_instances)\n losses = self.losses(anchors, pred_logits, gt_labels, pred_anchor_deltas, gt_boxes)\n\n if self.vis_period > 0:\n storage = get_event_storage()\n if storage.iter % self.vis_period == 0:\n results = self.inference(\n anchors, pred_logits, pred_anchor_deltas, images.image_sizes\n )\n self.visualize_training(batched_inputs, results)\n\n return losses\n else:\n results = self.inference(anchors, pred_logits, pred_anchor_deltas, images.image_sizes)\n processed_results = []\n for results_per_image, input_per_image, image_size in zip(\n results, batched_inputs, images.image_sizes\n ):\n height = input_per_image.get(\"height\", image_size[0])\n width = input_per_image.get(\"width\", image_size[1])\n r = detector_postprocess(results_per_image, height, width)\n processed_results.append({\"instances\": r})\n return processed_results\n\n def losses(self, anchors, pred_logits, gt_labels, pred_anchor_deltas, gt_boxes):\n \"\"\"\n Args:\n anchors (list[Boxes]): a list of #feature level Boxes\n gt_labels, gt_boxes: see output of :meth:`RetinaNet.label_anchors`.\n Their shapes are (N, R) and (N, R, 4), respectively, where R is\n the total number of anchors across levels, i.e. sum(Hi x Wi x Ai)\n pred_logits, pred_anchor_deltas: both are list[Tensor]. Each element in the\n list corresponds to one level and has shape (N, Hi * Wi * Ai, K or 4).\n Where K is the number of classes used in `pred_logits`.\n\n Returns:\n dict[str, Tensor]:\n mapping from a named loss to a scalar tensor\n storing the loss. Used during training only. The dict keys are:\n \"loss_cls\" and \"loss_box_reg\"\n \"\"\"\n num_images = len(gt_labels)\n gt_labels = torch.stack(gt_labels) # (N, R)\n anchors = type(anchors[0]).cat(anchors).tensor # (R, 4)\n gt_anchor_deltas = [self.box2box_transform.get_deltas(anchors, k) for k in gt_boxes]\n gt_anchor_deltas = torch.stack(gt_anchor_deltas) # (N, R, 4)\n\n valid_mask = gt_labels >= 0\n pos_mask = (gt_labels >= 0) & (gt_labels != self.num_classes)\n num_pos_anchors = pos_mask.sum().item()\n get_event_storage().put_scalar(\"num_pos_anchors\", num_pos_anchors / num_images)\n self.loss_normalizer = self.loss_normalizer_momentum * self.loss_normalizer + (\n 1 - self.loss_normalizer_momentum\n ) * max(num_pos_anchors, 1)\n\n # classification and regression loss\n gt_labels_target = F.one_hot(gt_labels[valid_mask], num_classes=self.num_classes + 1)[\n :, :-1\n ] # no loss for the last (background) class\n loss_cls = sigmoid_focal_loss_jit(\n cat(pred_logits, dim=1)[valid_mask],\n gt_labels_target.to(pred_logits[0].dtype),\n alpha=self.focal_loss_alpha,\n gamma=self.focal_loss_gamma,\n reduction=\"sum\",\n )\n\n if self.box_reg_loss_type == \"smooth_l1\":\n loss_box_reg = smooth_l1_loss(\n cat(pred_anchor_deltas, dim=1)[pos_mask],\n gt_anchor_deltas[pos_mask],\n beta=self.smooth_l1_loss_beta,\n reduction=\"sum\",\n )\n elif self.box_reg_loss_type == \"giou\":\n pred_boxes = [\n self.box2box_transform.apply_deltas(k, anchors)\n for k in cat(pred_anchor_deltas, dim=1)\n ]\n loss_box_reg = giou_loss(\n torch.stack(pred_boxes)[pos_mask], torch.stack(gt_boxes)[pos_mask], reduction=\"sum\"\n )\n else:\n raise ValueError(f\"Invalid bbox reg loss type '{self.box_reg_loss_type}'\")\n\n return {\n \"loss_cls\": loss_cls / self.loss_normalizer,\n \"loss_box_reg\": loss_box_reg / self.loss_normalizer,\n }\n\n @torch.no_grad()\n def label_anchors(self, anchors, gt_instances):\n \"\"\"\n Args:\n anchors (list[Boxes]): A list of #feature level Boxes.\n The Boxes contains anchors of this image on the specific feature level.\n gt_instances (list[Instances]): a list of N `Instances`s. The i-th\n `Instances` contains the ground-truth per-instance annotations\n for the i-th input image.\n\n Returns:\n list[Tensor]:\n List of #img tensors. i-th element is a vector of labels whose length is\n the total number of anchors across all feature maps (sum(Hi * Wi * A)).\n Label values are in {-1, 0, ..., K}, with -1 means ignore, and K means background.\n list[Tensor]:\n i-th element is a Rx4 tensor, where R is the total number of anchors across\n feature maps. The values are the matched gt boxes for each anchor.\n Values are undefined for those anchors not labeled as foreground.\n \"\"\"\n anchors = Boxes.cat(anchors) # Rx4\n\n gt_labels = []\n matched_gt_boxes = []\n for gt_per_image in gt_instances:\n match_quality_matrix = pairwise_iou(gt_per_image.gt_boxes, anchors)\n matched_idxs, anchor_labels = self.anchor_matcher(match_quality_matrix)\n del match_quality_matrix\n\n if len(gt_per_image) > 0:\n matched_gt_boxes_i = gt_per_image.gt_boxes.tensor[matched_idxs]\n\n gt_labels_i = gt_per_image.gt_classes[matched_idxs]\n # Anchors with label 0 are treated as background.\n gt_labels_i[anchor_labels == 0] = self.num_classes\n # Anchors with label -1 are ignored.\n gt_labels_i[anchor_labels == -1] = -1\n else:\n matched_gt_boxes_i = torch.zeros_like(anchors.tensor)\n gt_labels_i = torch.zeros_like(matched_idxs) + self.num_classes\n\n gt_labels.append(gt_labels_i)\n matched_gt_boxes.append(matched_gt_boxes_i)\n\n return gt_labels, matched_gt_boxes\n\n def inference(self, anchors, pred_logits, pred_anchor_deltas, image_sizes):\n \"\"\"\n Arguments:\n anchors (list[Boxes]): A list of #feature level Boxes.\n The Boxes contain anchors of this image on the specific feature level.\n pred_logits, pred_anchor_deltas: list[Tensor], one per level. Each\n has shape (N, Hi * Wi * Ai, K or 4)\n image_sizes (List[torch.Size]): the input image sizes\n\n Returns:\n results (List[Instances]): a list of #images elements.\n \"\"\"\n results = []\n for img_idx, image_size in enumerate(image_sizes):\n pred_logits_per_image = [x[img_idx] for x in pred_logits]\n deltas_per_image = [x[img_idx] for x in pred_anchor_deltas]\n results_per_image = self.inference_single_image(\n anchors, pred_logits_per_image, deltas_per_image, tuple(image_size)\n )\n results.append(results_per_image)\n return results\n\n def inference_single_image(self, anchors, box_cls, box_delta, image_size):\n \"\"\"\n Single-image inference. Return bounding-box detection results by thresholding\n on scores and applying non-maximum suppression (NMS).\n\n Arguments:\n anchors (list[Boxes]): list of #feature levels. Each entry contains\n a Boxes object, which contains all the anchors in that feature level.\n box_cls (list[Tensor]): list of #feature levels. Each entry contains\n tensor of size (H x W x A, K)\n box_delta (list[Tensor]): Same shape as 'box_cls' except that K becomes 4.\n image_size (tuple(H, W)): a tuple of the image height and width.\n\n Returns:\n Same as `inference`, but for only one image.\n \"\"\"\n boxes_all = []\n scores_all = []\n class_idxs_all = []\n\n # Iterate over every feature level\n for box_cls_i, box_reg_i, anchors_i in zip(box_cls, box_delta, anchors):\n # (HxWxAxK,)\n predicted_prob = box_cls_i.flatten().sigmoid_()\n\n # Apply two filtering below to make NMS faster.\n # 1. Keep boxes with confidence score higher than threshold\n keep_idxs = predicted_prob > self.score_threshold\n predicted_prob = predicted_prob[keep_idxs]\n topk_idxs = torch.nonzero(keep_idxs, as_tuple=True)[0]\n\n # 2. Keep top k top scoring boxes only\n num_topk = min(self.topk_candidates, topk_idxs.size(0))\n # torch.sort is actually faster than .topk (at least on GPUs)\n predicted_prob, idxs = predicted_prob.sort(descending=True)\n predicted_prob = predicted_prob[:num_topk]\n topk_idxs = topk_idxs[idxs[:num_topk]]\n\n anchor_idxs = topk_idxs // self.num_classes\n classes_idxs = topk_idxs % self.num_classes\n\n box_reg_i = box_reg_i[anchor_idxs]\n anchors_i = anchors_i[anchor_idxs]\n # predict boxes\n predicted_boxes = self.box2box_transform.apply_deltas(box_reg_i, anchors_i.tensor)\n\n boxes_all.append(predicted_boxes)\n scores_all.append(predicted_prob)\n class_idxs_all.append(classes_idxs)\n\n boxes_all, scores_all, class_idxs_all = [\n cat(x) for x in [boxes_all, scores_all, class_idxs_all]\n ]\n keep = batched_nms(boxes_all, scores_all, class_idxs_all, self.nms_threshold)\n keep = keep[: self.max_detections_per_image]\n\n result = Instances(image_size)\n result.pred_boxes = Boxes(boxes_all[keep])\n result.scores = scores_all[keep]\n result.pred_classes = class_idxs_all[keep]\n return result\n\n def preprocess_image(self, batched_inputs):\n \"\"\"\n Normalize, pad and batch the input images.\n \"\"\"\n images = [x[\"image\"].to(self.device) for x in batched_inputs]\n images = [(x - self.pixel_mean) / self.pixel_std for x in images]\n images = ImageList.from_tensors(images, self.backbone.size_divisibility)\n return images\n\n\nclass RetinaNetHead(nn.Module):\n \"\"\"\n The head used in RetinaNet for object classification and box regression.\n It has two subnets for the two tasks, with a common structure but separate parameters.\n \"\"\"\n\n @configurable\n def __init__(\n self,\n *,\n input_shape: List[ShapeSpec],\n num_classes,\n num_anchors,\n conv_dims: List[int],\n norm=\"\",\n prior_prob=0.01,\n ):\n \"\"\"\n NOTE: this interface is experimental.\n\n Args:\n input_shape (List[ShapeSpec]): input shape\n num_classes (int): number of classes. Used to label background proposals.\n num_anchors (int): number of generated anchors\n conv_dims (List[int]): dimensions for each convolution layer\n norm (str or callable):\n Normalization for conv layers except for the two output layers.\n See :func:`detectron2.layers.get_norm` for supported types.\n prior_prob (float): Prior weight for computing bias\n \"\"\"\n super().__init__()\n\n if norm == \"BN\" or norm == \"SyncBN\":\n logger = logging.getLogger(__name__)\n logger.warn(\"Shared norm does not work well for BN, SyncBN, expect poor results\")\n\n cls_subnet = []\n bbox_subnet = []\n for in_channels, out_channels in zip([input_shape[0].channels] + conv_dims, conv_dims):\n cls_subnet.append(\n nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)\n )\n if norm:\n cls_subnet.append(get_norm(norm, out_channels))\n cls_subnet.append(nn.ReLU())\n bbox_subnet.append(\n nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)\n )\n if norm:\n bbox_subnet.append(get_norm(norm, out_channels))\n bbox_subnet.append(nn.ReLU())\n\n self.cls_subnet = nn.Sequential(*cls_subnet)\n self.bbox_subnet = nn.Sequential(*bbox_subnet)\n self.cls_score = nn.Conv2d(\n conv_dims[-1], num_anchors * num_classes, kernel_size=3, stride=1, padding=1\n )\n self.bbox_pred = nn.Conv2d(\n conv_dims[-1], num_anchors * 4, kernel_size=3, stride=1, padding=1\n )\n\n # Initialization\n for modules in [self.cls_subnet, self.bbox_subnet, self.cls_score, self.bbox_pred]:\n for layer in modules.modules():\n if isinstance(layer, nn.Conv2d):\n torch.nn.init.normal_(layer.weight, mean=0, std=0.01)\n torch.nn.init.constant_(layer.bias, 0)\n\n # Use prior in model initialization to improve stability\n bias_value = -(math.log((1 - prior_prob) / prior_prob))\n torch.nn.init.constant_(self.cls_score.bias, bias_value)\n\n @classmethod\n def from_config(cls, cfg, input_shape: List[ShapeSpec]):\n num_anchors = build_anchor_generator(cfg, input_shape).num_cell_anchors\n # fmt: on\n assert (\n len(set(num_anchors)) == 1\n ), \"Using different number of anchors between levels is not currently supported!\"\n num_anchors = num_anchors[0]\n\n return {\n \"input_shape\": input_shape,\n \"num_classes\": cfg.MODEL.RETINANET.NUM_CLASSES,\n \"conv_dims\": [input_shape[0].channels] * cfg.MODEL.RETINANET.NUM_CONVS,\n \"prior_prob\": cfg.MODEL.RETINANET.PRIOR_PROB,\n \"norm\": cfg.MODEL.RETINANET.NORM,\n \"num_anchors\": num_anchors,\n }\n\n def forward(self, features):\n \"\"\"\n Arguments:\n features (list[Tensor]): FPN feature map tensors in high to low resolution.\n Each tensor in the list correspond to different feature levels.\n\n Returns:\n logits (list[Tensor]): #lvl tensors, each has shape (N, AxK, Hi, Wi).\n The tensor predicts the classification probability\n at each spatial position for each of the A anchors and K object\n classes.\n bbox_reg (list[Tensor]): #lvl tensors, each has shape (N, Ax4, Hi, Wi).\n The tensor predicts 4-vector (dx,dy,dw,dh) box\n regression values for every anchor. These values are the\n relative offset between the anchor and the ground truth box.\n \"\"\"\n logits = []\n bbox_reg = []\n for feature in features:\n logits.append(self.cls_score(self.cls_subnet(feature)))\n bbox_reg.append(self.bbox_pred(self.bbox_subnet(feature)))\n return logits, bbox_reg\n" ]
[ [ "torch.nn.Sequential", "torch.Tensor", "torch.nn.init.constant_", "torch.nn.functional.one_hot", "torch.nn.Conv2d", "torch.zeros_like", "torch.no_grad", "torch.nn.init.normal_", "torch.nonzero", "torch.stack", "torch.nn.ReLU", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jnjaby/DISCNet
[ "63b1859519091f8790afcc47e8c726cbefdcd0fe" ]
[ "datasets/data_scripts/utils/torch_fft.py" ]
[ "\"\"\"\nCopyright (c) Facebook, Inc. and its affiliates.\n\nThis source code is licensed under the MIT license found in the\nLICENSE file in the root directory of this source tree.\nhttps://github.com/facebookresearch/fastMRI/blob/master/data/transforms.py\n\"\"\"\n\nimport numpy as np\nimport torch\n\n\ndef to_tensor(data):\n \"\"\"\n Convert numpy array to PyTorch tensor. For complex arrays, the real and imaginary parts\n are stacked along the last dimension.\n\n Args:\n data (np.array): Input numpy array\n\n Returns:\n torch.Tensor: PyTorch version of data\n \"\"\"\n if np.iscomplexobj(data):\n data = np.stack((data.real, data.imag), axis=-1)\n return torch.from_numpy(data)\n\n\ndef apply_mask(data, mask_func, seed=None):\n \"\"\"\n Subsample given k-space by multiplying with a mask.\n\n Args:\n data (torch.Tensor): The input k-space data. This should have at least 3 dimensions, where\n dimensions -3 and -2 are the spatial dimensions, and the final dimension has size\n 2 (for complex values).\n mask_func (callable): A function that takes a shape (tuple of ints) and a random\n number seed and returns a mask.\n seed (int or 1-d array_like, optional): Seed for the random number generator.\n\n Returns:\n (tuple): tuple containing:\n masked data (torch.Tensor): Subsampled k-space data\n mask (torch.Tensor): The generated mask\n \"\"\"\n shape = np.array(data.shape)\n shape[:-3] = 1\n mask = mask_func(shape, seed)\n return torch.where(mask == 0, torch.Tensor([0]), data), mask\n\n\ndef fft2(data):\n \"\"\"\n Apply centered 2 dimensional Fast Fourier Transform.\n\n Args:\n data (torch.Tensor): Complex valued input data containing at least 3 dimensions: dimensions\n -3 & -2 are spatial dimensions and dimension -1 has size 2. All other dimensions are\n assumed to be batch dimensions.\n\n Returns:\n torch.Tensor: The FFT of the input.\n \"\"\"\n assert data.size(-1) == 2\n data = ifftshift(data, dim=(-3, -2))\n data = torch.fft(data, 2, normalized=True)\n data = fftshift(data, dim=(-3, -2))\n return data\n\n\ndef ifft2(data):\n \"\"\"\n Apply centered 2-dimensional Inverse Fast Fourier Transform.\n\n Args:\n data (torch.Tensor): Complex valued input data containing at least 3 dimensions: dimensions\n -3 & -2 are spatial dimensions and dimension -1 has size 2. All other dimensions are\n assumed to be batch dimensions.\n\n Returns:\n torch.Tensor: The IFFT of the input.\n \"\"\"\n assert data.size(-1) == 2\n data = ifftshift(data, dim=(-3, -2))\n data = torch.ifft(data, 2, normalized=True)\n data = fftshift(data, dim=(-3, -2))\n return data\n\ndef rfft2(data):\n \"\"\"\n Apply centered 2-dimensional Real-to-Complex Fast Fourier Transform.\n\n Args:\n data (torch.Tensor): Real valued input data containing at least 2 dimensions: dimensions\n -2 & -1 are spatial dimensions. All other dimensions are\n assumed to be batch dimensions.\n\n Returns:\n torch.Tensor: The FFT of the input where dimensions -3 & -2 are now spatial dimensions \n and dimension -1 has size 2 for real & complex values.\n \"\"\"\n assert data.size(-1) != 1\n data = ifftshift(data, dim=(-2, -1))\n data = torch.rfft(data, 2, onesided=False)\n data = fftshift(data, dim=(-3, -2))\n return data\n\ndef irfft2(data):\n \"\"\"\n Apply centered 2-dimensional Complex-to-Real Inverse Fast Fourier Transform.\n\n Args:\n data (torch.Tensor): Complex valued input data containing at least 3 dimensions: dimensions\n -3 & -2 are spatial dimensions and dimension -1 has size 2. All other dimensions are\n assumed to be batch dimensions.\n\n Returns:\n torch.Tensor: The IFFT of the input where dimensions -2 & -1 are now spatial dimensions.\n \"\"\"\n assert data.size(-1) == 2\n data = ifftshift(data, dim=(-3,-2))\n data = torch.irfft(data, 2, onesided=False)\n data = fftshift(data, dim=(-2,-1))\n return data\n\ndef complex_abs(data):\n \"\"\"\n Compute the absolute value of a complex valued input tensor.\n\n Args:\n data (torch.Tensor): A complex valued tensor, where the size of the final dimension\n should be 2.\n\n Returns:\n torch.Tensor: Absolute value of data\n \"\"\"\n assert data.size(-1) == 2\n return (data ** 2).sum(dim=-1).sqrt()\n\n\ndef root_sum_of_squares(data, dim=0):\n \"\"\"\n Compute the Root Sum of Squares (RSS) transform along a given dimension of a tensor.\n\n Args:\n data (torch.Tensor): The input tensor\n dim (int): The dimensions along which to apply the RSS transform\n\n Returns:\n torch.Tensor: The RSS value\n \"\"\"\n return torch.sqrt((data ** 2).sum(dim))\n\n\ndef center_crop(data, shape):\n \"\"\"\n Apply a center crop to the input real image or batch of real images.\n\n Args:\n data (torch.Tensor): The input tensor to be center cropped. It should have at\n least 2 dimensions and the cropping is applied along the last two dimensions.\n shape (int, int): The output shape. The shape should be smaller than the\n corresponding dimensions of data.\n\n Returns:\n torch.Tensor: The center cropped image\n \"\"\"\n assert 0 < shape[0] <= data.shape[-2]\n assert 0 < shape[1] <= data.shape[-1]\n w_from = (data.shape[-2] - shape[0]) // 2\n h_from = (data.shape[-1] - shape[1]) // 2\n w_to = w_from + shape[0]\n h_to = h_from + shape[1]\n return data[..., w_from:w_to, h_from:h_to]\n\n\ndef complex_center_crop(data, shape):\n \"\"\"\n Apply a center crop to the input image or batch of complex images.\n\n Args:\n data (torch.Tensor): The complex input tensor to be center cropped. It should\n have at least 3 dimensions and the cropping is applied along dimensions\n -3 and -2 and the last dimensions should have a size of 2.\n shape (int, int): The output shape. The shape should be smaller than the\n corresponding dimensions of data.\n\n Returns:\n torch.Tensor: The center cropped image\n \"\"\"\n assert 0 < shape[0] <= data.shape[-3]\n assert 0 < shape[1] <= data.shape[-2]\n w_from = (data.shape[-3] - shape[0]) // 2\n h_from = (data.shape[-2] - shape[1]) // 2\n w_to = w_from + shape[0]\n h_to = h_from + shape[1]\n return data[..., w_from:w_to, h_from:h_to, :]\n\n\ndef normalize(data, mean, stddev, eps=0.):\n \"\"\"\n Normalize the given tensor using:\n (data - mean) / (stddev + eps)\n\n Args:\n data (torch.Tensor): Input data to be normalized\n mean (float): Mean value\n stddev (float): Standard deviation\n eps (float): Added to stddev to prevent dividing by zero\n\n Returns:\n torch.Tensor: Normalized tensor\n \"\"\"\n return (data - mean) / (stddev + eps)\n\n\ndef normalize_instance(data, eps=0.):\n \"\"\"\n Normalize the given tensor using:\n (data - mean) / (stddev + eps)\n where mean and stddev are computed from the data itself.\n\n Args:\n data (torch.Tensor): Input data to be normalized\n eps (float): Added to stddev to prevent dividing by zero\n\n Returns:\n torch.Tensor: Normalized tensor\n \"\"\"\n mean = data.mean()\n std = data.std()\n return normalize(data, mean, std, eps), mean, std\n\n\n# Helper functions\n\ndef roll(x, shift, dim):\n \"\"\"\n Similar to np.roll but applies to PyTorch Tensors\n \"\"\"\n if isinstance(shift, (tuple, list)):\n assert len(shift) == len(dim)\n for s, d in zip(shift, dim):\n x = roll(x, s, d)\n return x\n shift = shift % x.size(dim)\n if shift == 0:\n return x\n left = x.narrow(dim, 0, x.size(dim) - shift)\n right = x.narrow(dim, x.size(dim) - shift, shift)\n return torch.cat((right, left), dim=dim)\n\n\ndef fftshift(x, dim=None):\n \"\"\"\n Similar to np.fft.fftshift but applies to PyTorch Tensors\n \"\"\"\n if dim is None:\n dim = tuple(range(x.dim()))\n shift = [dim // 2 for dim in x.shape]\n elif isinstance(dim, int):\n shift = x.shape[dim] // 2\n else:\n shift = [x.shape[i] // 2 for i in dim]\n return roll(x, shift, dim)\n\n\ndef ifftshift(x, dim=None):\n \"\"\"\n Similar to np.fft.ifftshift but applies to PyTorch Tensors\n \"\"\"\n if dim is None:\n dim = tuple(range(x.dim()))\n shift = [(dim + 1) // 2 for dim in x.shape]\n elif isinstance(dim, int):\n shift = (x.shape[dim] + 1) // 2\n else:\n shift = [(x.shape[i] + 1) // 2 for i in dim]\n return roll(x, shift, dim)\n" ]
[ [ "torch.Tensor", "torch.cat", "torch.from_numpy", "numpy.stack", "torch.rfft", "numpy.iscomplexobj", "numpy.array", "torch.ifft", "torch.fft", "torch.irfft" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
stootaghaj/NDNetGaming
[ "326b0ef022704204cbeafb471ba5e9697cfdfe5f" ]
[ "Training/mini.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 21 10:49:01 2018\n\n@author: utke.markus\n\"\"\"\n\nimport numpy as np\nnp.random.seed(7)\nfrom scipy import stats\nfrom sklearn import metrics\nfrom sklearn import ensemble\nfrom sklearn import svm\nimport tensorflow as tf\ntf.Session()\ntf.set_random_seed(9)\nfrom keras.activations import relu\nfrom keras.layers import Dense, Conv2D, Flatten, GlobalMaxPooling2D, GlobalAveragePooling2D\nfrom keras.models import Model, Sequential\nfrom keras.optimizers import Adam, SGD\nfrom keras.callbacks import Callback, TerminateOnNaN\nfrom keras import initializers\nfrom keras.applications import imagenet_utils\nfrom keras.utils import to_categorical\nfrom keras.metrics import categorical_accuracy\nimport keras.backend as K\nimport matplotlib.pyplot as plt\nimport time\nfrom importData import DataSequenceNew\n\n\ndef getMetrics(yPred, y, mode = 'regression', verbose = True):\n if mode == 'regression':\n r2 = metrics.r2_score(y, yPred)\n rmse = np.sqrt(metrics.mean_squared_error(y, yPred))\n pcc = stats.pearsonr(y, yPred)[0]\n srcc = stats.spearmanr(y, yPred)[0]\n if verbose:\n print(\"R²: %1.4f \\t RMSE: %1.4f \\t PCC: %1.4f \\t SRCC: %1.4f\" % (r2, rmse, pcc, srcc))\n return r2, rmse, pcc, srcc\n elif mode == 'classification':\n acc = metrics.accuracy_score(np.argmax(y, axis = -1), np.argmax(yPred, axis = -1))\n if verbose:\n print(\"Accuracy: %1.4f\" % (acc))\n return acc\n \n\n#%%\n\npatchSize = 299\nnPatches = 1\nmodel = Sequential()\nconv1 = Conv2D(10, (5,5), activation='relu', input_shape=(patchSize,patchSize,3))\nconv2 = Conv2D(15, (3,3), activation='relu')\npool = GlobalMaxPooling2D()\n#model.add(Flatten())\nmodel.add(conv1)\nmodel.add(conv2)\nmodel.add(pool)\nmodel.add(Dense(3, activation='relu'))\nmodel.add(Dense(1, activation='linear'))\nmodel.summary()\n#setTrainability(model, 204)#+5*10) \n\n\n#sgd = SGD(lr = 0.001, momentum = 0.0, decay = 0.0)\nmodel.compile(loss = 'mean_squared_error', optimizer = 'adam')\n#print(model.summary())\n\n\nfilepath = \"D:\\\\All\\\\\"\nfilepathTest = \"D:\\\\All\\\\\"\n\ntrainIndexes = np.arange(390)\ntestIndexes = np.hstack((np.arange(18, 33), np.arange(191, 209), np.arange(69, 105), np.arange(272, 282)))#np.hstack((np.arange(105, 140), np.arange(209, 239), np.arange(282, 318)))\ntrainIndexes = np.delete(trainIndexes, testIndexes)\n\nnTrainVideos = len(trainIndexes)\nnTestVideos = len(testIndexes)\n\n# Test: CSGO/2, Hearthstone/2, Dota, ProjectCar # CSGO, Hearthstone, LoL, Fifa, HeroesOfTheStorm, PU\n\nbatchSize = 64\neverynthTrain = 53\neverynthTest = 23\n\n#%%\n#class LossHistory(Callback):\n# def on_train_begin(self, logs={}):\n# self.losses = []\n#\n# def on_batch_end(self, batch, logs={}):\n# self.losses.append(logs.get('loss'))\n\n\ndef preprocess_input(X):\n return X/255.\n\n\nclass validationCallback(Callback): #TODO pass test indexes, nPatches\n def on_train_begin(self, logs={}):\n self.testIndexes = testIndexes\n self.nPatches = nPatches\n self.metricsPerFrame = []\n self.metricsPerVideo = []\n self.preds = []\n self.dsTest = DataSequenceNew(filepathTest, self.testIndexes, patchSize = patchSize, everynth = everynthTest, batchSize = 10, preprocess = preprocess_input, shuffle = False, returnMode = 2, nPatches = self.nPatches) \n yTest = []\n for i in range(self.dsTest.__len__()):\n yTest.append(self.dsTest.__getitem__(i))\n yTest = np.concatenate(yTest)\n self.yTestPerPic = yTest[::self.nPatches]\n self.dsTest.switchTestReturnMode()\n \n def on_epoch_end(self, epoch, logs={}):\n predTest = self.model.predict_generator(self.dsTest) \n predTestPerPic = np.mean(predTest.reshape((-1,self.nPatches)), axis = -1)\n self.preds.append(predTestPerPic)\n self.metricsPerFrame.append(getMetrics(predTestPerPic, self.yTestPerPic, verbose=True))\n self.metricsPerVideo.append(getMetrics(np.mean(predTestPerPic.reshape((len(self.testIndexes),-1)), axis=-1),np.mean(self.yTestPerPic.reshape((len(self.testIndexes),-1)), axis=-1), verbose=True))\n if np.argmin(np.array(self.metricsPerFrame)[:,1]) == epoch:\n print(\"New Best Epoch: %i\" % epoch)\n self.model.save(\"Results\\denseNet204every53thNewTest_best.model\")\n self.bestEpoch = epoch\n\n\n#%%\n\nvalidationLossHistory = validationCallback()\n#lossHistory = LossHistory()\n\ndsa = DataSequenceNew(filepath, trainIndexes, patchSize = patchSize, nPatches = nPatches,\n everynth = everynthTrain, batchSize = 16, preprocess = preprocess_input)\ntime1 = time.time()\nmodel.fit_generator(dsa, steps_per_epoch = None, epochs = 5, verbose = 1, callbacks=[validationLossHistory])#, lossHistory, TerminateOnNaN()])\ntime2 = time.time() - time1\n\n\n\n#%%\n#plt.figure()\n#plt.plot(lossHistory.losses)\n\nplt.rcParams.update({'font.size': 12})\nyTest = validationLossHistory.yTestPerPic\nplt.figure(figsize = (7,8))\ni = 2\nplt.plot(yTest , validationLossHistory.preds[i], 'co', markersize = .8) \nplt.plot(np.mean(yTest.reshape((nTestVideos,-1)), axis=-1),np.mean(validationLossHistory.preds[i].reshape((nTestVideos,-1)), axis=-1), 'go', markersize = 4)\nplt.plot(np.arange(101), 'k')\nplt.xlim((-10,110))\nplt.ylim((-10,110))\n#plt.title(\"Epoch %i\" % (i))\nplt.xlabel(\"Real VMAF\")\nplt.ylabel(\"Predicted VMAF\")\nplt.legend([\"Frame level\", \"Video level\"], loc = 2)\nplt.text(0, -35, \"Frame Level: R²: %1.2f RMSE: %1.2f PCC: %1.3f SRCC: %1.3f\" % validationLossHistory.metricsPerFrame[i])\nplt.text(0, -42, \"Video Level: R²: %1.2f RMSE: %1.2f PCC: %1.3f SRCC: %1.3f\" % validationLossHistory.metricsPerVideo[i])\nplt.subplots_adjust(bottom=.2)\n#plt.savefig(\"Results\\\\denseNet204every53thNewTest_epoch%i.png\" % (i), bbox_inches = 'tight')\n#plt.clf()\n#%%\n#np.save(\"Results\\\\denseNet204every53thNewTest_epoch%i\", validationLossHistory.preds[i])\n#%%\n\nweights = model.get_weights()\nkernels = weights[0]\n#kernels = weights[2]\n\nfig, axes = plt.subplots(nrows=3, ncols=5, figsize=(10, 6))\n\nfor (i, ax) in enumerate(axes.flat):\n ax.set_axis_off()\n im = ax.imshow(kernels[:,:,0,i], cmap='bwr_r',\n vmin=np.min(kernels), vmax=np.max(kernels))\n\n# notice that here we use ax param of figure.colorbar method instead of\n\n# the cax param as the above example\n\ncbar = fig.colorbar(im, ax=axes.ravel().tolist(), shrink=0.95)\n\n\nplt.show()\n\n\n#%%\n\nmodelPart = Sequential()\n#conv1 = Conv2D(10, (5,5), activation='relu', input_shape=(patchSize,patchSize,3))\n#conv2 = Conv2D(15, (3,3), activation='relu')\n#pool = GlobalMaxPooling2D()\n#model.add(Flatten())\nmodelPart.add(conv1)\nmodelPart.add(conv2)\nmodelPart.add(pool)\nmodelPart.summary()\n\n#%%\n\ndsPart = DataSequenceNew(filepath, trainIndexes, patchSize = 299, everynth = 53, batchSize = 64, preprocess = preprocess_input, shuffle = False, returnMode = 2, nPatches = nPatches, patchMode='random') \nyPart = []\nfor i in range(dsPart.__len__()):\n yPart.append(dsPart.__getitem__(i))\nyPart = np.concatenate(yPart)\nyPart = yPart[::nPatches]\ndsPart.switchTestReturnMode()\n\nxPart = modelPart.predict_generator(dsPart, verbose=1)\n\n#%%\n\ndsPartTest = DataSequenceNew(filepath, testIndexes, patchSize = 299, everynth = 53, batchSize = 64, preprocess = preprocess_input, shuffle = False, returnMode = 2, nPatches = nPatches, patchMode='random') \nyPartTest = []\nfor i in range(dsPartTest.__len__()):\n yPartTest.append(dsPartTest.__getitem__(i))\nyPartTest = np.concatenate(yPartTest)\nyPartTest = yPartTest[::nPatches]\ndsPartTest.switchTestReturnMode()\n\nxPartTest = modelPart.predict_generator(dsPartTest, verbose=1)\n\n#%%\nfrom sklearn.ensemble import RandomForestRegressor\n\nsvr = RandomForestRegressor(n_estimators=100, max_depth=None, max_features='auto', n_jobs=4, verbose=1)\n\nsvr.fit(xPart, yPart)\n\nyPartTestPred = svr.predict(xPartTest)\n\nyPartTrainPred = svr.predict(xPart)\n#%%\n\n\nplt.rcParams.update({'font.size': 12})\nplt.figure(figsize = (7,8))\ni = 2\nplt.plot(yPartTest, yPartTestPred, 'co', markersize = .8) \nplt.plot(np.mean(yPartTest.reshape((nTestVideos,-1)), axis=-1),np.mean(yPartTestPred.reshape((nTestVideos,-1)), axis=-1), 'go', markersize = 4)\nplt.plot(np.arange(101), 'k')\nplt.xlim((-10,110))\nplt.ylim((-10,110))\n#plt.title(\"Epoch %i\" % (i))\nplt.xlabel(\"Real VMAF\")\nplt.ylabel(\"Predicted VMAF\")\nplt.legend([\"Frame level\", \"Video level\"], loc = 2)\nplt.text(0, -35, \"Frame Level: R²: %1.2f RMSE: %1.2f PCC: %1.3f SRCC: %1.3f\" % getMetrics(yPartTestPred, yPartTest))\nplt.text(0, -42, \"Video Level: R²: %1.2f RMSE: %1.2f PCC: %1.3f SRCC: %1.3f\" % (1,2,3,4))\nplt.subplots_adjust(bottom=.2)\n\n#%%\n\n\nplt.rcParams.update({'font.size': 12})\nplt.figure(figsize = (7,8))\ni = 2\nplt.plot(yPart, yPartTrainPred, 'co', markersize = .8) \nplt.plot(np.mean(yPart.reshape((nTrainVideos,-1)), axis=-1),np.mean(yPartTrainPred.reshape((nTrainVideos,-1)), axis=-1), 'go', markersize = 4)\nplt.plot(np.arange(101), 'k')\nplt.xlim((-10,110))\nplt.ylim((-10,110))\n#plt.title(\"Epoch %i\" % (i))\nplt.xlabel(\"Real VMAF\")\nplt.ylabel(\"Predicted VMAF\")\nplt.legend([\"Frame level\", \"Video level\"], loc = 2)\nplt.text(0, -35, \"Frame Level: R²: %1.2f RMSE: %1.2f PCC: %1.3f SRCC: %1.3f\" % getMetrics(yPartTrainPred, yPart))\nplt.text(0, -42, \"Video Level: R²: %1.2f RMSE: %1.2f PCC: %1.3f SRCC: %1.3f\" % (1,2,3,4))\nplt.subplots_adjust(bottom=.2)" ]
[ [ "sklearn.ensemble.RandomForestRegressor", "matplotlib.pyplot.legend", "sklearn.metrics.r2_score", "sklearn.metrics.mean_squared_error", "matplotlib.pyplot.plot", "numpy.concatenate", "numpy.max", "scipy.stats.spearmanr", "matplotlib.pyplot.rcParams.update", "numpy.arange", "numpy.argmax", "tensorflow.Session", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.text", "matplotlib.pyplot.figure", "numpy.min", "matplotlib.pyplot.ylim", "scipy.stats.pearsonr", "numpy.delete", "tensorflow.set_random_seed", "matplotlib.pyplot.show", "numpy.array", "matplotlib.pyplot.ylabel", "numpy.random.seed", "matplotlib.pyplot.subplots", "matplotlib.pyplot.xlim", "matplotlib.pyplot.xlabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "1.3", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16", "1.8" ], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
bramgibs/tomopy
[ "2aa00814025d6c63c87d9a928de3d92b13c74dd7" ]
[ "tomopy/util/misc.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# #########################################################################\n# Copyright (c) 2015, UChicago Argonne, LLC. All rights reserved. #\n# #\n# Copyright 2015. UChicago Argonne, LLC. This software was produced #\n# under U.S. Government contract DE-AC02-06CH11357 for Argonne National #\n# Laboratory (ANL), which is operated by UChicago Argonne, LLC for the #\n# U.S. Department of Energy. The U.S. Government has rights to use, #\n# reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR #\n# UChicago Argonne, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR #\n# ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is #\n# modified to produce derivative works, such modified software should #\n# be clearly marked, so as not to confuse it with the version available #\n# from ANL. #\n# #\n# Additionally, redistribution and use in source and binary forms, with #\n# or without modification, are permitted provided that the following #\n# conditions are met: #\n# #\n# * Redistributions of source code must retain the above copyright #\n# notice, this list of conditions and the following disclaimer. #\n# #\n# * Redistributions in binary form must reproduce the above copyright #\n# notice, this list of conditions and the following disclaimer in #\n# the documentation and/or other materials provided with the #\n# distribution. #\n# #\n# * Neither the name of UChicago Argonne, LLC, Argonne National #\n# Laboratory, ANL, the U.S. Government, nor the names of its #\n# contributors may be used to endorse or promote products derived #\n# from this software without specific prior written permission. #\n# #\n# THIS SOFTWARE IS PROVIDED BY UChicago Argonne, LLC AND CONTRIBUTORS #\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS #\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UChicago #\n# Argonne, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, #\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, #\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; #\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER #\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT #\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN #\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #\n# POSSIBILITY OF SUCH DAMAGE. #\n# #########################################################################\n\n\"\"\"\nModule for internal utility functions.\n\"\"\"\n\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport logging\nimport warnings\nfrom .. import fft_impl\n\n\n\nlogger = logging.getLogger(__name__)\n\n\n__author__ = \"Doga Gursoy\"\n__copyright__ = \"Copyright (c) 2016, UChicago Argonne, LLC.\"\n__docformat__ = 'restructuredtext en'\n__all__ = ['deprecated', 'fft2', 'ifft2', 'fft', 'ifft']\n\n\ndef deprecated(func, msg=None):\n \"\"\"\n This is a decorator which can be used to mark functions\n as deprecated. It will result in a warning being emitted\n when the function is used.\n \"\"\"\n def new_func(*args, **kwargs):\n warnings.simplefilter('once', DeprecationWarning)\n warnings.warn(\n \"Deprecated function {}.\".format(func.__name__), category=DeprecationWarning)\n return func(*args, **kwargs)\n\n new_func.__name__ = func.__name__\n new_func.__doc__ = func.__doc__\n new_func.__dict__.update(func.__dict__)\n return new_func\n\n\nif fft_impl == 'mkl_fft':\n import mkl_fft\n def fft(x, n=None, axis=-1, overwrite_input=False, extra_info=None):\n return mkl_fft.fft(x, n=n, axis=axis, overwrite_x=overwrite_input)\n\n\n def ifft(x, n=None, axis=-1, overwrite_input=False, extra_info=None):\n return mkl_fft.ifft(x, n=n, axis=axis, overwrite_x=overwrite_input)\n\n\n def fft2(x, s=None, axes=(-2,-1), overwrite_input=False, extra_info=None):\n return mkl_fft.fft2(x, shape=s, axes=axes, overwrite_x=overwrite_input)\n\n\n def ifft2(x, s=None, axes=(-2,-1), overwrite_input=False, extra_info=None):\n return mkl_fft.ifft2(x, shape=s, axes=axes, overwrite_x=overwrite_input)\n\nelif fft_impl == 'pyfftw':\n import pyfftw\n def _plan_effort(num_jobs):\n if not num_jobs:\n return 'FFTW_MEASURE'\n if num_jobs > 10:\n return 'FFTW_MEASURE'\n else:\n return 'FFTW_ESTIMATE'\n\n def fft(x, n=None, axis=-1, overwrite_input=False, extra_info=None):\n return pyfftw.interfaces.numpy_fft.fft(x, n=n, axis=axis,\n overwrite_input=overwrite_input,\n planner_effort=_plan_effort(extra_info))\n \n\n def ifft(x, n=None, axis=-1, overwrite_input=False, extra_info=None):\n return pyfftw.interfaces.numpy_fft.ifft(x, n=n, axis=axis,\n overwrite_input=overwrite_input,\n planner_effort=_plan_effort(extra_info))\n\n\n def fft2(x, s=None, axes=(-2,-1), overwrite_input=False, extra_info=None):\n return pyfftw.interfaces.numpy_fft.fft2(x, s=s, axes=axes,\n overwrite_input=overwrite_input,\n planner_effort=_plan_effort(extra_info))\n \n\n def ifft2(x, s=None, axes=(-2,-1), overwrite_input=False, extra_info=None):\n return pyfftw.interfaces.numpy_fft.ifft2(x, s=s, axes=axes,\n overwrite_input=overwrite_input,\n planner_effort=_plan_effort(extra_info))\n\nelse:\n import numpy as np\n def fft(x, n=None, axis=-1, overwrite_input=False, extra_info=None):\n return np.fft.fft(x, n=n, axis=axis)\n\n\n def ifft(x, n=None, axis=-1, overwrite_input=False, extra_info=None):\n return np.fft.ifft(x, n=n, axis=axis)\n\n\n def fft2(x, s=None, axes=(-2,-1), overwrite_input=False, extra_info=None):\n return np.fft.fft2(x, s=s, axes=axes)\n\n\n def ifft2(x, s=None, axes=(-2,-1), overwrite_input=False, extra_info=None):\n return np.fft.ifft2(x, s=s, axes=axes)\n" ]
[ [ "numpy.fft.fft2", "numpy.fft.ifft", "numpy.fft.ifft2", "numpy.fft.fft" ] ]
[ { "matplotlib": [], "numpy": [ "1.11", "1.10", "1.12", "1.19", "1.13", "1.16", "1.9", "1.18", "1.21", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
paulaurel/exptorch
[ "3394a7120a39261481e9435247ab5aa107a8ee21" ]
[ "examples/models.py" ]
[ "import torch\nfrom torch import nn\n\nfrom exptorch.utils.itertools import pairwise\n\n\nclass LinearNet(nn.Module):\n \"\"\"Linear feed-forward neural network, i.e. linear regression model.\"\"\"\n\n def __init__(self, input_dim, output_dim):\n super().__init__()\n self.linear = nn.Linear(input_dim, output_dim)\n\n def forward(self, x):\n return self.linear(x)\n\n def training_step(self, batch, batch_idx, loss_criterion):\n x, y = batch\n y_pred = self.forward(x)\n return loss_criterion(y_pred, y), y_pred\n\n def configure_optimizers(self, optimizers: torch.optim, **kwargs):\n optimizer, *_ = optimizers\n return optimizer(self.parameters(), **kwargs)\n\n\ndef get_mlp_layers(channels: list, activation, output_activation=nn.Identity):\n \"\"\"Define basic multilayered perceptron network architecture.\"\"\"\n layers = []\n *intermediate_layer_definitions, final_layer_definition = pairwise(channels)\n\n for in_ch, out_ch in intermediate_layer_definitions:\n intermediate_layer = nn.Linear(in_ch, out_ch)\n layers += [intermediate_layer, activation()]\n\n layers += [nn.Linear(*final_layer_definition), output_activation()]\n return nn.Sequential(*layers)\n\n\nclass MLP(nn.Module):\n \"\"\"Multi-layered perceptron network.\"\"\"\n\n def __init__(\n self, input_dim: int, output_dim: int, channels: list, activation=nn.ReLU\n ):\n super().__init__()\n mlp_channels = [input_dim] + channels + [output_dim]\n self.net = get_mlp_layers(mlp_channels, activation)\n\n def forward(self, x):\n return self.net(x)\n\n def training_step(self, batch, batch_idx, loss_criterion):\n x, y = batch\n x = x.view(x.shape[0], -1)\n y_pred = self.forward(x)\n return loss_criterion(y_pred, y), y_pred\n\n def configure_optimizers(self, optimizer: torch.optim, **kwargs):\n return optimizer(self.net.parameters(), **kwargs)\n" ]
[ [ "torch.nn.Linear", "torch.nn.Sequential" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jaisw7/shenfun
[ "7482beb5b35580bc45f72704b69343cc6fc1d773", "7482beb5b35580bc45f72704b69343cc6fc1d773" ]
[ "demo/fourier_poisson4D.py", "shenfun/chebyshev/la.py" ]
[ "r\"\"\"\nSolve Poisson equation on the 4-dimensional (0, 2pi)^4 with periodic bcs\n\n \\nabla^2 u = f,\n\nUse Fourier basis and find u in V^4 such that\n\n (v, div(grad(u))) = (v, f) for all v in V^4\n\nwhere V is the Fourier space span{exp(1jkx)}_{k=-N/2}^{N/2-1} and\nV^4 is a 4-dimensional tensorproductspace.\n\n\"\"\"\nimport os\nfrom sympy import symbols, cos, sin\nimport numpy as np\nfrom shenfun import inner, div, grad, TestFunction, TrialFunction, FunctionSpace, \\\n TensorProductSpace, Array, Function, dx, comm\n\n# Use sympy to compute a rhs, given an analytical solution\nx, y, z, r = symbols(\"x,y,z,r\", real=True)\nue = cos(4*x) + sin(4*y) + sin(6*z) + cos(6*r)\nfe = ue.diff(x, 2) + ue.diff(y, 2) + ue.diff(z, 2) + ue.diff(r, 2)\n\n# Size of discretization\nN = (8, 10, 12, 14)\n\nK0 = FunctionSpace(N[0], 'F', dtype='D')\nK1 = FunctionSpace(N[1], 'F', dtype='D')\nK2 = FunctionSpace(N[2], 'F', dtype='D')\nK3 = FunctionSpace(N[3], 'F', dtype='d')\nT = TensorProductSpace(comm, (K0, K1, K2, K3))\nu = TrialFunction(T)\nv = TestFunction(T)\n\n# Get f on quad points\nfj = Array(T, buffer=fe)\n\n# Compute right hand side\nf_hat = Function(T)\nf_hat = inner(v, fj, output_array=f_hat)\n\n# Solve Poisson equation\nA = inner(v, div(grad(u)))\nf_hat = A.solve(f_hat)\n\nuq = T.backward(f_hat)\n\nuj = Array(T, buffer=ue)\nprint(np.sqrt(dx((uj-uq)**2)))\nassert np.allclose(uj, uq)\n\nif 'pytest' not in os.environ and comm.Get_size() == 1:\n import matplotlib.pyplot as plt\n plt.figure()\n X = T.local_mesh(True) # With broadcasting=True the shape of X is local_shape, even though the number of datapoints are still the same as in 1D\n plt.contourf(X[0][:, :, 0, 0], X[1][:, :, 0, 0], uq[:, :, 0, 0])\n plt.colorbar()\n\n plt.figure()\n plt.contourf(X[0][:, :, 0, 0], X[1][:, :, 0, 0], uj[:, :, 0, 0])\n plt.colorbar()\n\n plt.figure()\n plt.contourf(X[0][:, :, 0, 0], X[1][:, :, 0, 0], uq[:, :, 0, 0]-uj[:, :, 0, 0])\n plt.colorbar()\n plt.title('Error')\n plt.show()\n", "#pylint: disable=line-too-long, missing-docstring\n\nfrom copy import copy\nimport numpy as np\nfrom shenfun.optimization import optimizer\nfrom shenfun.optimization.cython import la\nfrom shenfun.la import TDMA as la_TDMA\nfrom shenfun.matrixbase import TPMatrix\n\n\nclass TDMA(la_TDMA):\n\n def __call__(self, b, u=None, axis=0):\n\n if u is None:\n u = b\n else:\n assert u.shape == b.shape\n u[:] = b[:]\n\n if not self.dd.shape[0] == self.mat.shape[0]:\n self.init()\n\n self.TDMA_SymSolve(self.dd, self.ud, self.L, u, axis=axis)\n\n if self.mat.scale not in (1, 1.0):\n u /= self.mat.scale\n return u\n\n\nclass Helmholtz:\n r\"\"\"Helmholtz solver\n\n .. math::\n\n \\alpha u'' + \\beta u = b\n\n where :math:`u` is the solution, :math:`b` is the right hand side and\n :math:`\\alpha` and :math:`\\beta` are scalars, or arrays of scalars for\n a multidimensional problem.\n\n The user must provide mass and stiffness matrices with scale arrays\n :math:`(\\alpha/\\beta)` to each matrix. The matrices and scales can be\n provided as instances of :class:`.TPMatrix`, or :class:`.SpectralMatrix`.\n\n Parameters\n ----------\n A : :class:`.SpectralMatrix` or :class:`.TPMatrix`\n mass or stiffness matrix\n B : :class:`.SpectralMatrix` or :class:`.TPMatrix`\n mass or stiffness matrix\n\n scale_A : array, optional\n Scale array to stiffness matrix\n scale_B : array, optional\n Scale array to mass matrix\n\n The two matrices must be one stiffness and one mass matrix. Which is which\n will be found by inspection if only two arguments are provided. The scales\n :math:`\\alpha` and :math:`\\beta` must then be available as A.scale and\n B.scale.\n If four arguments are provided they must be in the order\n\n - stiffness matrix, mass matrix, scale stiffness, scale mass\n\n Attributes\n ----------\n axis : int\n The axis over which to solve for\n neumann : bool\n Whether or not bases are Neumann\n bc : BoundaryValues\n For Dirichlet problem with inhomogeneous boundary values\n\n Variables are extracted from the matrices\n\n The solver can be used along any axis of a multidimensional problem. For\n example, if the Chebyshev basis (Dirichlet or Neumann) is the last in a\n 3-dimensional TensorProductSpace, where the first two dimensions use Fourier,\n then the 1D Helmholtz equation arises when one is solving the 3D Poisson\n equation\n\n .. math::\n\n \\nabla^2 u = b\n\n With the spectral Galerkin method we multiply this equation with a test\n function (:math:`v`) and integrate (weighted inner product :math:`(\\cdot, \\cdot)_w`)\n over the domain\n\n .. math::\n\n (v, \\nabla^2 u)_w = (v, b)_w\n\n\n See :ref:`demo:poisson3d`\n for details, since it is actually quite involved. But basically, one\n obtains a linear algebra system to be solved along the :math:`z`-axis for\n all combinations of the two Fourier indices :math:`k` and :math:`l`\n\n .. math::\n\n (A_{mj} - (k^2 + l^2) B_{mj}) \\hat{u}[k, l, j] = (v, b)_w[k, l, m]\n\n Note that :math:`k` only varies along :math:`x`-direction, whereas :math:`l`\n varies along :math:`y`. To allow for Numpy broadcasting these two variables\n are stored as arrays of shape\n\n .. math::\n\n k : (N, 1, 1)\n\n l : (1, M, 1)\n\n Here it is assumed that the solution array :math:`\\hat{u}` has shape\n (N, M, P). Now, multiplying k array with :math:`\\hat{u}` is achieved as an\n elementwise multiplication\n\n .. math::\n\n k \\cdot \\hat{u}\n\n Numpy will then take care of broadcasting :math:`k` to an array of shape\n (N, M, P) before performing the elementwise multiplication. Likewise, the\n constant scale :math:`1` in front of the :math:`A_{mj}` matrix is\n stored with shape (1, 1, 1), and multiplying with :math:`\\hat{u}` is\n performed as if it was a scalar (as it here happens to be).\n\n This is where the scale arrays come from. :math:`\\alpha` is here\n :math:`1`, whereas :math:`\\beta` is :math:`(k^2+l^2)`. Note that\n :math:`k+l` is an array of shape (N, M, 1).\n\n \"\"\"\n def __init__(self, *args):\n\n args = list(args)\n for i, arg in enumerate(args):\n if hasattr(arg, 'is_bc_matrix'):\n if arg.is_bc_matrix():\n # For this particular case the boundary dofs contribution\n # to the right hand side is only nonzero for Fourier wavenumber\n # 0, so the contribution is in effect zero\n args.pop(i)\n break\n\n assert len(args) in (2, 4)\n A, B = args[0], args[1]\n M = {d.get_key(): d for d in (A, B)}\n self.A = A = M.get('ADDmat', M.get('ANNmat'))\n self.B = B = M.get('BDDmat', M.get('BNNmat'))\n\n if len(args) == 2:\n self.alfa = self.A.scale\n self.beta = self.B.scale\n if isinstance(self.A, TPMatrix):\n self.A = self.A.pmat\n self.B = self.B.pmat\n self.alfa *= self.A.scale\n self.beta *= self.B.scale\n elif len(args) == 4:\n self.alfa = args[2]\n self.beta = args[3]\n\n A, B = self.A, self.B\n B[2] = np.broadcast_to(B[2], A[2].shape)\n B[-2] = np.broadcast_to(B[-2], A[2].shape)\n v = A.testfunction[0]\n neumann = self.neumann = v.boundary_condition() == 'Neumann'\n self.axis = A.axis\n shape = [1]\n T = A.tensorproductspace\n if T is not None:\n shape = list(T.shape(True))\n shape[A.axis] = 1\n self.alfa = np.atleast_1d(self.alfa)\n self.beta = np.atleast_1d(self.beta)\n if not self.alfa.shape == shape:\n self.alfa = np.broadcast_to(self.alfa, shape).copy()\n if not self.beta.shape == shape:\n self.beta = np.broadcast_to(self.beta, shape).copy()\n\n shape[self.axis] = A.shape[0] + 2\n self.u0 = np.zeros(shape) # Diagonal entries of U\n self.u1 = np.zeros(shape) # Diagonal+2 entries of U\n self.u2 = np.zeros(shape) # Diagonal+4 entries of U\n self.L = np.zeros(shape) # The single nonzero row of L\n self.LU_Helmholtz(A, B, self.alfa, self.beta, neumann, self.u0,\n self.u1, self.u2, self.L, self.axis)\n\n @staticmethod\n @optimizer\n def LU_Helmholtz(A, B, As, Bs, neumann, u0, u1, u2, L, axis=0):\n raise NotImplementedError\n\n @staticmethod\n @optimizer\n def Solve_Helmholtz(b, u, neumann, u0, u1, u2, L, axis=0):\n raise NotImplementedError\n\n def __call__(self, u, b):\n \"\"\"Solve matrix problem\n\n Parameters\n ----------\n b : array\n Array of right hand side on entry and solution on exit unless\n u is provided.\n u : array\n Output array\n\n If b and u are multidimensional, then the axis over which to solve for is\n determined on creation of the class.\n\n \"\"\"\n self.Solve_Helmholtz(b, u, self.neumann, self.u0, self.u1, self.u2, self.L, self.axis)\n\n if self.A.testfunction[0].has_nonhomogeneous_bcs:\n self.A.testfunction[0].bc.set_boundary_dofs(u, True)\n\n return u\n\n def matvec(self, v, c):\n \"\"\"Matrix vector product c = dot(self, v)\n\n Parameters\n ----------\n v : array\n c : array\n\n Returns\n -------\n c : array\n \"\"\"\n assert self.neumann is False\n c[:] = 0\n self.Helmholtz_matvec(v, c, self.alfa, self.beta, self.A[0], self.A[2], self.B[0], self.axis)\n return c\n\n @staticmethod\n @optimizer\n def Helmholtz_matvec(v, b, alfa, beta, dd, ud, bd, axis=0):\n raise NotImplementedError(\"Use Cython or Numba\")\n\n\nclass Biharmonic:\n r\"\"\"Multidimensional Biharmonic solver for\n\n .. math::\n\n a_0 u'''' + \\alpha u'' + \\beta u = b\n\n where :math:`u` is the solution, :math:`b` is the right hand side and\n :math:`a_0, \\alpha` and :math:`\\beta` are scalars, or arrays of scalars for\n a multidimensional problem.\n\n The user must provide mass, stiffness and biharmonic matrices with\n associated scale arrays :math:`(a_0/\\alpha/\\beta)`. The matrices and scales\n can be provided in any order\n\n Parameters\n ----------\n S : :class:`.TPMatrix` or :class:`.SpectralMatrix`\n A : :class:`.TPMatrix` or :class:`.SpectralMatrix`\n B : :class:`.TPMatrix` or :class:`.SpectralMatrix`\n\n scale_S : array, optional\n scale_A : array, optional\n scale_B : array, optional\n\n If only three arguments are passed, then we decide which matrix is which\n through inspection. The three scale arrays must then be available as\n S.scale, A.scale, B.scale.\n If six arguments are provided they must be in order S, A, B, scale S,\n scale A, scale B.\n\n Variables are extracted from the matrices\n\n The solver can be used along any axis of a multidimensional problem. For\n example, if the Chebyshev basis (Biharmonic) is the last in a\n 3-dimensional TensorProductSpace, where the first two dimensions use Fourier,\n then the 1D equation listed above arises when one is solving the 3D biharmonic\n equation\n\n .. math::\n\n \\nabla^4 u = b\n\n With the spectral Galerkin method we multiply this equation with a test\n function (:math:`v`) and integrate (weighted inner product :math:`(\\cdot, \\cdot)_w`)\n over the domain\n\n .. math::\n\n (v, \\nabla^4 u)_w = (v, b)_w\n\n See `the Poisson problem <https://rawgit.com/spectralDNS/shenfun/master/docs/src/mekit17/pub/._shenfun_bootstrap004.html#sec:tensorproductspaces>`_\n for details, since it is actually quite involved. But basically, one obtains\n a linear algebra system to be solved along the :math:`z`-axis for all combinations\n of the two Fourier indices :math:`k` and :math:`l`\n\n .. math::\n\n (S_{mj} - 2(k^2 + l^2) A_{mj}) + (k^2 + l^2)^2 B_{mj}) \\hat{u}[k, l, j] = (v, b)_w[k, l, m]\n\n Note that :math:`k` only varies along :math:`x`-direction, whereas :math:`l` varies along\n :math:`y`. To allow for Numpy broadcasting these two variables are stored as arrays of\n shape\n\n .. math::\n\n k : (N, 1, 1)\n\n l : (1, M, 1)\n\n Here it is assumed that the solution array :math:`\\hat{u}` has shape\n (N, M, P). Now, multiplying :math:`k` array with :math:`\\hat{u}` is achieved as\n\n .. math::\n\n k \\cdot \\hat{u}\n\n Numpy will then take care of broadcasting :math:`k` to an array of shape (N, M, P)\n before performing the elementwise multiplication. Likewise, the constant\n scale :math:`1` in front of the :math:`A_{mj}` matrix is stored with\n shape (1, 1, 1), and multiplying with :math:`\\hat{u}` is performed as if it\n was a scalar (as it here happens to be).\n\n This is where the scale arrays in the signature to the Helmholt solver comes\n from. :math:`a_0` is here :math:`1`, whereas :math:`\\alpha` and\n :math:`\\beta` are :math:`-2(k^2+l^2)` and :math:`(k^2+l^2)^2`, respectively.\n Note that :math:`k+l` is an array of shape (N, M, 1).\n \"\"\"\n def __init__(self, *args):\n\n args = list(args)\n\n if isinstance(args[0], TPMatrix):\n args = [arg for arg in args if not arg.is_bc_matrix()]\n\n assert len(args) in (3, 6)\n\n S, A, B = args[0], args[1], args[2]\n M = {d.get_key(): d for d in (S, A, B)}\n self.S = M['SBBmat']\n self.A = M['ABBmat']\n self.B = M['BBBmat']\n\n if len(args) == 3:\n self.a0 = a0 = np.atleast_1d(self.S.scale).item()\n self.alfa = alfa = self.A.scale\n self.beta = beta = self.B.scale\n if isinstance(self.S, TPMatrix):\n self.S = self.S.pmat\n self.A = self.A.pmat\n self.B = self.B.pmat\n self.alfa *= self.A.scale\n self.beta *= self.B.scale\n elif len(args) == 6:\n self.a0 = a0 = args[3]\n self.alfa = alfa = args[4]\n self.beta = beta = args[5]\n\n S, A, B = self.S, self.A, self.B\n self.axis = S.axis\n T = S.tensorproductspace\n if T is None:\n shape = [S[0].shape]\n else:\n shape = list(T.shape(True))\n sii, siu, siuu = S[0], S[2], S[4]\n ail, aii, aiu = A[-2], A[0], A[2]\n bill, bil, bii, biu, biuu = B[-4], B[-2], B[0], B[2], B[4]\n M = sii[::2].shape[0]\n shape[S.axis] = M\n ss = copy(shape)\n ss.insert(0, 2)\n self.u0 = np.zeros(ss)\n self.u1 = np.zeros(ss)\n self.u2 = np.zeros(ss)\n self.l0 = np.zeros(ss)\n self.l1 = np.zeros(ss)\n self.ak = np.zeros(ss)\n self.bk = np.zeros(ss)\n\n self.LU_Biharmonic(a0, alfa, beta, sii, siu, siuu, ail, aii, aiu,\n bill, bil, bii, biu, biuu, self.u0, self.u1,\n self.u2, self.l0, self.l1, self.axis)\n self.Biharmonic_factor_pr(self.ak, self.bk, self.l0, self.l1, self.axis)\n\n @staticmethod\n @optimizer\n def LU_Biharmonic(a0, alfa, beta, sii, siu, siuu, ail, aii, aiu,\n bill, bil, bii, biu, biuu, u0, u1, u2, l0, l1, axis):\n raise NotImplementedError('Use Cython or Numba')\n\n @staticmethod\n @optimizer\n def Biharmonic_factor_pr(ak, bk, l0, l1, axis):\n raise NotImplementedError('Use Cython or Numba')\n\n @staticmethod\n @optimizer\n def Biharmonic_Solve(axis, b, u, u0, u1, u2, l0, l1, ak, bk, a0):\n raise NotImplementedError('Use Cython or Numba')\n\n @staticmethod\n @optimizer\n def Biharmonic_matvec(v, b, a0, alfa, beta,\n sii, siu, siuu, ail, aii, aiu,\n bill, bil, bii, biu, biuu, axis=0):\n raise NotImplementedError('Use Cython or Numba')\n\n def __call__(self, u, b):\n \"\"\"Solve matrix problem\n\n Parameters\n ----------\n b : array\n Array of right hand side on entry and solution on exit unless\n u is provided.\n u : array\n Output array\n\n If b and u are multidimensional, then the axis over which to solve for is\n determined on creation of the class.\n\n \"\"\"\n self.Biharmonic_Solve(b, u, self.u0, self.u1, self.u2, self.l0,\n self.l1, self.ak, self.bk, self.a0, self.axis)\n if self.S.testfunction[0].has_nonhomogeneous_bcs:\n self.S.testfunction[0].bc.set_boundary_dofs(u, True)\n\n return u\n\n def matvec(self, v, c):\n c[:] = 0\n self.Biharmonic_matvec(v, c, self.a0, self.alfa, self.beta, self.S[0],\n self.S[2], self.S[4], self.A[-2], self.A[0],\n self.A[2], self.B[-4], self.B[-2], self.B[0],\n self.B[2], self.B[4], self.axis)\n return c\n\n\nclass PDMA:\n r\"\"\"Pentadiagonal matrix solver\n\n Pentadiagonal matrix with diagonals in offsets -4, -2, 0, 2, 4\n\n Arising with Poisson equation and biharmonic basis u\n\n .. math::\n\n \\alpha u'' + \\beta u = f\n\n As 4 arguments\n\n Parameters\n ----------\n A : SpectralMatrix\n Stiffness matrix\n B : SpectralMatrix\n Mass matrix\n alfa : array\n beta : array\n\n or as dict with key/vals\n\n Parameters\n ----------\n solver : str\n Choose between implementations ('cython', 'python')\n ABBmat : A\n Stiffness matrix\n BBBmat : B\n Mass matrix\n\n where alfa and beta must be avalable as A.scale, B.scale.\n\n Attributes\n ----------\n axis : int\n The axis over which to solve for\n\n Variables are extracted from the matrices\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n if 'ABBmat' in kwargs:\n assert 'BBBmat' in kwargs\n A = self.A = kwargs['ABBmat']\n B = self.B = kwargs['BBBmat']\n self.alfa = A.scale\n self.beta = B.scale\n\n elif len(args) == 4:\n A = self.A = args[0]\n B = self.B = args[1]\n self.alfa = args[2]\n self.beta = args[3]\n else:\n raise RuntimeError('Wrong input to PDMA solver')\n\n self.solver = kwargs.get('solver', 'cython')\n self.d, self.u1, self.u2 = (np.zeros_like(B[0]), np.zeros_like(B[2]),\n np.zeros_like(B[4]))\n self.l1, self.l2 = np.zeros_like(B[2]), np.zeros_like(B[4])\n self.alfa = np.atleast_1d(self.alfa)\n self.beta = np.atleast_1d(self.beta)\n shape = list(self.beta.shape)\n\n if len(shape) == 1:\n if self.solver == 'python':\n H = self.alfa[0]*self.A + self.beta[0]*self.B\n self.d[:] = H[0]\n self.u1[:] = H[2]\n self.u2[:] = H[4]\n self.l1[:] = H[-2]\n self.l2[:] = H[-4]\n self.PDMA_LU(self.l2, self.l1, self.d, self.u1, self.u2)\n\n elif self.solver == 'cython':\n la.LU_Helmholtz_Biharmonic_1D(self.A, self.B, self.alfa[0],\n self.beta[0], self.l2, self.l1,\n self.d, self.u1, self.u2)\n else:\n\n self.axis = A.axis\n assert self.alfa.shape[A.axis] == 1\n assert self.beta.shape[A.axis] == 1\n N = A.shape[0]+4\n self.alfa = np.broadcast_to(self.alfa, shape).copy()\n shape[A.axis] = N\n self.d = np.zeros(shape, float) # Diagonal entries of U\n self.u1 = np.zeros(shape, float) # Diagonal+2 entries of U\n self.l1 = np.zeros(shape, float) # Diagonal-2 entries of U\n self.u2 = np.zeros(shape, float) # Diagonal+4 entries of U\n self.l2 = np.zeros(shape, float) # Diagonal-4 entries of U\n\n if len(shape) == 2:\n raise NotImplementedError\n\n elif len(shape) == 3:\n la.LU_Helmholtz_Biharmonic_3D(A, B, A.axis, self.alfa, self.beta, self.l2,\n self.l1, self.d, self.u1, self.u2)\n\n @staticmethod\n def PDMA_LU(l2, l1, d, u1, u2): # pragma: no cover\n \"\"\"LU decomposition of PDM (for testing only)\"\"\"\n n = d.shape[0]\n m = u1.shape[0]\n k = n - m\n\n for i in range(n-2*k):\n lam = l1[i]/d[i]\n d[i+k] -= lam*u1[i]\n u1[i+k] -= lam*u2[i]\n l1[i] = lam\n lam = l2[i]/d[i]\n l1[i+k] -= lam*u1[i]\n d[i+2*k] -= lam*u2[i]\n l2[i] = lam\n\n i = n-4\n lam = l1[i]/d[i]\n d[i+k] -= lam*u1[i]\n l1[i] = lam\n i = n-3\n lam = l1[i]/d[i]\n d[i+k] -= lam*u1[i]\n l1[i] = lam\n\n\n @staticmethod\n def PDMA_Solve(l2, l1, d, u1, u2, b): # pragma: no cover\n \"\"\"Solve method for PDM (for testing only)\"\"\"\n n = d.shape[0]\n bc = np.full_like(b, b)\n\n bc[2] -= l1[0]*bc[0]\n bc[3] -= l1[1]*bc[1]\n for k in range(4, n):\n bc[k] -= (l1[k-2]*bc[k-2] + l2[k-4]*bc[k-4])\n\n bc[n-1] /= d[n-1]\n bc[n-2] /= d[n-2]\n bc[n-3] /= d[n-3]\n bc[n-3] -= u1[n-3]*bc[n-1]/d[n-3]\n bc[n-4] /= d[n-4]\n bc[n-4] -= u1[n-4]*bc[n-2]/d[n-4]\n for k in range(n-5, -1, -1):\n bc[k] /= d[k]\n bc[k] -= (u1[k]*bc[k+2]/d[k] + u2[k]*bc[k+4]/d[k])\n b[:] = bc\n\n def __call__(self, u, b):\n \"\"\"Solve matrix problem\n\n Parameters\n ----------\n b : array\n Array of right hand side on entry and solution on exit unless\n u is provided.\n u : array\n Output array\n\n If b and u are multidimensional, then the axis over which to solve for\n is determined on creation of the class.\n\n \"\"\"\n if np.ndim(u) == 3:\n la.Solve_Helmholtz_Biharmonic_3D_ptr(self.A.axis, b, u, self.l2,\n self.l1, self.d, self.u1,\n self.u2)\n elif np.ndim(u) == 2:\n la.Solve_Helmholtz_Biharmonic_2D_ptr(self.A.axis, b, u, self.l2,\n self.l1, self.d, self.u1,\n self.u2)\n else:\n if self.solver == 'python': # pragma: no cover\n u[:] = b\n self.PDMA_Solve(self.l2, self.l1, self.d, self.u1, self.u2, u)\n\n elif self.solver == 'cython':\n if u is b:\n u = np.zeros_like(b)\n #la.Solve_Helmholtz_Biharmonic_1D(b, u, self.l2, self.l1,\n # self.d, self.u1, self.u2)\n la.Solve_Helmholtz_Biharmonic_1D_p(b, u, self.l2, self.l1,\n self.d, self.u1, self.u2)\n\n #u /= self.mat.scale\n return u\n" ]
[ [ "matplotlib.pyplot.contourf", "numpy.allclose", "matplotlib.pyplot.title", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ], [ "numpy.atleast_1d", "numpy.full_like", "numpy.ndim", "numpy.zeros_like", "numpy.broadcast_to", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
haox07/isoSTED
[ "7e5e244f82c52e06e0b66acfb246dfd3708e1b3b" ]
[ "DM-Training/code/fringe/unwrap.py" ]
[ "#!/usr/bin/env python3\n\nimport scipy\nimport os\nimport argparse\nimport numpy as np\nfrom skimage.restoration import unwrap_phase\nfrom scipy import io\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='''Unwrap phase using M. A. Herráez, D. R. Burton, M. J.\n Lalor, and M. A. Gdeisat, \"Fast two-dimensional phase-unwrapping\n algorithm based on sorting by reliability following a noncontinuous\n path,\" Appl. Opt. 41, 7437-7444 (2002).\n ''',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\n 'file',\n type=argparse.FileType('rb'),\n help='Wrapped phase, either in a MATLAB or an ASCII file.')\n parser.add_argument(\n '--debug', action='store_true', help='Plot phases.')\n parser.add_argument(\n '--quiet', action='store_true', help='No console output.')\n\n args = parser.parse_args()\n\n dout = dict()\n matfile = io.loadmat(args.file)\n\n phiw = matfile['phiw']\n apmask = matfile['apmask'].astype(np.bool)\n masked = np.ma.masked_array(phiw, np.invert(apmask))\n phiu = np.array(unwrap_phase(masked, wrap_around=False, seed=10))\n splits = os.path.splitext(args.file.name)\n scipy.io.savemat(splits[0] + '_unwrapped' + splits[1], {'phiu': phiu})\n" ]
[ [ "scipy.io.loadmat", "numpy.invert", "scipy.io.savemat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
daveliepmann/incubator-mxnet
[ "0d7794730ad0272e52a62d1101ccbe9fcf1aafcb", "0d7794730ad0272e52a62d1101ccbe9fcf1aafcb" ]
[ "tests/nightly/test_large_array.py", "python/mxnet/ndarray/ndarray.py" ]
[ "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport mxnet as mx\nimport numpy as np\nfrom mxnet.test_utils import rand_ndarray, assert_almost_equal\nfrom mxnet import gluon, nd\nfrom tests.python.unittest.common import with_seed\n\n# dimension constants\nMEDIUM_X = 10000\nLARGE_X = 100000000\nLARGE_Y = 50000000\nSMALL_Y = 50\nLARGE_SIZE = LARGE_X * SMALL_Y\n\n\ndef test_gluon_embedding():\n m = gluon.nn.Embedding(SMALL_Y, MEDIUM_X)\n m.initialize()\n a = nd.zeros((MEDIUM_X, SMALL_Y))\n b = m(a)\n assert b.shape == (MEDIUM_X, SMALL_Y, MEDIUM_X)\n assert b.asnumpy().size == LARGE_SIZE\n\n\ndef test_ndarray_zeros():\n a = nd.zeros(shape=(LARGE_X, SMALL_Y))\n assert a[-1][0] == 0\n assert a.shape == (LARGE_X, SMALL_Y)\n assert a.size == LARGE_SIZE\n\n\ndef test_ndarray_ones():\n a = nd.ones(shape=(LARGE_X, SMALL_Y))\n assert a[-1][0] == 1\n assert nd.sum(a).asnumpy() == LARGE_SIZE\n\n\n@with_seed()\ndef test_ndarray_random_uniform():\n a = nd.random.uniform(shape=(LARGE_X, SMALL_Y))\n assert a[-1][0] != 0\n\n\n@with_seed()\ndef test_ndarray_random_randint():\n a = nd.random.randint(100, 10000, shape=(LARGE_X, SMALL_Y))\n assert a.shape == (LARGE_X, SMALL_Y)\n # check if randint can generate value greater than 2**32 (large)\n low_large_value = 2**32\n high_large_value = 2**34\n a = nd.random.randint(low_large_value,high_large_value)\n low = mx.nd.array([low_large_value], dtype='int64')\n high = mx.nd.array([high_large_value], dtype='int64')\n assert a.__gt__(low) & a.__lt__(high)\n\n\ndef test_ndarray_empty():\n a = nd.empty((LARGE_X, SMALL_Y))\n assert a.shape == (LARGE_X, SMALL_Y)\n\n\ndef test_elementwise():\n a = nd.ones(shape=(LARGE_X, SMALL_Y))\n b = nd.ones(shape=(LARGE_X, SMALL_Y))\n res = a + b\n assert np.sum(res[-1].asnumpy() == 2) == a.shape[1]\n res = a + 1\n assert np.sum(res[-1].asnumpy() == 2) == a.shape[1]\n res = nd.sqrt(a + 3)\n assert np.sum(res[-1].asnumpy() == 2) == a.shape[1]\n\n\ndef test_reduce():\n a = nd.ones(shape=(LARGE_X, SMALL_Y)) \n assert nd.sum(a).asnumpy() == a.shape[0] * a.shape[1]\n\n\ndef test_dot():\n a = nd.ones(shape=(LARGE_X, SMALL_Y)) \n b = nd.ones(shape=(SMALL_Y, SMALL_Y))\n res = nd.dot(a, b)\n assert np.sum(res[-1].asnumpy() == SMALL_Y) == b.shape[1]\n\n\ndef test_FullyConnected():\n a = nd.ones(shape=(LARGE_X, SMALL_Y)) \n b = nd.ones(shape=(SMALL_Y, SMALL_Y)) \n res = nd.FullyConnected(a, b, num_hidden=b.shape[1], no_bias=True)\n assert np.sum(res[-1].asnumpy() == SMALL_Y) == b.shape[1]\n\n\ndef test_broadcast():\n a = nd.ones(shape=(LARGE_X, SMALL_Y))\n b = nd.arange(0, LARGE_X).reshape(LARGE_X, 1)\n res = nd.broadcast_to(b, shape=(b.shape[0], SMALL_Y))\n assert np.sum(res[-1].asnumpy() == LARGE_X) == res.shape[1]\n res = mx.nd.broadcast_like(b, a)\n assert np.sum(res[-1].asnumpy() == LARGE_X) == a.shape[1]\n\n\ndef test_clip():\n a = nd.arange(0, LARGE_X).reshape(LARGE_X, 1)\n b = nd.broadcast_to(a, shape=(a.shape[0], SMALL_Y))\n res = nd.clip(b, a_min=100, a_max=1000)\n assert np.sum(res[-1].asnumpy() == 1000) == b.shape[1]\n\n\ndef test_take():\n a = nd.ones(shape=(LARGE_X, SMALL_Y))\n idx = nd.arange(LARGE_X-1000, LARGE_X)\n res = nd.take(a, idx)\n assert np.sum(res[-1].asnumpy() == 1) == res.shape[1]\n\n\ndef test_slice():\n a = nd.ones(shape=(LARGE_X, SMALL_Y))\n res = nd.slice(a, begin=(LARGE_X-1000, 1), end=(LARGE_X, SMALL_Y))\n assert np.sum(res[-1].asnumpy() == 1) == res.shape[1]\n\n\ndef test_slice_assign():\n a = nd.ones(shape=(LARGE_X, SMALL_Y))\n a[LARGE_X-1:LARGE_X] = 1000\n assert np.sum(a[-1].asnumpy() == 1000) == a.shape[1]\n\n\ndef test_expand_dims():\n a = nd.ones(shape=(LARGE_X, SMALL_Y))\n res = nd.expand_dims(a, axis=1)\n assert res.shape == (a.shape[0], 1, a.shape[1])\n\n\ndef test_squeeze():\n a = nd.ones(shape=(LARGE_X, SMALL_Y))\n data = nd.expand_dims(a, axis=1)\n res = nd.squeeze(data)\n assert res.shape == a.shape\n\n\ndef test_broadcast_div():\n a = nd.ones(shape=(LARGE_X, SMALL_Y))\n b = nd.ones(shape=(LARGE_X, 1)) * 2\n res = a / b\n assert np.sum(res[-1].asnumpy() == 0.5) == a.shape[1]\n\n\ndef test_Dense(ctx=mx.cpu(0)):\n data = mx.nd.ones(shape=(50*1000*1000, 100))\n linear = gluon.nn.Dense(100)\n linear.initialize(ctx=ctx)\n res = linear(data)\n res.wait_to_read()\n assert res.shape == (50000000, 100)\n\n\ndef test_where():\n a = nd.ones(shape=(LARGE_X, SMALL_Y))\n b = nd.arange(0, LARGE_X).reshape(LARGE_X, 1)\n b = nd.broadcast_to(b, shape=(b.shape[0], SMALL_Y))\n res = nd.where(b > 100, a, b)\n assert np.sum(res[-1].asnumpy() == 1) == b.shape[1]\n\n csr_cond = nd.sparse.cast_storage(b < 10, 'csr')\n res = nd.sparse.where(csr_cond, a, b)\n assert np.sum(res[0].asnumpy() == 1) == b.shape[1]\n\n\ndef test_pick():\n a = mx.nd.ones(shape=(256*35, 1024*1024))\n b = mx.nd.ones(shape=(256*35,))\n res = mx.nd.pick(a,b)\n assert res.shape == b.shape\n \ndef test_depthtospace():\n def numpy_depth_to_space(x, blocksize):\n b, c, h, w = x.shape[0], x.shape[1], x.shape[2], x.shape[3]\n tmp = np.reshape(x, [b, blocksize, blocksize, c // (blocksize**2), h, w])\n tmp = np.transpose(tmp, [0, 3, 4, 1, 5, 2])\n y = np.reshape(tmp, [b, c // (blocksize**2), h * blocksize, w * blocksize])\n return y\n\n shape_inp = (LARGE_X, 8, 4, 2)\n data = rand_ndarray(shape_inp, 'default')\n data_np = data.asnumpy()\n expected = numpy_depth_to_space(data_np, 2)\n output = mx.nd.depth_to_space(data, 2)\n assert_almost_equal(output.asnumpy(), expected, atol=1e-3, rtol=1e-3)\n\ndef test_spacetodepth():\n def numpy_space_to_depth(x, blocksize):\n b, c, h, w = x.shape[0], x.shape[1], x.shape[2], x.shape[3]\n tmp = np.reshape(x, [b, c, h // blocksize, blocksize, w // blocksize, blocksize])\n tmp = np.transpose(tmp, [0, 3, 5, 1, 2, 4])\n y = np.reshape(tmp, [b, c * (blocksize**2), h // blocksize, w // blocksize])\n return y\n\n shape_inp = (LARGE_X, 2, 8, 4)\n data = rand_ndarray(shape_inp, 'default')\n data_np = data.asnumpy()\n expected = numpy_space_to_depth(data_np, 2)\n output = mx.nd.space_to_depth(data, 2)\n assert_almost_equal(output.asnumpy(), expected, atol=1e-3, rtol=1e-3)\n\nif __name__ == '__main__':\n import nose\n nose.runmodule()\n", "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# coding: utf-8\n# pylint: disable=too-many-lines, protected-access\n# pylint: disable=import-error, no-name-in-module, undefined-variable\n\"\"\"NDArray API of MXNet.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\n\ntry:\n from __builtin__ import slice as py_slice\nexcept ImportError:\n from builtins import slice as py_slice\n\nfrom array import array as native_array\nimport ctypes\nimport warnings\nimport operator\nfrom functools import reduce # pylint: disable=redefined-builtin\nimport numpy as np\nfrom ..base import _LIB, numeric_types, integer_types\nfrom ..base import c_str, c_array, c_array_buf, c_handle_array, mx_real_t\nfrom ..base import mx_uint, NDArrayHandle, check_call, DLPackHandle, mx_int\nfrom ..base import ctypes2buffer\nfrom ..context import Context, current_context\nfrom . import _internal\nfrom . import op\nfrom ._internal import NDArrayBase\n\n__all__ = [\"NDArray\", \"concatenate\", \"_DTYPE_NP_TO_MX\", \"_DTYPE_MX_TO_NP\", \"_GRAD_REQ_MAP\",\n \"ones\", \"add\", \"arange\", \"linspace\", \"eye\", \"divide\", \"equal\", \"full\", \"greater\",\n \"greater_equal\", \"imdecode\", \"lesser\", \"lesser_equal\", \"logical_and\", \"logical_or\",\n \"logical_xor\", \"maximum\", \"minimum\", \"moveaxis\", \"modulo\", \"multiply\", \"not_equal\",\n \"onehot_encode\", \"power\", \"subtract\", \"true_divide\", \"waitall\", \"_new_empty_handle\",\n \"histogram\", \"split_v2\", \"to_dlpack_for_read\", \"to_dlpack_for_write\", \"from_dlpack\",\n \"from_numpy\"]\n\n_STORAGE_TYPE_UNDEFINED = -1\n_STORAGE_TYPE_DEFAULT = 0\n_STORAGE_TYPE_ROW_SPARSE = 1\n_STORAGE_TYPE_CSR = 2\n\n# pylint: disable= no-member\n_DTYPE_NP_TO_MX = {\n None: -1,\n np.float32: 0,\n np.float64: 1,\n np.float16: 2,\n np.uint8: 3,\n np.int32: 4,\n np.int8: 5,\n np.int64: 6,\n}\n\n_DTYPE_MX_TO_NP = {\n -1: None,\n 0: np.float32,\n 1: np.float64,\n 2: np.float16,\n 3: np.uint8,\n 4: np.int32,\n 5: np.int8,\n 6: np.int64,\n}\n\n_STORAGE_TYPE_STR_TO_ID = {\n 'undefined': _STORAGE_TYPE_UNDEFINED,\n 'default': _STORAGE_TYPE_DEFAULT,\n 'row_sparse': _STORAGE_TYPE_ROW_SPARSE,\n 'csr': _STORAGE_TYPE_CSR,\n}\n\n_STORAGE_TYPE_ID_TO_STR = {\n _STORAGE_TYPE_UNDEFINED: 'undefined',\n _STORAGE_TYPE_DEFAULT: 'default',\n _STORAGE_TYPE_ROW_SPARSE: 'row_sparse',\n _STORAGE_TYPE_CSR: 'csr',\n}\n\n_GRAD_REQ_MAP = {\n 'null': 0,\n 'write': 1,\n 'add': 3\n}\n# pylint: enable= no-member\n\n# Return code for dispatching indexing function call\n_NDARRAY_UNSUPPORTED_INDEXING = -1\n_NDARRAY_BASIC_INDEXING = 0\n_NDARRAY_ADVANCED_INDEXING = 1\n\n\ndef _new_empty_handle():\n \"\"\"Returns a new empty handle.\n\n Empty handle can be used to hold a result.\n\n Returns\n -------\n handle\n A new empty `NDArray` handle.\n \"\"\"\n hdl = NDArrayHandle()\n check_call(_LIB.MXNDArrayCreateNone(ctypes.byref(hdl)))\n return hdl\n\n\ndef _new_alloc_handle(shape, ctx, delay_alloc, dtype=mx_real_t):\n \"\"\"Return a new handle with specified shape and context.\n\n Empty handle is only used to hold results.\n\n Returns\n -------\n handle\n A new empty `NDArray` handle.\n \"\"\"\n hdl = NDArrayHandle()\n check_call(_LIB.MXNDArrayCreateEx(\n c_array_buf(mx_uint, native_array('I', shape)),\n mx_uint(len(shape)),\n ctypes.c_int(ctx.device_typeid),\n ctypes.c_int(ctx.device_id),\n ctypes.c_int(int(delay_alloc)),\n ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])),\n ctypes.byref(hdl)))\n return hdl\n\n\ndef _new_from_shared_mem(shared_pid, shared_id, shape, dtype):\n hdl = NDArrayHandle()\n check_call(_LIB.MXNDArrayCreateFromSharedMemEx(\n ctypes.c_int(shared_pid),\n ctypes.c_int(shared_id),\n c_array(mx_int, shape),\n mx_int(len(shape)),\n ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])),\n ctypes.byref(hdl)))\n return hdl\n\n\ndef waitall():\n \"\"\"Wait for all async operations to finish in MXNet.\n\n This function is used for benchmarking only.\n\n .. note::\n\n If your mxnet code throws an exception, then waitall can cause performance impact.\n \"\"\"\n check_call(_LIB.MXNDArrayWaitAll())\n\n\ndef _storage_type(handle):\n storage_type = ctypes.c_int(0)\n check_call(_LIB.MXNDArrayGetStorageType(handle, ctypes.byref(storage_type)))\n return storage_type.value\n\n\nclass NDArray(NDArrayBase):\n \"\"\"An array object representing a multidimensional, homogeneous array of\nfixed-size items.\n\n \"\"\"\n __slots__ = []\n # make numpy functions return NDArray instead of numpy object array\n __array_priority__ = 1000.0\n # Extension type code for TVM function.\n # See C++ side of definition(kTVMNDArrayTypeCode) at include/mxmet/tensor_blob.h\n _tvm_tcode = 19\n # pylint: disable= no-member, undefined-variable\n @property\n def _tvm_handle(self):\n return self.handle.value\n\n def __repr__(self):\n \"\"\"Returns a string representation of the array.\"\"\"\n shape_info = 'x'.join(['%d' % x for x in self.shape])\n return '\\n%s\\n<%s %s @%s>' % (str(self.asnumpy()),\n self.__class__.__name__,\n shape_info, self.context)\n\n def __reduce__(self):\n return NDArray, (None,), self.__getstate__()\n\n def _to_shared_mem(self):\n shared_pid = ctypes.c_int()\n shared_id = ctypes.c_int()\n check_call(_LIB.MXNDArrayGetSharedMemHandle(\n self.handle, ctypes.byref(shared_pid), ctypes.byref(shared_id)))\n return shared_pid.value, shared_id.value, self.shape, self.dtype\n\n def __add__(self, other):\n \"\"\"x.__add__(y) <=> x+y <=> mx.nd.add(x, y) \"\"\"\n return add(self, other)\n\n def __iadd__(self, other):\n \"\"\"x.__iadd__(y) <=> x+=y \"\"\"\n if not self.writable:\n raise ValueError('trying to add to a readonly NDArray')\n if isinstance(other, NDArray):\n return op.broadcast_add(self, other, out=self)\n elif isinstance(other, numeric_types):\n return _internal._plus_scalar(self, float(other), out=self)\n else:\n raise TypeError('type %s not supported' % str(type(other)))\n\n def __radd__(self, other):\n return self.__add__(other)\n\n def __sub__(self, other):\n \"\"\"x.__sub__(y) <=> x-y <=> mx.nd.subtract(x, y) \"\"\"\n return subtract(self, other)\n\n def __isub__(self, other):\n \"\"\"x.__isub__(y) <=> x-=y \"\"\"\n if not self.writable:\n raise ValueError('trying to subtract from a readonly NDArray')\n if isinstance(other, NDArray):\n return op.broadcast_sub(self, other, out=self)\n elif isinstance(other, numeric_types):\n return _internal._minus_scalar(self, float(other), out=self)\n else:\n raise TypeError('type %s not supported' % str(type(other)))\n\n def __rsub__(self, other):\n \"\"\"x.__rsub__(y) <=> y-x <=> mx.nd.subtract(y, x) \"\"\"\n return subtract(other, self)\n\n def __mul__(self, other):\n \"\"\"x.__mul__(y) <=> x*y <=> mx.nd.multiply(x, y) \"\"\"\n return multiply(self, other)\n\n def __neg__(self):\n \"\"\"x.__neg__(y) <=> -x \"\"\"\n return _internal._mul_scalar(self, -1.0)\n\n def __imul__(self, other):\n \"\"\"x.__imul__(y) <=> x*=y \"\"\"\n if not self.writable:\n raise ValueError('trying to multiply to a readonly NDArray')\n if isinstance(other, NDArray):\n return op.broadcast_mul(self, other, out=self)\n elif isinstance(other, numeric_types):\n return _internal._mul_scalar(self, float(other), out=self)\n else:\n raise TypeError('type %s not supported' % str(type(other)))\n\n def __rmul__(self, other):\n return self.__mul__(other)\n\n def __div__(self, other):\n \"\"\"x.__div__(y) <=> x/y <=> mx.nd.divide(x, y) \"\"\"\n return divide(self, other)\n\n def __rdiv__(self, other):\n \"\"\"x.__rdiv__(y) <=> y/x <=> mx.nd.divide(y, x) \"\"\"\n return divide(other, self)\n\n def __idiv__(self, other):\n \"\"\"x.__rdiv__(y) <=> x/=y \"\"\"\n if not self.writable:\n raise ValueError('trying to divide from a readonly NDArray')\n if isinstance(other, NDArray):\n return op.broadcast_div(self, other, out=self)\n elif isinstance(other, numeric_types):\n return _internal._div_scalar(self, float(other), out=self)\n else:\n raise TypeError('type %s not supported' % str(type(other)))\n\n def __truediv__(self, other):\n return divide(self, other)\n\n def __rtruediv__(self, other):\n return divide(other, self)\n\n def __itruediv__(self, other):\n return self.__idiv__(other)\n\n def __mod__(self, other):\n \"\"\"x.__mod__(y) <=> x%y <=> mx.nd.modulo(x, y) \"\"\"\n return modulo(self, other)\n\n def __rmod__(self, other):\n \"\"\"x.__rmod__(y) <=> y%x <=> mx.nd.modulo(y, x) \"\"\"\n return modulo(other, self)\n\n def __imod__(self, other):\n \"\"\"x.__rmod__(y) <=> x%=y \"\"\"\n if not self.writable:\n raise ValueError('trying to take modulo from a readonly NDArray')\n if isinstance(other, NDArray):\n return op.broadcast_mod(self, other, out=self)\n elif isinstance(other, numeric_types):\n return _internal._mod_scalar(self, float(other), out=self)\n else:\n raise TypeError('type %s not supported' % str(type(other)))\n\n def __pow__(self, other):\n \"\"\"x.__pow__(y) <=> x**y <=> mx.nd.power(x,y) \"\"\"\n return power(self, other)\n\n def __rpow__(self, other):\n \"\"\"x.__pow__(y) <=> y**x <=> mx.nd.power(y,x) \"\"\"\n return power(other, self)\n\n def __eq__(self, other):\n \"\"\"x.__eq__(y) <=> x==y <=> mx.nd.equal(x, y) \"\"\"\n return equal(self, other)\n\n def __hash__(self):\n \"\"\"Default hash function.\"\"\"\n return id(self)//16\n\n def __ne__(self, other):\n \"\"\"x.__ne__(y) <=> x!=y <=> mx.nd.not_equal(x, y) \"\"\"\n return not_equal(self, other)\n\n def __gt__(self, other):\n \"\"\"x.__gt__(y) <=> x>y <=> mx.nd.greater(x, y) \"\"\"\n return greater(self, other)\n\n def __ge__(self, other):\n \"\"\"x.__ge__(y) <=> x>=y <=> mx.nd.greater_equal(x, y) \"\"\"\n return greater_equal(self, other)\n\n def __lt__(self, other):\n \"\"\"x.__lt__(y) <=> x<y <=> mx.nd.lesser(x, y) \"\"\"\n return lesser(self, other)\n\n def __le__(self, other):\n \"\"\"x.__le__(y) <=> x<=y <=> mx.nd.less_equal(x, y) \"\"\"\n return lesser_equal(self, other)\n\n def __bool__(self):\n num_elements = reduce(operator.mul, self.shape, 1)\n if num_elements == 0:\n return False\n elif num_elements == 1:\n return bool(self.asscalar())\n else:\n raise ValueError(\"The truth value of an NDArray with multiple elements \" \\\n \"is ambiguous.\")\n\n __nonzero__ = __bool__\n\n def __len__(self):\n \"\"\"Number of element along the first axis.\"\"\"\n return self.shape[0]\n\n def __getstate__(self):\n handle = self.handle\n this = {'handle' : None}\n if handle is not None:\n length = ctypes.c_size_t()\n cptr = ctypes.POINTER(ctypes.c_char)()\n check_call(_LIB.MXNDArraySaveRawBytes(self.handle,\n ctypes.byref(length),\n ctypes.byref(cptr)))\n this['handle'] = ctypes2buffer(cptr, length.value)\n return this\n\n def __setstate__(self, state):\n # pylint: disable=assigning-non-slot\n handle = state['handle']\n if handle is not None:\n buf = handle\n handle = NDArrayHandle()\n ptr = (ctypes.c_char * len(buf)).from_buffer(buf)\n length = ctypes.c_size_t(len(buf))\n check_call(_LIB.MXNDArrayLoadFromRawBytes(ptr, length, ctypes.byref(handle)))\n self.handle = handle\n else:\n self.handle = None\n\n # pylint: disable=line-too-long\n def __setitem__(self, key, value):\n \"\"\"x.__setitem__(i, y) <=> x[i]=y\n\n Sets value to self[key]. This functions supports advanced indexing defined in the following reference with\n some restrictions.\n\n https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#combining-advanced-and-basic-indexing\n\n - If key is a list type, only a list of integers is supported, e.g. key=[1, 2] is supported,\n while not for key=[[1, 2]].\n - Ellipsis (...) and np.newaxis are not supported.\n - Boolean array indexing is not supported.\n\n Parameters\n ----------\n key : int, mxnet.ndarray.slice, list, np.ndarray, NDArray, or tuple of all previous types\n The indexing key.\n value : scalar or array-like object that can be broadcast to the shape of self[key]\n The value to set.\n\n Examples\n --------\n >>> x = mx.nd.zeros((2,3))\n >>> x[:] = 1\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> x[:,1:2] = 2\n >>> x.asnumpy()\n array([[ 1., 2., 1.],\n [ 1., 2., 1.]], dtype=float32)\n >>> x[1:2,1:] = 3\n >>> x.asnumpy()\n array([[ 1., 2., 1.],\n [ 1., 3., 3.]], dtype=float32)\n >>> x[1:,0:2] = mx.nd.zeros((1,2))\n >>> x.asnumpy()\n array([[ 1., 2., 1.],\n [ 0., 0., 3.]], dtype=float32)\n >>> x[1,2] = 4\n >>> x.asnumpy()\n array([[ 1., 2., 1.],\n [ 0., 0., 4.]], dtype=float32)\n >>> x[[0], [1, 2]] = 5\n >>> x.asnumpy()\n array([[ 1., 5., 5.],\n [ 0., 0., 4.]], dtype=float32)\n >>> x[::-1, 0:2:2] = [6]\n >>> x.asnumpy()\n array([[ 6., 5., 5.],\n [ 6., 0., 4.]], dtype=float32)\n \"\"\"\n indexing_dispatch_code = _get_indexing_dispatch_code(key)\n if indexing_dispatch_code == _NDARRAY_BASIC_INDEXING:\n self._set_nd_basic_indexing(key, value)\n elif indexing_dispatch_code == _NDARRAY_ADVANCED_INDEXING:\n self._set_nd_advanced_indexing(key, value)\n else:\n raise ValueError('Indexing NDArray with index=%s and type=%s is not supported'\n % (str(key), str(type(key))))\n # pylint: enable=line-too-long\n\n # pylint: disable=line-too-long\n def __getitem__(self, key):\n \"\"\"x.__getitem__(i) <=> x[i]\n\n Returns a sliced view of this array if the elements fetched are contiguous in memory;\n otherwise, returns a newly created NDArray.\n This functions supports advanced indexing defined in the following reference with\n some restrictions.\n\n https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#combining-advanced-and-basic-indexing\n\n - If key is a list type, only a list of integers is supported, e.g. key=[1, 2] is supported,\n while not for key=[[1, 2]].\n - Ellipsis (...) and np.newaxis are not supported.\n - Boolean array indexing is not supported.\n\n Parameters\n ----------\n key : int, mxnet.ndarray.slice, list, np.ndarray, NDArray, or tuple of all previous types\n Indexing key.\n\n Examples\n --------\n >>> x = mx.nd.arange(0,6).reshape((2,3))\n >>> x.asnumpy()\n array([[ 0., 1., 2.],\n [ 3., 4., 5.]], dtype=float32)\n >>> x[1].asnumpy()\n array([ 3., 4., 5.], dtype=float32)\n >>> y = x[0:1]\n >>> y[:] = 2\n >>> x.asnumpy()\n array([[ 2., 2., 2.],\n [ 3., 4., 5.]], dtype=float32)\n >>> x = mx.nd.arange(0, 8, dtype='int32').reshape((2, 2, 2))\n >>> x[[0, 1]]\n [[[0 1]\n [2 3]]\n [[4 5]\n [6 7]]]\n >>> x[1:, [0, 1]]\n [[[4 5]\n [6 7]]]\n >>> y = np.array([0, 1], dtype='int32')\n >>> x[1:, y]\n [[[4 5]\n [6 7]]]\n >>> y = mx.nd.array([0, 1], dtype='int32')\n >>> x[1:, y]\n [[[4 5]\n [6 7]]]\n \"\"\"\n indexing_dispatch_code = _get_indexing_dispatch_code(key)\n if indexing_dispatch_code == _NDARRAY_BASIC_INDEXING:\n return self._get_nd_basic_indexing(key)\n elif indexing_dispatch_code == _NDARRAY_ADVANCED_INDEXING:\n return self._get_nd_advanced_indexing(key)\n else:\n raise ValueError('Indexing NDArray with index=%s and type=%s is not supported'\n % (str(key), str(type(key))))\n # pylint: enable=line-too-long\n\n def _get_index_nd(self, key):\n \"\"\"Returns an index array for use in scatter_nd and gather_nd.\"\"\"\n def _is_advanced_index(index):\n \"\"\"The definition of advanced index here includes integers as well, while\n integers are considered as basic index type when the key contains only\n slices and integers.\"\"\"\n return not isinstance(index, py_slice)\n\n if isinstance(key, (NDArray, np.ndarray, list, integer_types, py_slice)):\n key = (key,)\n\n assert isinstance(key, tuple),\\\n 'index=%s must be a NDArray, or np.ndarray, or list, or tuple ' \\\n ' type to use advanced indexing, received type=%s' % (str(key), str(type(key)))\n\n assert len(key) > 0, \"Cannot slice with empty indices\"\n shape = self.shape\n assert len(shape) >= len(key),\\\n \"Slicing dimensions exceeds array dimensions, %d vs %d\" % (len(key), len(shape))\n indices = []\n dtype = 'int32' # index data type passed to gather_nd op\n need_broadcast = (len(key) != 1)\n advanced_indices = [] # include list, NDArray, np.ndarray, integer\n basic_indices = [] # include only slices\n advanced_index_bshape = None # final advanced index shape\n for i, idx_i in enumerate(key):\n is_advanced_index = True\n if isinstance(idx_i, (np.ndarray, list, tuple)):\n idx_i = array(idx_i, ctx=self.context, dtype=dtype)\n advanced_indices.append(i)\n elif isinstance(idx_i, py_slice):\n start, stop, step = _get_index_range(idx_i.start, idx_i.stop, shape[i], idx_i.step)\n idx_i = arange(start, stop, step, ctx=self.context, dtype=dtype)\n basic_indices.append(i)\n is_advanced_index = False\n elif isinstance(idx_i, integer_types):\n start, stop, step = _get_index_range(idx_i, idx_i+1, shape[i], 1)\n idx_i = arange(start, stop, step, ctx=self.context, dtype=dtype)\n advanced_indices.append(i)\n elif isinstance(idx_i, NDArray):\n if dtype != idx_i.dtype:\n idx_i = idx_i.astype(dtype)\n advanced_indices.append(i)\n else:\n raise IndexError('Indexing NDArray with index=%s of type=%s is not supported'\n % (str(key), str(type(key))))\n if is_advanced_index:\n if advanced_index_bshape is None:\n advanced_index_bshape = idx_i.shape\n elif advanced_index_bshape != idx_i.shape:\n need_broadcast = True\n advanced_index_bshape = _get_broadcast_shape(advanced_index_bshape, idx_i.shape)\n indices.append(idx_i)\n\n # Get final index shape for gather_nd. See the following reference\n # for determining the output array shape.\n # https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#combining-advanced-and-basic-indexing # pylint: disable=line-too-long\n if len(advanced_indices) == 0:\n raise ValueError('Advanced index tuple must contain at least one of the following types:'\n ' list, tuple, NDArray, np.ndarray, integer, received index=%s' % key)\n # determine the output array's shape by checking whether advanced_indices are all adjacent\n # or separated by slices\n advanced_indices_adjacent = True\n for i in range(0, len(advanced_indices)-1):\n if advanced_indices[i] + 1 != advanced_indices[i+1]:\n advanced_indices_adjacent = False\n break\n\n index_bshape_list = [] # index broadcasted shape\n if advanced_indices_adjacent:\n for i in range(0, advanced_indices[0]):\n index_bshape_list.extend(indices[i].shape)\n if not need_broadcast and indices[i].shape != advanced_index_bshape:\n need_broadcast = True\n index_bshape_list.extend(advanced_index_bshape)\n for i in range(advanced_indices[-1]+1, len(indices)):\n if not need_broadcast and indices[i].shape != advanced_index_bshape:\n need_broadcast = True\n index_bshape_list.extend(indices[i].shape)\n else:\n index_bshape_list.extend(advanced_index_bshape)\n for i in basic_indices:\n index_bshape_list.extend(indices[i].shape)\n if not need_broadcast and indices[i].shape != advanced_index_bshape:\n need_broadcast = True\n index_bshape = tuple(index_bshape_list)\n\n # Need to broadcast all ndarrays in indices to the final shape.\n # For example, suppose an array has shape=(5, 6, 7, 8) and\n # key=(slice(1, 5), [[1, 2]], slice(2, 5), [1]).\n # Since key[1] and key[3] are two advanced indices here and they are\n # separated by basic indices key[0] and key[2], the output shape\n # is (1, 2, 4, 3), where the first two elements come from the shape\n # that key[1] and key[3] should broadcast to, which is (1, 2), and\n # the last two elements come from the shape of two basic indices.\n # In order to broadcast all basic and advanced indices to the output shape,\n # we need to reshape them based on their axis. For example, to broadcast key[0],\n # with shape=(4,), we first need to reshape it into (1, 1, 4, 1), and then\n # broadcast the reshaped array to (1, 2, 4, 3); to broadcast key[1], we first\n # reshape it into (1, 2, 1, 1), then broadcast the reshaped array to (1, 2, 4, 3).\n if need_broadcast:\n broadcasted_indices = []\n idx_rshape = [1] * len(index_bshape)\n if advanced_indices_adjacent:\n advanced_index_bshape_start = advanced_indices[0] # start index of advanced_index_bshape in index_shape\n advanced_index_bshape_stop = advanced_index_bshape_start + len(advanced_index_bshape)\n for i, idx in enumerate(key):\n if _is_advanced_index(idx):\n k = advanced_index_bshape_stop\n # find the reshaped shape for indices[i]\n for dim_size in indices[i].shape[::-1]:\n k -= 1\n idx_rshape[k] = dim_size\n else:\n if i < advanced_indices[0]: # slice is on the left side of advanced indices\n idx_rshape[i] = indices[i].shape[0]\n elif i > advanced_indices[-1]: # slice is on the right side of advanced indices\n idx_rshape[i-len(key)] = indices[i].shape[0]\n else:\n raise ValueError('basic index i=%d cannot be between advanced index i=%d and i=%d'\n % (i, advanced_indices[0], advanced_indices[-1]))\n # broadcast current index to the final shape\n broadcasted_indices.append(indices[i].reshape(tuple(idx_rshape)).broadcast_to(index_bshape))\n # reset idx_rshape to ones\n for j, _ in enumerate(idx_rshape):\n idx_rshape[j] = 1\n else:\n basic_index_offset = len(advanced_index_bshape)\n for i, idx in enumerate(key):\n if _is_advanced_index(idx):\n k = len(advanced_index_bshape)\n for dim_size in indices[i].shape[::-1]:\n k -= 1\n idx_rshape[k] = dim_size\n else:\n idx_rshape[basic_index_offset] = indices[i].shape[0]\n basic_index_offset += 1\n # broadcast current index to the final shape\n broadcasted_indices.append(indices[i].reshape(tuple(idx_rshape)).broadcast_to(index_bshape))\n # reset idx_rshape to ones\n for j, _ in enumerate(idx_rshape):\n idx_rshape[j] = 1\n\n indices = broadcasted_indices\n return op.stack(*indices)\n\n def _prepare_value_nd(self, value, vshape):\n \"\"\"Given value and vshape, create an `NDArray` from value with the same\n context and dtype as the current one and broadcast it to vshape.\"\"\"\n if isinstance(value, numeric_types):\n value_nd = full(shape=vshape, val=value, ctx=self.context, dtype=self.dtype)\n elif isinstance(value, NDArray):\n value_nd = value.as_in_context(self.context)\n if value_nd.dtype != self.dtype:\n value_nd = value_nd.astype(self.dtype)\n else:\n try:\n value_nd = array(value, ctx=self.context, dtype=self.dtype)\n except:\n raise TypeError('NDArray does not support assignment with non-array-like'\n ' object %s of type %s' % (str(value), str(type(value))))\n if value_nd.shape != vshape:\n value_nd = value_nd.broadcast_to(vshape)\n return value_nd\n\n def _set_nd_basic_indexing(self, key, value):\n \"\"\"This function is called by __setitem__ when key is a basic index, i.e.\n an integer, or a slice, or a tuple of integers and slices. No restrictions\n on the values of slices' steps.\"\"\"\n shape = self.shape\n if isinstance(key, integer_types):\n if key < 0:\n key += shape[0]\n if key < 0 or key >= shape[0]:\n if key < 0:\n key -= shape[0]\n raise IndexError('index %d is out of bounds for axis 0 with size %d'\n % (key, shape[0]))\n key = py_slice(key, key+1) # key must be >= 0 here\n\n if isinstance(key, py_slice):\n assign_to_self = key.step is None or key.step == 1\n assign_to_self &= key.start is None or key.start == 0\n assign_to_self &= key.stop is None or key.stop == shape[0]\n if assign_to_self: # trivial case, assign value to self\n if isinstance(value, NDArray):\n if value.handle is not self.handle:\n if value.shape != shape:\n value = value.broadcast_to(shape)\n value.copyto(self)\n elif isinstance(value, numeric_types):\n _internal._full(shape=shape, ctx=self.context,\n dtype=self.dtype, value=float(value), out=self)\n elif isinstance(value, (np.ndarray, np.generic)):\n if isinstance(value, np.generic) or value.shape != shape:\n value = np.broadcast_to(value, shape)\n self._sync_copyfrom(value)\n else: # value might be a list or a tuple\n value_nd = self._prepare_value_nd(value, shape)\n value_nd.copyto(self)\n return\n else: # non-trivial case, use _slice_assign or _slice_assign_scalar\n key = (key,)\n\n assert isinstance(key, tuple), \"key=%s must be a tuple of slices and integers\" % str(key)\n\n assert len(key) <= len(shape), \"Indexing dimensions exceed array dimensions, %d vs %d\"\\\n % (len(key), len(shape))\n begin = []\n end = []\n steps = []\n oshape = [] # output shape of slice using key\n vshape = [] # value shape of data[key]\n for i, slice_i in enumerate(key):\n dim_size = 1\n if isinstance(slice_i, py_slice):\n begin.append(slice_i.start)\n end.append(slice_i.stop)\n steps.append(slice_i.step)\n start, stop, step = _get_index_range(slice_i.start, slice_i.stop,\n shape[i], slice_i.step)\n dim_size = _get_dim_size(start, stop, step)\n vshape.append(dim_size)\n elif isinstance(slice_i, integer_types):\n begin.append(slice_i)\n end.append(slice_i+1 if slice_i != -1 else self.shape[i])\n steps.append(1)\n else:\n raise ValueError(\"basic indexing does not support index=%s of type=%s\"\n % (str(slice_i), str(type(slice_i))))\n oshape.append(dim_size)\n\n oshape.extend(shape[len(key):])\n vshape.extend(shape[len(key):])\n # if key contains all integers, vshape should be (1,)\n if len(vshape) == 0:\n vshape.append(1)\n oshape = tuple(oshape)\n vshape = tuple(vshape)\n\n if isinstance(value, numeric_types):\n _internal._slice_assign_scalar(self, out=self, begin=begin, end=end,\n step=steps, scalar=float(value))\n else:\n value_nd = self._prepare_value_nd(value, vshape)\n if vshape != oshape:\n value_nd = value_nd.reshape(oshape)\n _internal._slice_assign(self, value_nd, begin, end, steps, out=self)\n\n def _set_nd_advanced_indexing(self, key, value):\n \"\"\"This function is called by __setitem__ when key is an advanced index.\"\"\"\n indices = self._get_index_nd(key)\n vshape = _get_oshape_of_gather_nd_op(self.shape, indices.shape)\n value_nd = self._prepare_value_nd(value, vshape)\n _internal._scatter_set_nd(lhs=self, rhs=value_nd, indices=indices,\n shape=self.shape, out=self)\n\n def _get_nd_basic_indexing(self, key):\n \"\"\"This function is called when key is a slice, or an integer,\n or a tuple of slices or integers\"\"\"\n shape = self.shape\n if isinstance(key, integer_types):\n if key > shape[0] - 1:\n raise IndexError(\n 'index {} is out of bounds for axis 0 with size {}'.format(\n key, shape[0]))\n return self._at(key)\n elif isinstance(key, py_slice):\n if key.step is not None and key.step != 1:\n if key.step == 0:\n raise ValueError(\"slice step cannot be zero\")\n return op.slice(self, begin=(key.start,), end=(key.stop,), step=(key.step,))\n elif key.start is not None or key.stop is not None:\n return self._slice(key.start, key.stop)\n else:\n return self\n\n if not isinstance(key, tuple):\n raise ValueError('index=%s must be a slice, or an ineger, or a tuple'\n ' of slices and integers to use basic indexing, received type=%s'\n % (str(key), str(type(key))))\n assert len(key) != 0, 'basic index cannot be an empty tuple'\n begin = []\n end = []\n step = []\n kept_axes = [] # axes where slice_i is a slice\n i = -1\n for i, slice_i in enumerate(key):\n if isinstance(slice_i, integer_types):\n begin.append(slice_i)\n end.append(slice_i+1 if slice_i != -1 else self.shape[i])\n step.append(1)\n elif isinstance(slice_i, py_slice):\n if slice_i.step == 0:\n raise ValueError('basic index=%s cannot have slice=%s with step = 0'\n % (str(key), str(slice_i)))\n begin.append(slice_i.start)\n end.append(slice_i.stop)\n step.append(slice_i.step)\n kept_axes.append(i)\n else:\n raise ValueError('basic_indexing does not support slicing with '\n 'index=%s of type=%s.' % (str(slice_i), str(type(slice_i))))\n kept_axes.extend(range(i+1, len(shape)))\n sliced_nd = op.slice(self, begin, end, step)\n if len(kept_axes) == len(shape):\n return sliced_nd\n # squeeze sliced_shape to remove the axes indexed by integers\n oshape = []\n sliced_shape = sliced_nd.shape\n for axis in kept_axes:\n oshape.append(sliced_shape[axis])\n # if key is a tuple of integers, still need to keep 1 dim\n # while in Numpy, the output will become an value instead of an ndarray\n if len(oshape) == 0:\n oshape.append(1)\n oshape = tuple(oshape)\n assert np.prod(oshape) == np.prod(sliced_shape), 'oshape=%s has different size'\\\n ' than sliced_shape=%s'\\\n % (oshape, sliced_shape)\n return sliced_nd.reshape(oshape)\n\n def _get_nd_advanced_indexing(self, key):\n \"\"\"Get item when key is a tuple of any objects of the following types:\n NDArray, np.ndarray, list, tuple, slice, and integer.\"\"\"\n return op.gather_nd(self, self._get_index_nd(key))\n\n def _sync_copyfrom(self, source_array):\n \"\"\"Performs a synchronized copy from the `source_array` to the current array.\n This is called through ``x[:] = source_array``, where the `source_array`\n is a `numpy.ndarray` or array-like object.\n This function blocks until all the pending read/write operations with respect\n to the current `NDArray` are finished and carry out the copy operation to the\n current NDArray.\n\n Parameters\n ----------\n source_array : array_like\n The data source we would like to copy from.\n\n Example\n -------\n >>> a = mx.nd.array([1, 2])\n >>> a.asnumpy()\n array([ 1., 2.], dtype=float32)\n >>> a[:] = np.array([3, 4])\n >> a.asnumpy()\n array([ 3., 4.], dtype=float32)\n \"\"\"\n if not isinstance(source_array, np.ndarray):\n try:\n source_array = np.array(source_array, dtype=self.dtype)\n except:\n raise TypeError('array must consist of array-like data,' +\n 'type %s is not supported' % str(type(array)))\n source_array = np.asarray(source_array, dtype=self.dtype, order='C')\n if source_array.shape != self.shape:\n raise ValueError('Shape inconsistent: expected %s vs got %s'%(\n str(source_array.shape), str(self.shape)))\n check_call(_LIB.MXNDArraySyncCopyFromCPU(\n self.handle,\n source_array.ctypes.data_as(ctypes.c_void_p),\n ctypes.c_size_t(source_array.size)))\n\n def _slice(self, start, stop):\n \"\"\"Returns a sliced NDArray that shares memory with the current one.\n This is called through ``x[start:stop]``.\n\n Parameters\n ----------\n start : int\n Starting inclusive index of slice in the first dim.\n stop : int\n Finishing exclusive index of slice in the first dim.\n\n Returns\n -------\n `NDArray` sharing the memory with the current one sliced from\n start to stop in the first dim.\n\n Examples:\n >>> a = mx.nd.array([[1,2], [3, 4], [5, 6], [7, 8]])\n >>> a[1:2].asnumpy()\n array([[ 3., 4.]], dtype=float32)\n >>> a[1:1].asnumpy()\n array([], shape=(0, 2), dtype=float32)\n \"\"\"\n handle = NDArrayHandle()\n start, stop, _ = _get_index_range(start, stop, self.shape[0])\n\n check_call(_LIB.MXNDArraySlice(\n self.handle, mx_uint(start), mx_uint(stop), ctypes.byref(handle)))\n return NDArray(handle=handle, writable=self.writable)\n\n def _at(self, idx):\n \"\"\"Returns a view of the array sliced at `idx` in the first dim.\n This is called through ``x[idx]``.\n\n Parameters\n ----------\n idx : int\n index for slicing the `NDArray` in the first dim.\n\n Returns\n -------\n NDArray\n `NDArray` sharing the memory with the current one sliced at `idx` in the first dim.\n\n Examples\n --------\n >>> a = mx.nd.array([[1,2], [3, 4]])\n >>> a[1].asnumpy()\n array([ 3., 4.], dtype=float32)\n >>> b = mx.nd.array([1, 2, 3, 4])\n >>> b[0].asnumpy()\n array([ 1.], dtype=float32)\n \"\"\"\n handle = NDArrayHandle()\n if idx < 0:\n length = self.shape[0]\n idx += length\n if idx < 0:\n raise IndexError('index %d is out of bounds for axis 0 with size %d'\n % (idx-length, length))\n check_call(_LIB.MXNDArrayAt(\n self.handle, mx_uint(idx), ctypes.byref(handle)))\n return NDArray(handle=handle, writable=self.writable)\n\n def reshape(self, *shape, **kwargs):\n \"\"\"Returns a **view** of this array with a new shape without altering any data.\n\n Parameters\n ----------\n shape : tuple of int, or n ints\n The new shape should not change the array size, namely\n ``np.prod(new_shape)`` should be equal to ``np.prod(self.shape)``.\n Some dimensions of the shape can take special values from the set {0, -1, -2, -3, -4}.\n The significance of each is explained below:\n\n - ``0`` copy this dimension from the input to the output shape.\n\n Example::\n\n - input shape = (2,3,4), shape = (4,0,2), output shape = (4,3,2)\n - input shape = (2,3,4), shape = (2,0,0), output shape = (2,3,4)\n\n - ``-1`` infers the dimension of the output shape by using the remainder of the\n input dimensions keeping the size of the new array same as that of the input array.\n At most one dimension of shape can be -1.\n\n Example::\n\n - input shape = (2,3,4), shape = (6,1,-1), output shape = (6,1,4)\n - input shape = (2,3,4), shape = (3,-1,8), output shape = (3,1,8)\n - input shape = (2,3,4), shape=(-1,), output shape = (24,)\n\n - ``-2`` copy all/remainder of the input dimensions to the output shape.\n\n Example::\n\n - input shape = (2,3,4), shape = (-2,), output shape = (2,3,4)\n - input shape = (2,3,4), shape = (2,-2), output shape = (2,3,4)\n - input shape = (2,3,4), shape = (-2,1,1), output shape = (2,3,4,1,1)\n\n - ``-3`` use the product of two consecutive dimensions of the input shape as the\n output dimension.\n\n Example::\n\n - input shape = (2,3,4), shape = (-3,4), output shape = (6,4)\n - input shape = (2,3,4,5), shape = (-3,-3), output shape = (6,20)\n - input shape = (2,3,4), shape = (0,-3), output shape = (2,12)\n - input shape = (2,3,4), shape = (-3,-2), output shape = (6,4)\n\n - ``-4`` split one dimension of the input into two dimensions passed subsequent to\n -4 in shape (can contain -1).\n\n Example::\n\n - input shape = (2,3,4), shape = (-4,1,2,-2), output shape =(1,2,3,4)\n - input shape = (2,3,4), shape = (2,-4,-1,3,-2), output shape = (2,1,3,4)\n\n - If the argument `reverse` is set to 1, then the special values are inferred from right\n to left.\n\n Example::\n\n - without reverse=1, for input shape = (10,5,4), shape = (-1,0), output shape would be \\\n (40,5).\n - with reverse=1, output shape will be (50,4).\n\n reverse : bool, default False\n If true then the special values are inferred from right to left. Only supported as\n keyword argument.\n\n\n Returns\n -------\n NDArray\n An array with desired shape that shares data with this array.\n\n Examples\n --------\n >>> x = mx.nd.arange(0,6).reshape(2,3)\n >>> x.asnumpy()\n array([[ 0., 1., 2.],\n [ 3., 4., 5.]], dtype=float32)\n >>> y = x.reshape(3,2)\n >>> y.asnumpy()\n array([[ 0., 1.],\n [ 2., 3.],\n [ 4., 5.]], dtype=float32)\n >>> y = x.reshape(3,-1)\n >>> y.asnumpy()\n array([[ 0., 1.],\n [ 2., 3.],\n [ 4., 5.]], dtype=float32)\n >>> y = x.reshape(3,2)\n >>> y.asnumpy()\n array([[ 0., 1.],\n [ 2., 3.],\n [ 4., 5.]], dtype=float32)\n >>> y = x.reshape(-3)\n >>> y.asnumpy()\n array([ 0. 1. 2. 3. 4. 5.], dtype=float32)\n >>> y[:] = -1\n >>> x.asnumpy()\n array([[-1., -1., -1.],\n [-1., -1., -1.]], dtype=float32)\n \"\"\"\n if len(shape) == 1 and isinstance(shape[0], (list, tuple)):\n shape = shape[0]\n elif not shape:\n shape = kwargs.get('shape')\n assert shape, \"Shape must be provided.\"\n if not all(k in ['shape', 'reverse'] for k in kwargs):\n raise TypeError(\n \"Got unknown keywords in reshape: {}. \" \\\n \"Accepted keyword arguments are 'shape' and 'reverse'.\".format(\n ', '.join([k for k in kwargs if k not in ['shape', 'reverse']])))\n reverse = kwargs.get('reverse', False)\n handle = NDArrayHandle()\n\n # Actual reshape\n check_call(_LIB.MXNDArrayReshape64(self.handle,\n len(shape),\n c_array(ctypes.c_int64, shape),\n reverse,\n ctypes.byref(handle)))\n return NDArray(handle=handle, writable=self.writable)\n\n def reshape_like(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`reshape_like`.\n\n The arguments are the same as for :py:func:`reshape_like`, with\n this array as data.\n \"\"\"\n return op.reshape_like(self, *args, **kwargs)\n\n def zeros_like(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`zeros_like`.\n\n The arguments are the same as for :py:func:`zeros_like`, with\n this array as data.\n \"\"\"\n return op.zeros_like(self, *args, **kwargs)\n\n def ones_like(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`ones_like`.\n\n The arguments are the same as for :py:func:`ones_like`, with\n this array as data.\n \"\"\"\n return op.ones_like(self, *args, **kwargs)\n\n def broadcast_axes(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`broadcast_axes`.\n\n The arguments are the same as for :py:func:`broadcast_axes`, with\n this array as data.\n \"\"\"\n return op.broadcast_axes(self, *args, **kwargs)\n\n def repeat(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`repeat`.\n\n The arguments are the same as for :py:func:`repeat`, with\n this array as data.\n \"\"\"\n return op.repeat(self, *args, **kwargs)\n\n def pad(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`pad`.\n\n The arguments are the same as for :py:func:`pad`, with\n this array as data.\n \"\"\"\n return op.pad(self, *args, **kwargs)\n\n def swapaxes(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`swapaxes`.\n\n The arguments are the same as for :py:func:`swapaxes`, with\n this array as data.\n \"\"\"\n return op.swapaxes(self, *args, **kwargs)\n\n def split(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`split`.\n\n The arguments are the same as for :py:func:`split`, with\n this array as data.\n \"\"\"\n return op.split(self, *args, **kwargs)\n\n def split_v2(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`split_v2`.\n\n The arguments are the same as for :py:func:`split_v2`, with\n this array as data.\n \"\"\"\n return split_v2(self, *args, **kwargs)\n\n def slice(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`slice`.\n\n The arguments are the same as for :py:func:`slice`, with\n this array as data.\n \"\"\"\n return op.slice(self, *args, **kwargs)\n\n def slice_axis(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`slice_axis`.\n\n The arguments are the same as for :py:func:`slice_axis`, with\n this array as data.\n \"\"\"\n return op.slice_axis(self, *args, **kwargs)\n\n def slice_like(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`slice_like`.\n\n The arguments are the same as for :py:func:`slice_like`, with\n this array as data.\n \"\"\"\n return op.slice_like(self, *args, **kwargs)\n\n def take(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`take`.\n\n The arguments are the same as for :py:func:`take`, with\n this array as data.\n \"\"\"\n return op.take(self, *args, **kwargs)\n\n def one_hot(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`one_hot`.\n\n The arguments are the same as for :py:func:`one_hot`, with\n this array as data.\n \"\"\"\n return op.one_hot(self, *args, **kwargs)\n\n def pick(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`pick`.\n\n The arguments are the same as for :py:func:`pick`, with\n this array as data.\n \"\"\"\n return op.pick(self, *args, **kwargs)\n\n def sort(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`sort`.\n\n The arguments are the same as for :py:func:`sort`, with\n this array as data.\n \"\"\"\n return op.sort(self, *args, **kwargs)\n\n def topk(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`topk`.\n\n The arguments are the same as for :py:func:`topk`, with\n this array as data.\n \"\"\"\n return op.topk(self, *args, **kwargs)\n\n def argsort(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`argsort`.\n\n The arguments are the same as for :py:func:`argsort`, with\n this array as data.\n \"\"\"\n return op.argsort(self, *args, **kwargs)\n\n def argmax(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`argmax`.\n\n The arguments are the same as for :py:func:`argmax`, with\n this array as data.\n \"\"\"\n return op.argmax(self, *args, **kwargs)\n\n def argmax_channel(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`argmax_channel`.\n\n The arguments are the same as for :py:func:`argmax_channel`, with\n this array as data.\n \"\"\"\n return op.argmax_channel(self, *args, **kwargs)\n\n def argmin(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`argmin`.\n\n The arguments are the same as for :py:func:`argmin`, with\n this array as data.\n \"\"\"\n return op.argmin(self, *args, **kwargs)\n\n def clip(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`clip`.\n\n The arguments are the same as for :py:func:`clip`, with\n this array as data.\n \"\"\"\n return op.clip(self, *args, **kwargs)\n\n def abs(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`abs`.\n\n The arguments are the same as for :py:func:`abs`, with\n this array as data.\n \"\"\"\n return op.abs(self, *args, **kwargs)\n\n def sign(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`sign`.\n\n The arguments are the same as for :py:func:`sign`, with\n this array as data.\n \"\"\"\n return op.sign(self, *args, **kwargs)\n\n def flatten(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`flatten`.\n\n The arguments are the same as for :py:func:`flatten`, with\n this array as data.\n \"\"\"\n return op.flatten(self, *args, **kwargs)\n\n def shape_array(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`shape_array`.\n\n The arguments are the same as for :py:func:`shape_array`, with\n this array as data.\n \"\"\"\n return op.shape_array(self, *args, **kwargs)\n\n def size_array(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`size_array`.\n\n The arguments are the same as for :py:func:`size_array`, with\n this array as data.\n \"\"\"\n return op.size_array(self, *args, **kwargs)\n\n def expand_dims(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`expand_dims`.\n\n The arguments are the same as for :py:func:`expand_dims`, with\n this array as data.\n \"\"\"\n return op.expand_dims(self, *args, **kwargs)\n\n def tile(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`tile`.\n\n The arguments are the same as for :py:func:`tile`, with\n this array as data.\n \"\"\"\n return op.tile(self, *args, **kwargs)\n\n def transpose(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`transpose`.\n\n The arguments are the same as for :py:func:`transpose`, with\n this array as data.\n \"\"\"\n return op.transpose(self, *args, **kwargs)\n\n def flip(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`flip`.\n\n The arguments are the same as for :py:func:`flip`, with\n this array as data.\n \"\"\"\n return op.flip(self, *args, **kwargs)\n\n def depth_to_space(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`depth_to_space`.\n\n The arguments are the same as for :py:func:`depth_to_space`, with\n this array as data.\n \"\"\"\n return op.depth_to_space(self, *args, **kwargs)\n\n def space_to_depth(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`space_to_depth`.\n\n The arguments are the same as for :py:func:`space_to_depth`, with\n this array as data.\n \"\"\"\n return op.space_to_depth(self, *args, **kwargs)\n\n def diag(self, k=0, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`diag`.\n\n The arguments are the same as for :py:func:`diag`, with\n this array as data.\n \"\"\"\n return op.diag(self, k, **kwargs)\n\n def sum(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`sum`.\n\n The arguments are the same as for :py:func:`sum`, with\n this array as data.\n \"\"\"\n return op.sum(self, *args, **kwargs)\n\n def nansum(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`nansum`.\n\n The arguments are the same as for :py:func:`nansum`, with\n this array as data.\n \"\"\"\n return op.nansum(self, *args, **kwargs)\n\n def prod(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`prod`.\n\n The arguments are the same as for :py:func:`prod`, with\n this array as data.\n \"\"\"\n return op.prod(self, *args, **kwargs)\n\n def nanprod(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`nanprod`.\n\n The arguments are the same as for :py:func:`nanprod`, with\n this array as data.\n \"\"\"\n return op.nanprod(self, *args, **kwargs)\n\n def mean(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`mean`.\n\n The arguments are the same as for :py:func:`mean`, with\n this array as data.\n \"\"\"\n return op.mean(self, *args, **kwargs)\n\n def max(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`max`.\n\n The arguments are the same as for :py:func:`max`, with\n this array as data.\n \"\"\"\n return op.max(self, *args, **kwargs)\n\n def min(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`min`.\n\n The arguments are the same as for :py:func:`min`, with\n this array as data.\n \"\"\"\n return op.min(self, *args, **kwargs)\n\n def norm(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`norm`.\n\n The arguments are the same as for :py:func:`norm`, with\n this array as data.\n \"\"\"\n return op.norm(self, *args, **kwargs)\n\n def round(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`round`.\n\n The arguments are the same as for :py:func:`round`, with\n this array as data.\n \"\"\"\n return op.round(self, *args, **kwargs)\n\n def rint(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`rint`.\n\n The arguments are the same as for :py:func:`rint`, with\n this array as data.\n \"\"\"\n return op.rint(self, *args, **kwargs)\n\n def fix(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`fix`.\n\n The arguments are the same as for :py:func:`fix`, with\n this array as data.\n \"\"\"\n return op.fix(self, *args, **kwargs)\n\n def floor(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`floor`.\n\n The arguments are the same as for :py:func:`floor`, with\n this array as data.\n \"\"\"\n return op.floor(self, *args, **kwargs)\n\n def ceil(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`ceil`.\n\n The arguments are the same as for :py:func:`ceil`, with\n this array as data.\n \"\"\"\n return op.ceil(self, *args, **kwargs)\n\n def trunc(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`trunc`.\n\n The arguments are the same as for :py:func:`trunc`, with\n this array as data.\n \"\"\"\n return op.trunc(self, *args, **kwargs)\n\n def sin(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`sin`.\n\n The arguments are the same as for :py:func:`sin`, with\n this array as data.\n \"\"\"\n return op.sin(self, *args, **kwargs)\n\n def cos(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`cos`.\n\n The arguments are the same as for :py:func:`cos`, with\n this array as data.\n \"\"\"\n return op.cos(self, *args, **kwargs)\n\n def tan(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`tan`.\n\n The arguments are the same as for :py:func:`tan`, with\n this array as data.\n \"\"\"\n return op.tan(self, *args, **kwargs)\n\n def arcsin(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`arcsin`.\n\n The arguments are the same as for :py:func:`arcsin`, with\n this array as data.\n \"\"\"\n return op.arcsin(self, *args, **kwargs)\n\n def arccos(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`arccos`.\n\n The arguments are the same as for :py:func:`arccos`, with\n this array as data.\n \"\"\"\n return op.arccos(self, *args, **kwargs)\n\n def arctan(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`arctan`.\n\n The arguments are the same as for :py:func:`arctan`, with\n this array as data.\n \"\"\"\n return op.arctan(self, *args, **kwargs)\n\n def degrees(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`degrees`.\n\n The arguments are the same as for :py:func:`degrees`, with\n this array as data.\n \"\"\"\n return op.degrees(self, *args, **kwargs)\n\n def radians(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`radians`.\n\n The arguments are the same as for :py:func:`radians`, with\n this array as data.\n \"\"\"\n return op.radians(self, *args, **kwargs)\n\n def sinh(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`sinh`.\n\n The arguments are the same as for :py:func:`sinh`, with\n this array as data.\n \"\"\"\n return op.sinh(self, *args, **kwargs)\n\n def cosh(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`cosh`.\n\n The arguments are the same as for :py:func:`cosh`, with\n this array as data.\n \"\"\"\n return op.cosh(self, *args, **kwargs)\n\n def tanh(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`tanh`.\n\n The arguments are the same as for :py:func:`tanh`, with\n this array as data.\n \"\"\"\n return op.tanh(self, *args, **kwargs)\n\n def arcsinh(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`arcsinh`.\n\n The arguments are the same as for :py:func:`arcsinh`, with\n this array as data.\n \"\"\"\n return op.arcsinh(self, *args, **kwargs)\n\n def arccosh(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`arccosh`.\n\n The arguments are the same as for :py:func:`arccosh`, with\n this array as data.\n \"\"\"\n return op.arccosh(self, *args, **kwargs)\n\n def arctanh(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`arctanh`.\n\n The arguments are the same as for :py:func:`arctanh`, with\n this array as data.\n \"\"\"\n return op.arctanh(self, *args, **kwargs)\n\n def exp(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`exp`.\n\n The arguments are the same as for :py:func:`exp`, with\n this array as data.\n \"\"\"\n return op.exp(self, *args, **kwargs)\n\n def expm1(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`expm1`.\n\n The arguments are the same as for :py:func:`expm1`, with\n this array as data.\n \"\"\"\n return op.expm1(self, *args, **kwargs)\n\n def log(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`log`.\n\n The arguments are the same as for :py:func:`log`, with\n this array as data.\n \"\"\"\n return op.log(self, *args, **kwargs)\n\n def log10(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`log10`.\n\n The arguments are the same as for :py:func:`log10`, with\n this array as data.\n \"\"\"\n return op.log10(self, *args, **kwargs)\n\n def log2(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`log2`.\n\n The arguments are the same as for :py:func:`log2`, with\n this array as data.\n \"\"\"\n return op.log2(self, *args, **kwargs)\n\n def log1p(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`log1p`.\n\n The arguments are the same as for :py:func:`log1p`, with\n this array as data.\n \"\"\"\n return op.log1p(self, *args, **kwargs)\n\n def sqrt(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`sqrt`.\n\n The arguments are the same as for :py:func:`sqrt`, with\n this array as data.\n \"\"\"\n return op.sqrt(self, *args, **kwargs)\n\n def rsqrt(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`rsqrt`.\n\n The arguments are the same as for :py:func:`rsqrt`, with\n this array as data.\n \"\"\"\n return op.rsqrt(self, *args, **kwargs)\n\n def cbrt(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`cbrt`.\n\n The arguments are the same as for :py:func:`cbrt`, with\n this array as data.\n \"\"\"\n return op.cbrt(self, *args, **kwargs)\n\n def rcbrt(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`rcbrt`.\n\n The arguments are the same as for :py:func:`rcbrt`, with\n this array as data.\n \"\"\"\n return op.rcbrt(self, *args, **kwargs)\n\n def square(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`square`.\n\n The arguments are the same as for :py:func:`square`, with\n this array as data.\n \"\"\"\n return op.square(self, *args, **kwargs)\n\n def reciprocal(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`reciprocal`.\n\n The arguments are the same as for :py:func:`reciprocal`, with\n this array as data.\n \"\"\"\n return op.reciprocal(self, *args, **kwargs)\n\n def relu(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`relu`.\n\n The arguments are the same as for :py:func:`relu`, with\n this array as data.\n \"\"\"\n return op.relu(self, *args, **kwargs)\n\n def sigmoid(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`sigmoid`.\n\n The arguments are the same as for :py:func:`sigmoid`, with\n this array as data.\n \"\"\"\n return op.sigmoid(self, *args, **kwargs)\n\n def softmax(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`softmax`.\n\n The arguments are the same as for :py:func:`softmax`, with\n this array as data.\n \"\"\"\n return op.softmax(self, *args, **kwargs)\n\n def log_softmax(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`log_softmax`.\n\n The arguments are the same as for :py:func:`log_softmax`, with\n this array as data.\n \"\"\"\n return op.log_softmax(self, *args, **kwargs)\n\n def softmin(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`softmin`.\n\n The arguments are the same as for :py:func:`softmin`, with\n this array as data.\n \"\"\"\n return op.softmin(self, *args, **kwargs)\n\n def squeeze(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`squeeze`.\n\n The arguments are the same as for :py:func:`squeeze`, with\n this array as data.\n \"\"\"\n return op.squeeze(self, *args, **kwargs)\n\n # pylint: disable= undefined-variable\n def broadcast_to(self, shape):\n \"\"\"Broadcasts the input array to a new shape.\n\n Broadcasting is only allowed on axes with size 1. The new shape cannot change\n the number of dimensions.\n For example, you could broadcast from shape (2, 1) to (2, 3), but not from\n shape (2, 3) to (2, 3, 3).\n\n Parameters\n ----------\n shape : tuple of int\n The shape of the desired array.\n\n Returns\n -------\n NDArray\n A NDArray with the desired shape that is not sharing data with this\n array, even if the new shape is the same as ``self.shape``.\n\n Examples\n --------\n >>> x = mx.nd.arange(0,3).reshape((1,3,1))\n >>> x.asnumpy()\n array([[[ 0.],\n [ 1.],\n [ 2.]]], dtype=float32)\n >>> y = x.broadcast_to((2,3,3))\n >>> y.asnumpy()\n array([[[ 0., 0., 0.],\n [ 1., 1., 1.],\n [ 2., 2., 2.]],\n <BLANKLINE>\n [[ 0., 0., 0.],\n [ 1., 1., 1.],\n [ 2., 2., 2.]]], dtype=float32)\n \"\"\"\n cur_shape = self.shape\n err_str = 'operands could not be broadcast together with remapped shapes' \\\n '[original->remapped]: {} and requested shape {}'.format(cur_shape, shape)\n if len(shape) < len(cur_shape):\n raise ValueError(err_str)\n cur_shape = (1,) * (len(shape) - len(cur_shape)) + cur_shape\n cur_shape_arr = np.array(cur_shape)\n broadcasting_axes = np.nonzero(cur_shape_arr != np.array(shape))\n if (cur_shape_arr[broadcasting_axes] != 1).any():\n raise ValueError(err_str)\n if cur_shape != self.shape:\n return op.broadcast_to(self.reshape(cur_shape), shape=shape)\n else:\n return op.broadcast_to(self, shape=tuple(shape))\n # pylint: enable= undefined-variable\n\n def broadcast_like(self, other):\n \"\"\"Broadcasts the input array to the shape of other.\n\n Broadcasting is only allowed on axes with size 1. The new shape cannot change\n the number of dimensions.\n For example, you could broadcast from shape (2, 1) to (2, 3), but not from\n shape (2, 3) to (2, 3, 3).\n\n Parameters\n ----------\n other : NDArray\n Array with shape of the desired array.\n\n Returns\n -------\n NDArray\n A NDArray with the desired shape that is not sharing data with this\n array, even if the new shape is the same as ``self.shape``.\n\n Examples\n --------\n >>> x = mx.nd.arange(0,3).reshape((1,3,1))\n >>> x.asnumpy()\n array([[[ 0.],\n [ 1.],\n [ 2.]]], dtype=float32)\n >>> y = x.broadcast_like(mx.nd.ones((2,3,3)))\n >>> y.asnumpy()\n array([[[ 0., 0., 0.],\n [ 1., 1., 1.],\n [ 2., 2., 2.]],\n <BLANKLINE>\n [[ 0., 0., 0.],\n [ 1., 1., 1.],\n [ 2., 2., 2.]]], dtype=float32)\n \"\"\"\n return self.broadcast_to(other.shape)\n\n def wait_to_read(self):\n \"\"\"Waits until all previous write operations on the current array are finished.\n\n This method guarantees that all previous write operations that pushed\n into the backend engine for execution are actually finished.\n\n Examples\n --------\n >>> import time\n >>> tic = time.time()\n >>> a = mx.nd.ones((1000,1000))\n >>> b = mx.nd.dot(a, a)\n >>> print(time.time() - tic) # doctest: +SKIP\n 0.003854036331176758\n >>> b.wait_to_read()\n >>> print(time.time() - tic) # doctest: +SKIP\n 0.0893700122833252\n \"\"\"\n check_call(_LIB.MXNDArrayWaitToRead(self.handle))\n\n @property\n def ndim(self):\n \"\"\"Returns the number of dimensions of this array\n\n Examples\n --------\n >>> x = mx.nd.array([1, 2, 3, 4])\n >>> x.ndim\n 1\n >>> x = mx.nd.array([[1, 2], [3, 4]])\n >>> x.ndim\n 2\n \"\"\"\n return len(self.shape)\n\n @property\n def shape(self):\n \"\"\"Tuple of array dimensions.\n\n Examples\n --------\n >>> x = mx.nd.array([1, 2, 3, 4])\n >>> x.shape\n (4L,)\n >>> y = mx.nd.zeros((2, 3, 4))\n >>> y.shape\n (2L, 3L, 4L)\n \"\"\"\n ndim = mx_int()\n pdata = ctypes.POINTER(mx_int)()\n check_call(_LIB.MXNDArrayGetShapeEx(\n self.handle, ctypes.byref(ndim), ctypes.byref(pdata)))\n if ndim.value == -1:\n return None\n else:\n return tuple(pdata[:ndim.value]) # pylint: disable=invalid-slice-index\n\n\n @property\n def size(self):\n \"\"\"Number of elements in the array.\n\n Equivalent to the product of the array's dimensions.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = mx.nd.zeros((3, 5, 2))\n >>> x.size\n 30\n >>> np.prod(x.shape)\n 30\n \"\"\"\n size = 1\n for i in self.shape:\n size *= i\n return size\n\n @property\n def context(self):\n \"\"\"Device context of the array.\n\n Examples\n --------\n >>> x = mx.nd.array([1, 2, 3, 4])\n >>> x.context\n cpu(0)\n >>> type(x.context)\n <class 'mxnet.context.Context'>\n >>> y = mx.nd.zeros((2,3), mx.gpu(0))\n >>> y.context\n gpu(0)\n \"\"\"\n dev_typeid = ctypes.c_int()\n dev_id = ctypes.c_int()\n check_call(_LIB.MXNDArrayGetContext(\n self.handle, ctypes.byref(dev_typeid), ctypes.byref(dev_id)))\n return Context(Context.devtype2str[dev_typeid.value], dev_id.value)\n\n @property\n def dtype(self):\n \"\"\"Data-type of the array's elements.\n\n Returns\n -------\n numpy.dtype\n This NDArray's data type.\n\n Examples\n --------\n >>> x = mx.nd.zeros((2,3))\n >>> x.dtype\n <type 'numpy.float32'>\n >>> y = mx.nd.zeros((2,3), dtype='int32')\n >>> y.dtype\n <type 'numpy.int32'>\n \"\"\"\n mx_dtype = ctypes.c_int()\n check_call(_LIB.MXNDArrayGetDType(\n self.handle, ctypes.byref(mx_dtype)))\n return _DTYPE_MX_TO_NP[mx_dtype.value]\n\n @property\n def stype(self):\n \"\"\"Storage-type of the array.\n \"\"\"\n return _STORAGE_TYPE_ID_TO_STR[_storage_type(self.handle)]\n\n @property\n # pylint: disable= invalid-name, undefined-variable\n def T(self):\n \"\"\"Returns a copy of the array with axes transposed.\n\n Equivalent to ``mx.nd.transpose(self)`` except that\n self is returned if ``self.ndim < 2``.\n\n Unlike ``numpy.ndarray.T``, this function returns a copy\n rather than a view of the array unless ``self.ndim < 2``.\n\n Examples\n --------\n >>> x = mx.nd.arange(0,6).reshape((2,3))\n >>> x.asnumpy()\n array([[ 0., 1., 2.],\n [ 3., 4., 5.]], dtype=float32)\n >>> x.T.asnumpy()\n array([[ 0., 3.],\n [ 1., 4.],\n [ 2., 5.]], dtype=float32)\n\n \"\"\"\n if len(self.shape) < 2:\n return self\n return op.transpose(self)\n # pylint: enable= invalid-name, undefined-variable\n\n @property\n def _fresh_grad(self):\n \"\"\"Whether this array's corresponding gradient array\n (registered via `autograd.mark_variables`) has been\n updated by `autograd.backward` since last reset.\n\n `_fresh_grad` need to be manually set to False\n after consuming gradient (usually after updating this\n array).\n \"\"\"\n out = ctypes.c_int()\n check_call(_LIB.MXNDArrayGetGradState(self.handle, ctypes.byref(out)))\n return out.value\n\n @_fresh_grad.setter\n def _fresh_grad(self, state):\n check_call(_LIB.MXNDArraySetGradState(self.handle, ctypes.c_int(state)))\n\n def asnumpy(self):\n \"\"\"Returns a ``numpy.ndarray`` object with value copied from this array.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = x.asnumpy()\n >>> type(y)\n <type 'numpy.ndarray'>\n >>> y\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> z = mx.nd.ones((2,3), dtype='int32')\n >>> z.asnumpy()\n array([[1, 1, 1],\n [1, 1, 1]], dtype=int32)\n \"\"\"\n data = np.empty(self.shape, dtype=self.dtype)\n check_call(_LIB.MXNDArraySyncCopyToCPU(\n self.handle,\n data.ctypes.data_as(ctypes.c_void_p),\n ctypes.c_size_t(data.size)))\n return data\n\n def asscalar(self):\n \"\"\"Returns a scalar whose value is copied from this array.\n\n This function is equivalent to ``self.asnumpy()[0]``. This NDArray must have shape (1,).\n\n Examples\n --------\n >>> x = mx.nd.ones((1,), dtype='int32')\n >>> x.asscalar()\n 1\n >>> type(x.asscalar())\n <type 'numpy.int32'>\n \"\"\"\n if self.shape != (1,):\n raise ValueError(\"The current array is not a scalar\")\n return self.asnumpy()[0]\n\n def astype(self, dtype, copy=True):\n \"\"\"Returns a copy of the array after casting to a specified type.\n\n Parameters\n ----------\n dtype : numpy.dtype or str\n The type of the returned array.\n copy : bool\n Default `True`. By default, astype always returns a newly\n allocated ndarray on the same context. If this is set to\n `False`, and the dtype requested is the same as the ndarray's\n dtype, the ndarray is returned instead of a copy.\n\n Returns\n -------\n NDArray, CSRNDArray or RowSparseNDArray\n The copied array after casting to the specified type, or\n the same array if copy=False and dtype is the same as the input\n array.\n\n Examples\n --------\n >>> x = mx.nd.zeros((2,3), dtype='float32')\n >>> y = x.astype('int32')\n >>> y.dtype\n <type 'numpy.int32'>\n \"\"\"\n\n if not copy and np.dtype(dtype) == self.dtype:\n return self\n\n res = empty(self.shape, ctx=self.context, dtype=dtype)\n self.copyto(res)\n return res\n\n def copyto(self, other):\n \"\"\"Copies the value of this array to another array.\n\n If ``other`` is a ``NDArray`` object, then ``other.shape`` and\n ``self.shape`` should be the same. This function copies the value from\n ``self`` to ``other``.\n\n If ``other`` is a context, a new ``NDArray`` will be first created on\n the target context, and the value of ``self`` is copied.\n\n Parameters\n ----------\n other : NDArray or Context\n The destination array or context.\n\n Returns\n -------\n NDArray, CSRNDArray or RowSparseNDArray\n The copied array. If ``other`` is an ``NDArray``, then the return value\n and ``other`` will point to the same ``NDArray``.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.zeros((2,3), mx.gpu(0))\n >>> z = x.copyto(y)\n >>> z is y\n True\n >>> y.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.copyto(mx.gpu(0))\n <NDArray 2x3 @gpu(0)>\n\n \"\"\"\n if isinstance(other, NDArray):\n if other.handle is self.handle:\n warnings.warn('You are attempting to copy an array to itself', RuntimeWarning)\n return False\n return _internal._copyto(self, out=other)\n elif isinstance(other, Context):\n hret = NDArray(_new_alloc_handle(self.shape, other, True, self.dtype))\n return _internal._copyto(self, out=hret)\n else:\n raise TypeError('copyto does not support type ' + str(type(other)))\n\n def copy(self):\n \"\"\"Makes a copy of this ``NDArray``, keeping the same context.\n\n Returns\n -------\n NDArray, CSRNDArray or RowSparseNDArray\n The copied array\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = x.copy()\n >>> y.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n \"\"\"\n return self.copyto(self.context)\n\n def as_in_context(self, context):\n \"\"\"Returns an array on the target device with the same value as this array.\n\n If the target context is the same as ``self.context``, then ``self`` is\n returned. Otherwise, a copy is made.\n\n Parameters\n ----------\n context : Context\n The target context.\n\n Returns\n -------\n NDArray, CSRNDArray or RowSparseNDArray\n The target array.\n\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = x.as_in_context(mx.cpu())\n >>> y is x\n True\n >>> z = x.as_in_context(mx.gpu(0))\n >>> z is x\n False\n \"\"\"\n if self.context == context:\n return self\n return self.copyto(context)\n\n def attach_grad(self, grad_req='write', stype=None):\n \"\"\"Attach a gradient buffer to this NDArray, so that `backward`\n can compute gradient with respect to it.\n\n Parameters\n ----------\n grad_req : {'write', 'add', 'null'}\n How gradient will be accumulated.\n - 'write': gradient will be overwritten on every backward.\n - 'add': gradient will be added to existing value on every backward.\n - 'null': do not compute gradient for this NDArray.\n stype : str, optional\n The storage type of the gradient array. Defaults to the same stype of this NDArray.\n \"\"\"\n from . import zeros as _zeros\n if stype is not None:\n grad = _zeros(self.shape, stype=stype)\n else:\n grad = op.zeros_like(self) # pylint: disable=undefined-variable\n grad_req = _GRAD_REQ_MAP[grad_req]\n check_call(_LIB.MXAutogradMarkVariables(\n 1, ctypes.pointer(self.handle),\n ctypes.pointer(mx_uint(grad_req)),\n ctypes.pointer(grad.handle)))\n\n @property\n def grad(self):\n \"\"\"Returns gradient buffer attached to this NDArray.\"\"\"\n from . import _ndarray_cls\n hdl = NDArrayHandle()\n check_call(_LIB.MXNDArrayGetGrad(self.handle, ctypes.byref(hdl)))\n if hdl.value is None:\n return None\n return _ndarray_cls(hdl)\n\n def detach(self):\n \"\"\"Returns a new NDArray, detached from the current graph.\"\"\"\n from . import _ndarray_cls\n hdl = NDArrayHandle()\n check_call(_LIB.MXNDArrayDetach(self.handle, ctypes.byref(hdl)))\n return _ndarray_cls(hdl)\n\n def backward(self, out_grad=None, retain_graph=False, train_mode=True):\n \"\"\"Compute the gradients of this NDArray w.r.t variables.\n\n Parameters\n ----------\n out_grad : NDArray, optional\n Gradient with respect to head.\n retain_graph : bool, optional\n Whether to retain the computaion graph for another backward\n pass on the same graph. By default the computaion history\n is cleared.\n train_mode : bool, optional\n Whether to compute gradient for training or inference.\n \"\"\"\n if out_grad is None:\n ograd_handles = [NDArrayHandle(0)]\n else:\n ograd_handles = [out_grad.handle]\n\n check_call(_LIB.MXAutogradBackwardEx(\n 1, c_handle_array([self]),\n c_array(NDArrayHandle, ograd_handles),\n 0,\n ctypes.c_void_p(0),\n ctypes.c_int(retain_graph),\n ctypes.c_int(0),\n ctypes.c_int(train_mode),\n ctypes.c_void_p(0),\n ctypes.c_void_p(0)))\n\n def tostype(self, stype):\n \"\"\"Return a copy of the array with chosen storage type.\n\n See Also\n ----------\n :meth:`mxnet.ndarray.cast_storage`.\n\n Returns\n -------\n NDArray, CSRNDArray or RowSparseNDArray\n A copy of the array with the chosen storage stype\n \"\"\"\n return op.cast_storage(self, stype=stype)\n\n def to_dlpack_for_read(self):\n \"\"\"Returns a reference view of NDArray that represents as DLManagedTensor until\n all previous write operations on the current array are finished.\n\n Returns\n -------\n PyCapsule (the pointer of DLManagedTensor)\n a reference view of NDArray that represents as DLManagedTensor.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.to_dlpack_for_read(x)\n >>> type(y)\n <class 'PyCapsule'>\n >>> z = mx.nd.from_dlpack(y)\n >>> z\n [[1. 1. 1.]\n [1. 1. 1.]]\n <NDArray 2x3 @cpu(0)>\n \"\"\"\n return to_dlpack_for_read(self)\n\n def to_dlpack_for_write(self):\n \"\"\"Returns a reference view of NDArray that represents as DLManagedTensor until\n all previous read/write operations on the current array are finished.\n\n Returns\n -------\n PyCapsule (the pointer of DLManagedTensor)\n a reference view of NDArray that represents as DLManagedTensor.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> w = mx.nd.to_dlpack_for_write(x)\n >>> type(w)\n <class 'PyCapsule'>\n >>> u = mx.nd.from_dlpack(w)\n >>> u += 1\n >>> x\n [[2. 2. 2.]\n [2. 2. 2.]]\n <NDArray 2x3 @cpu(0)>\n \"\"\"\n return to_dlpack_for_write(self)\n\ndef _get_indexing_dispatch_code(key):\n \"\"\"Returns a dispatch code for calling basic or advanced indexing functions.\"\"\"\n if isinstance(key, (NDArray, np.ndarray)):\n return _NDARRAY_ADVANCED_INDEXING\n elif isinstance(key, list):\n # TODO(junwu): Add support for nested lists besides integer list\n for i in key:\n if not isinstance(i, integer_types):\n raise TypeError('Indexing NDArray only supports a list of integers as index'\n ' when key is of list type, received element=%s of type=%s'\n % (str(i), str(type(i))))\n return _NDARRAY_ADVANCED_INDEXING\n elif isinstance(key, (integer_types, py_slice)):\n return _NDARRAY_BASIC_INDEXING\n elif isinstance(key, tuple):\n for idx in key:\n if isinstance(idx, (NDArray, np.ndarray, list, tuple)):\n return _NDARRAY_ADVANCED_INDEXING\n elif not isinstance(idx, (py_slice, integer_types)):\n raise ValueError(\"NDArray does not support slicing with key %s of type %s.\"\n % (str(idx), str(type(idx))))\n return _NDARRAY_BASIC_INDEXING\n else:\n return _NDARRAY_UNSUPPORTED_INDEXING\n\n\ndef _get_index_range(start, stop, length, step=1):\n \"\"\"Given start, stop, step and array length, return\n absolute values of start, stop, and step for generating index range.\n The returned values have been compensated by adding length if they\n are less than zero for all the cases but slice(None, None, -1).\n Note that the returned value of stop is not necessarily >= 0, since\n absolute stop is -1 in the case of slice(None, None, -1).\"\"\"\n if step == 0:\n raise ValueError('step size cannot be zero')\n if length < 0:\n raise ValueError('array length cannot be less than zero')\n if step is None:\n step = 1\n if start is None:\n if step > 0:\n start = 0\n else:\n start = length - 1\n elif start < 0:\n start += length\n if start < 0:\n raise IndexError('Slicing start %d exceeds limit of %d' % (start-length, length))\n elif start >= length:\n raise IndexError('Slicing start %d exceeds limit of %d' % (start, length))\n\n if stop is None:\n if step > 0:\n stop = length\n else:\n # this supports case such as ::-1\n # stop = -1 here refers to the element before index 0,\n # instead of the last element in the array\n stop = -1\n elif stop < 0:\n stop += length\n if stop < 0:\n raise IndexError('Slicing stop %d exceeds limit of %d' % (stop-length, length))\n elif stop > length:\n raise IndexError('Slicing stop %d exceeds limit of %d' % (stop, length))\n\n return start, stop, step\n\n\ndef _get_oshape_of_gather_nd_op(dshape, ishape):\n \"\"\"Given data and index shapes, get the output `NDArray` shape.\n This basically implements the infer shape logic of op gather_nd.\"\"\"\n assert len(dshape) > 0 and len(ishape) > 0\n oshape = list(ishape[1:])\n if ishape[0] < len(dshape):\n oshape.extend(dshape[ishape[0]:])\n return tuple(oshape)\n\n\ndef _get_dim_size(start, stop, step):\n \"\"\"Given start, stop, and stop, calculate the number of elements\n of this slice.\"\"\"\n assert step != 0\n if step > 0:\n assert start < stop\n dim_size = (stop - start - 1) // step + 1\n else:\n assert stop < start\n dim_size = (start - stop - 1) // (-step) + 1\n return dim_size\n\n\ndef _get_broadcast_shape(shape1, shape2):\n \"\"\"Given two shapes that are not identical, find the shape\n that both input shapes can broadcast to.\"\"\"\n if shape1 == shape2:\n return shape1\n\n length1 = len(shape1)\n length2 = len(shape2)\n if length1 > length2:\n shape = list(shape1)\n else:\n shape = list(shape2)\n i = max(length1, length2) - 1\n for a, b in zip(shape1[::-1], shape2[::-1]):\n if a != 1 and b != 1 and a != b:\n raise ValueError('shape1=%s is not broadcastable to shape2=%s' % (shape1, shape2))\n shape[i] = max(a, b)\n i -= 1\n return tuple(shape)\n\n\ndef onehot_encode(indices, out):\n \"\"\"One-hot encoding indices into matrix out.\n\n .. note:: `onehot_encode` is deprecated. Use `one_hot` instead.\n\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _internal._onehot_encode(indices, out, out=out)\n # pylint: enable= no-member, protected-access\n\n\ndef ones(shape, ctx=None, dtype=None, **kwargs):\n \"\"\"Returns a new array filled with all ones, with the given shape and type.\n\n Parameters\n ----------\n shape : int or tuple of int or list of int\n The shape of the empty array.\n ctx : Context, optional\n An optional device context.\n Defaults to the current default context (``mxnet.context.current_context()``).\n dtype : str or numpy.dtype, optional\n An optional value type (default is `float32`).\n out : NDArray, optional\n The output NDArray (default is `None`).\n\n Returns\n -------\n NDArray\n A new array of the specified shape filled with all ones.\n\n Examples\n --------\n >>> mx.nd.ones(1).asnumpy()\n array([ 1.], dtype=float32)\n >>> mx.nd.ones((1,2), mx.gpu(0))\n <NDArray 1x2 @gpu(0)>\n >>> mx.nd.ones((1,2), dtype='float16').asnumpy()\n array([[ 1., 1.]], dtype=float16)\n \"\"\"\n # pylint: disable= unused-argument\n if ctx is None:\n ctx = current_context()\n dtype = mx_real_t if dtype is None else dtype\n # pylint: disable= no-member, protected-access\n return _internal._ones(shape=shape, ctx=ctx, dtype=dtype, **kwargs)\n # pylint: enable= no-member, protected-access\n\n\ndef full(shape, val, ctx=None, dtype=mx_real_t, out=None):\n \"\"\"Returns a new array of given shape and type, filled with the given value `val`.\n\n Parameters\n --------\n shape : int or tuple of int\n The shape of the new array.\n val : scalar\n Fill value.\n ctx : Context, optional\n Device context (default is the current default context).\n dtype : `str` or `numpy.dtype`, optional\n The data type of the returned `NDArray`. The default datatype is `float32`.\n out : NDArray, optional\n The output NDArray (default is `None`).\n\n Returns\n -------\n NDArray\n `NDArray` filled with `val`, with the given shape, ctx, and dtype.\n\n Examples\n --------\n >>> mx.nd.full(1, 2.0).asnumpy()\n array([ 2.], dtype=float32)\n >>> mx.nd.full((1, 2), 2.0, mx.gpu(0))\n <NDArray 1x2 @gpu(0)>\n >>> mx.nd.full((1, 2), 2.0, dtype='float16').asnumpy()\n array([[ 2., 2.]], dtype=float16)\n \"\"\"\n out = empty(shape, ctx, dtype) if out is None else out\n out[:] = val\n return out\n\n\ndef array(source_array, ctx=None, dtype=None):\n \"\"\"Creates an array from any object exposing the array interface.\n\n Parameters\n ----------\n source_array : array_like\n An object exposing the array interface, an object whose `__array__`\n method returns an array, or any (nested) sequence.\n ctx : Context, optional\n Device context (default is the current default context).\n dtype : str or numpy.dtype, optional\n The data type of the output array. The default dtype is ``source_array.dtype``\n if `source_array` is an `NDArray`, `float32` otherwise.\n\n Returns\n -------\n NDArray\n An `NDArray` with the same contents as the `source_array`.\n \"\"\"\n if isinstance(source_array, NDArray):\n dtype = source_array.dtype if dtype is None else dtype\n else:\n dtype = mx_real_t if dtype is None else dtype\n if not isinstance(source_array, np.ndarray):\n try:\n source_array = np.array(source_array, dtype=dtype)\n except:\n raise TypeError('source_array must be array like object')\n arr = empty(source_array.shape, ctx, dtype)\n arr[:] = source_array\n return arr\n\n\ndef moveaxis(tensor, source, destination):\n \"\"\"Moves the `source` axis into the `destination` position\n while leaving the other axes in their original order\n\n Parameters\n ----------\n tensor : mx.nd.array\n The array which axes should be reordered\n source : int or sequence of int\n Original position of the axes to move. Can be negative but must be unique.\n destination : int or sequence of int\n Destination position for each of the original axes. Can be negative but must be unique.\n\n Returns\n -------\n result : mx.nd.array\n Array with moved axes.\n\n Examples\n --------\n >>> X = mx.nd.array([[1, 2, 3], [4, 5, 6]])\n >>> mx.nd.moveaxis(X, 0, 1).shape\n (3L, 2L)\n\n >>> X = mx.nd.zeros((3, 4, 5))\n >>> mx.nd.moveaxis(X, [0, 1], [-1, -2]).shape\n (5, 4, 3)\n \"\"\"\n try:\n source = np.core.numeric.normalize_axis_tuple(source, tensor.ndim)\n except IndexError:\n raise ValueError('Source should verify 0 <= source < tensor.ndim'\n 'Got %d' % source)\n try:\n destination = np.core.numeric.normalize_axis_tuple(destination, tensor.ndim)\n except IndexError:\n raise ValueError('Destination should verify 0 <= destination < tensor.ndim (%d).'\n % tensor.ndim, 'Got %d' % destination)\n\n if len(source) != len(destination):\n raise ValueError('`source` and `destination` arguments must have '\n 'the same number of elements')\n\n order = [n for n in range(tensor.ndim) if n not in source]\n\n for dest, src in sorted(zip(destination, source)):\n order.insert(dest, src)\n\n return op.transpose(tensor, order)\n\n\n# pylint: disable= no-member, protected-access, too-many-arguments, redefined-outer-name\ndef arange(start, stop=None, step=1.0, repeat=1, infer_range=None, ctx=None, dtype=mx_real_t):\n \"\"\"Returns evenly spaced values within a given interval.\n\n Values are generated within the half-open interval [`start`, `stop`). In other\n words, the interval includes `start` but excludes `stop`. The function is\n similar to the built-in Python function `range` and to `numpy.arange`,\n but returns an `NDArray`.\n\n Parameters\n ----------\n start : number, optional\n Start of interval. The default start value is 0.\n stop : number\n End of interval.\n step : number, optional\n Spacing between values. The default step size is 1.\n repeat : int, optional\n Number of times to repeat each element. The default repeat count is 1.\n infer_range : boolean, optional\n When set to True, infer the stop position from the start, step,\n repeat, and output tensor size.\n ctx : Context, optional\n Device context. Default context is the current default context.\n dtype : str or numpy.dtype, optional\n The data type of the `NDArray`. The default datatype is `np.float32`.\n\n Returns\n -------\n NDArray\n `NDArray` of evenly spaced values in the specified range.\n\n Examples\n --------\n >>> mx.nd.arange(3).asnumpy()\n array([ 0., 1., 2.], dtype=float32)\n >>> mx.nd.arange(2, 6).asnumpy()\n array([ 2., 3., 4., 5.], dtype=float32)\n >>> mx.nd.arange(2, 6, step=2).asnumpy()\n array([ 2., 4.], dtype=float32)\n >>> mx.nd.arange(2, 6, step=1.5, repeat=2).asnumpy()\n array([ 2. , 2. , 3.5, 3.5, 5. , 5. ], dtype=float32)\n >>> mx.nd.arange(2, 6, step=2, repeat=3, dtype='int32').asnumpy()\n array([2, 2, 2, 4, 4, 4], dtype=int32)\n \"\"\"\n if infer_range is not None:\n warnings.warn('`infer_range` argument has been deprecated',\n DeprecationWarning)\n if ctx is None:\n ctx = current_context()\n return _internal._arange(start=start, stop=stop, step=step, repeat=repeat,\n infer_range=False, dtype=dtype, ctx=str(ctx))\n# pylint: enable= no-member, protected-access, too-many-arguments\n\n\n# pylint: disable= no-member, protected-access, too-many-arguments\ndef linspace(start, stop, num, endpoint=True, ctx=None, dtype=mx_real_t):\n \"\"\"Return evenly spaced numbers within a specified interval.\n\n Values are generated within the half-open interval [`start`, `stop`) or\n closed interval [start, stop] depending on whether `endpoint` is True or\n False. The function is similar to `numpy.linspace`, but returns an `NDArray`.\n\n Parameters\n ----------\n start : number\n Start of interval.\n stop : number\n End of interval, unless endpoint is set to False. In that case,\n the sequence consists of all but the last of `num + 1` evenly spaced\n samples, so that stop is excluded. Note that the step size changes\n when endpoint is False.\n num : number\n Number of samples to generate. Must be non-negative.\n endpoint : bool\n If True, stop is the last sample. Otherwise, it is not included.\n The default is True.\n ctx : Context, optional\n Device context. Default context is the current default context.\n dtype : str or numpy.dtype, optional\n The data type of the `NDArray`. The default datatype is `np.float32`.\n\n Returns\n -------\n NDArray\n `NDArray` of evenly spaced values in the specified range.\n\n Examples\n --------\n >>> mx.nd.linspace(2.0, 3.0, 5).asnumpy()\n array([ 2., 2.25., 2.5, 2.75, 3.], dtype=float32)\n >>> mx.nd.linspace(2.0, 3.0, 5, endpoint=False).asnumpy()\n array([ 2., 2.2., 2.4, 2.6, 2.8], dtype=float32)\n \"\"\"\n if ctx is None:\n ctx = current_context()\n return _internal._linspace(start=start, stop=stop, num=num,\n endpoint=endpoint, dtype=dtype, ctx=str(ctx))\n# pylint: disable= no-member, protected-access, too-many-arguments\n\n\n#pylint: disable= too-many-arguments, no-member, protected-access\ndef _ufunc_helper(lhs, rhs, fn_array, fn_scalar, lfn_scalar, rfn_scalar=None):\n \"\"\" Helper function for element-wise operation.\n The function will perform numpy-like broadcasting if needed and call different functions.\n\n Parameters\n --------\n lhs : NDArray or numeric value\n Left-hand side operand.\n\n rhs : NDArray or numeric value\n Right-hand operand,\n\n fn_array : function\n Function to be called if both lhs and rhs are of ``NDArray`` type.\n\n fn_scalar : function\n Function to be called if both lhs and rhs are numeric values.\n\n lfn_scalar : function\n Function to be called if lhs is ``NDArray`` while rhs is numeric value\n\n rfn_scalar : function\n Function to be called if lhs is numeric value while rhs is ``NDArray``;\n if none is provided, then the function is commutative, so rfn_scalar is equal to lfn_scalar\n\n Returns\n --------\n NDArray\n result array\n \"\"\"\n if isinstance(lhs, numeric_types):\n if isinstance(rhs, numeric_types):\n return fn_scalar(lhs, rhs)\n else:\n if rfn_scalar is None:\n # commutative function\n return lfn_scalar(rhs, float(lhs))\n else:\n return rfn_scalar(rhs, float(lhs))\n elif isinstance(rhs, numeric_types):\n return lfn_scalar(lhs, float(rhs))\n elif isinstance(rhs, NDArray):\n return fn_array(lhs, rhs)\n else:\n raise TypeError('type %s not supported' % str(type(rhs)))\n#pylint: enable= too-many-arguments, no-member, protected-access\n\n\ndef add(lhs, rhs):\n \"\"\"Returns element-wise sum of the input arrays with broadcasting.\n\n Equivalent to ``lhs + rhs``, ``mx.nd.broadcast_add(lhs, rhs)`` and\n ``mx.nd.broadcast_plus(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First array to be added.\n rhs : scalar or mxnet.ndarray.array\n Second array to be added.\n If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n The element-wise sum of the input arrays.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x+2).asnumpy()\n array([[ 3., 3., 3.],\n [ 3., 3., 3.]], dtype=float32)\n >>> (x+y).asnumpy()\n array([[ 1., 1., 1.],\n [ 2., 2., 2.]], dtype=float32)\n >>> mx.nd.add(x,y).asnumpy()\n array([[ 1., 1., 1.],\n [ 2., 2., 2.]], dtype=float32)\n >>> (z + y).asnumpy()\n array([[ 0., 1.],\n [ 1., 2.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_add,\n operator.add,\n _internal._plus_scalar,\n None)\n # pylint: enable= no-member, protected-access\n\n\ndef subtract(lhs, rhs):\n \"\"\"Returns element-wise difference of the input arrays with broadcasting.\n\n Equivalent to ``lhs - rhs``, ``mx.nd.broadcast_sub(lhs, rhs)`` and\n ``mx.nd.broadcast_minus(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First array to be subtracted.\n rhs : scalar or mxnet.ndarray.array\n Second array to be subtracted.\n If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n The element-wise difference of the input arrays.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x-2).asnumpy()\n array([[-1., -1., -1.],\n [-1., -1., -1.]], dtype=float32)\n >>> (x-y).asnumpy()\n array([[ 1., 1., 1.],\n [ 0., 0., 0.]], dtype=float32)\n >>> mx.nd.subtract(x,y).asnumpy()\n array([[ 1., 1., 1.],\n [ 0., 0., 0.]], dtype=float32)\n >>> (z-y).asnumpy()\n array([[ 0., 1.],\n [-1., 0.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_sub,\n operator.sub,\n _internal._minus_scalar,\n _internal._rminus_scalar)\n # pylint: enable= no-member, protected-access\n\n\ndef multiply(lhs, rhs):\n \"\"\"Returns element-wise product of the input arrays with broadcasting.\n\n Equivalent to ``lhs * rhs`` and ``mx.nd.broadcast_mul(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First array to be multiplied.\n rhs : scalar or mxnet.ndarray.array\n Second array to be multiplied.\n If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n The element-wise multiplication of the input arrays.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x*2).asnumpy()\n array([[ 2., 2., 2.],\n [ 2., 2., 2.]], dtype=float32)\n >>> (x*y).asnumpy()\n array([[ 0., 0., 0.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.multiply(x, y).asnumpy()\n array([[ 0., 0., 0.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (z*y).asnumpy()\n array([[ 0., 0.],\n [ 0., 1.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_mul,\n operator.mul,\n _internal._mul_scalar,\n None)\n # pylint: enable= no-member, protected-access\n\n\ndef divide(lhs, rhs):\n \"\"\"Returns element-wise division of the input arrays with broadcasting.\n\n Equivalent to ``lhs / rhs`` and ``mx.nd.broadcast_div(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First array in division.\n rhs : scalar or mxnet.ndarray.array\n Second array in division.\n The arrays to be divided. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n The element-wise division of the input arrays.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))*6\n >>> y = mx.nd.ones((2,1))*2\n >>> x.asnumpy()\n array([[ 6., 6., 6.],\n [ 6., 6., 6.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 2.],\n [ 2.]], dtype=float32)\n >>> x/2\n <NDArray 2x3 @cpu(0)>\n >>> (x/3).asnumpy()\n array([[ 2., 2., 2.],\n [ 2., 2., 2.]], dtype=float32)\n >>> (x/y).asnumpy()\n array([[ 3., 3., 3.],\n [ 3., 3., 3.]], dtype=float32)\n >>> mx.nd.divide(x,y).asnumpy()\n array([[ 3., 3., 3.],\n [ 3., 3., 3.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_div,\n operator.truediv,\n _internal._div_scalar,\n _internal._rdiv_scalar)\n # pylint: enable= no-member, protected-access\n\n\ndef modulo(lhs, rhs):\n \"\"\"Returns element-wise modulo of the input arrays with broadcasting.\n\n Equivalent to ``lhs % rhs`` and ``mx.nd.broadcast_mod(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First array in modulo.\n rhs : scalar or mxnet.ndarray.array\n Second array in modulo.\n The arrays to be taken modulo. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n The element-wise modulo of the input arrays.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))*6\n >>> y = mx.nd.ones((2,1))*4\n >>> x.asnumpy()\n array([[ 6., 6., 6.],\n [ 6., 6., 6.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 4.],\n [ 4.]], dtype=float32)\n >>> x%5\n <NDArray 2x3 @cpu(0)>\n >>> (x%5).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (x%y).asnumpy()\n array([[ 2., 2., 2.],\n [ 2., 2., 2.]], dtype=float32)\n >>> mx.nd.modulo(x,y).asnumpy()\n array([[ 2., 2., 2.],\n [ 2., 2., 2.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_mod,\n operator.mod,\n _internal._mod_scalar,\n _internal._rmod_scalar)\n # pylint: enable= no-member, protected-access\n\n\ndef power(base, exp):\n \"\"\"Returns result of first array elements raised to powers from second array, element-wise\n with broadcasting.\n\n Equivalent to ``base ** exp`` and ``mx.nd.broadcast_power(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n base : scalar or NDArray\n The base array\n exp : scalar or NDArray\n The exponent array. If ``base.shape != exp.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n --------\n NDArray\n The bases in x raised to the exponents in y.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))*2\n >>> y = mx.nd.arange(1,3).reshape((2,1))\n >>> z = mx.nd.arange(1,3).reshape((2,1))\n >>> x.asnumpy()\n array([[ 2., 2., 2.],\n [ 2., 2., 2.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 1.],\n [ 2.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 1.],\n [ 2.]], dtype=float32)\n >>> (x**2).asnumpy()\n array([[ 4., 4., 4.],\n [ 4., 4., 4.]], dtype=float32)\n >>> (x**y).asnumpy()\n array([[ 2., 2., 2.],\n [ 4., 4., 4.]], dtype=float32)\n >>> mx.nd.power(x,y).asnumpy()\n array([[ 2., 2., 2.],\n [ 4., 4., 4.]], dtype=float32)\n >>> (z**y).asnumpy()\n array([[ 1.],\n [ 4.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n base,\n exp,\n op.broadcast_power,\n operator.pow,\n _internal._power_scalar,\n _internal._rpower_scalar)\n # pylint: enable= no-member, protected-access\n\n\ndef maximum(lhs, rhs):\n \"\"\"Returns element-wise maximum of the input arrays with broadcasting.\n\n Equivalent to ``mx.nd.broadcast_maximum(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First array to be compared.\n rhs : scalar or mxnet.ndarray.array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n The element-wise maximum of the input arrays.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> mx.nd.maximum(x, 2).asnumpy()\n array([[ 2., 2., 2.],\n [ 2., 2., 2.]], dtype=float32)\n >>> mx.nd.maximum(x, y).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.maximum(y, z).asnumpy()\n array([[ 0., 1.],\n [ 1., 1.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_maximum,\n lambda x, y: x if x > y else y,\n _internal._maximum_scalar,\n None)\n # pylint: enable= no-member, protected-access\n\n\ndef minimum(lhs, rhs):\n \"\"\"Returns element-wise minimum of the input arrays with broadcasting.\n\n Equivalent to ``mx.nd.broadcast_minimum(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First array to be compared.\n rhs : scalar or mxnet.ndarray.array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n The element-wise minimum of the input arrays.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> mx.nd.minimum(x, 2).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.minimum(x, y).asnumpy()\n array([[ 0., 0., 0.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.minimum(z, y).asnumpy()\n array([[ 0., 0.],\n [ 0., 1.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_minimum,\n lambda x, y: x if x < y else y,\n _internal._minimum_scalar,\n None)\n # pylint: enable= no-member, protected-access\n\n\ndef equal(lhs, rhs):\n \"\"\"Returns the result of element-wise **equal to** (==) comparison operation with\n broadcasting.\n\n For each element in input arrays, return 1(true) if corresponding elements are same,\n otherwise return 0(false).\n\n Equivalent to ``lhs == rhs`` and ``mx.nd.broadcast_equal(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First array to be compared.\n rhs : scalar or mxnet.ndarray.array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n Output array of boolean values.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x == 1).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (x == y).asnumpy()\n array([[ 0., 0., 0.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.equal(x,y).asnumpy()\n array([[ 0., 0., 0.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (z == y).asnumpy()\n array([[ 1., 0.],\n [ 0., 1.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_equal,\n lambda x, y: 1 if x == y else 0,\n _internal._equal_scalar,\n None)\n # pylint: enable= no-member, protected-access\n\n\ndef not_equal(lhs, rhs):\n \"\"\"Returns the result of element-wise **not equal to** (!=) comparison operation\n with broadcasting.\n\n For each element in input arrays, return 1(true) if corresponding elements are different,\n otherwise return 0(false).\n\n Equivalent to ``lhs != rhs`` and ``mx.nd.broadcast_not_equal(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First array to be compared.\n rhs : scalar or mxnet.ndarray.array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n Output array of boolean values.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (z == y).asnumpy()\n array([[ 1., 0.],\n [ 0., 1.]], dtype=float32)\n >>> (x != 1).asnumpy()\n array([[ 0., 0., 0.],\n [ 0., 0., 0.]], dtype=float32)\n >>> (x != y).asnumpy()\n array([[ 1., 1., 1.],\n [ 0., 0., 0.]], dtype=float32)\n >>> mx.nd.not_equal(x, y).asnumpy()\n array([[ 1., 1., 1.],\n [ 0., 0., 0.]], dtype=float32)\n >>> (z != y).asnumpy()\n array([[ 0., 1.],\n [ 1., 0.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_not_equal,\n lambda x, y: 1 if x != y else 0,\n _internal._not_equal_scalar,\n None)\n # pylint: enable= no-member, protected-access\n\n\ndef greater(lhs, rhs):\n \"\"\"Returns the result of element-wise **greater than** (>) comparison operation\n with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements are greater than rhs,\n otherwise return 0(false).\n\n Equivalent to ``lhs > rhs`` and ``mx.nd.broadcast_greater(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First array to be compared.\n rhs : scalar or mxnet.ndarray.array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n Output array of boolean values.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x > 1).asnumpy()\n array([[ 0., 0., 0.],\n [ 0., 0., 0.]], dtype=float32)\n >>> (x > y).asnumpy()\n array([[ 1., 1., 1.],\n [ 0., 0., 0.]], dtype=float32)\n >>> mx.nd.greater(x, y).asnumpy()\n array([[ 1., 1., 1.],\n [ 0., 0., 0.]], dtype=float32)\n >>> (z > y).asnumpy()\n array([[ 0., 1.],\n [ 0., 0.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_greater,\n lambda x, y: 1 if x > y else 0,\n _internal._greater_scalar,\n _internal._lesser_scalar)\n # pylint: enable= no-member, protected-access\n\n\ndef greater_equal(lhs, rhs):\n \"\"\"Returns the result of element-wise **greater than or equal to** (>=) comparison\n operation with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements are greater than equal to rhs,\n otherwise return 0(false).\n\n Equivalent to ``lhs >= rhs`` and ``mx.nd.broadcast_greater_equal(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First array to be compared.\n rhs : scalar or mxnet.ndarray.array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n Output array of boolean values.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x >= 1).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (x >= y).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.greater_equal(x, y).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (z >= y).asnumpy()\n array([[ 1., 1.],\n [ 0., 1.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_greater_equal,\n lambda x, y: 1 if x >= y else 0,\n _internal._greater_equal_scalar,\n _internal._lesser_equal_scalar)\n # pylint: enable= no-member, protected-access\n\n\ndef lesser(lhs, rhs):\n \"\"\"Returns the result of element-wise **lesser than** (<) comparison operation\n with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements are less than rhs,\n otherwise return 0(false).\n\n Equivalent to ``lhs < rhs`` and ``mx.nd.broadcast_lesser(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First array to be compared.\n rhs : scalar or mxnet.ndarray.array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n Output array of boolean values.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x < 1).asnumpy()\n array([[ 0., 0., 0.],\n [ 0., 0., 0.]], dtype=float32)\n >>> (x < y).asnumpy()\n array([[ 0., 0., 0.],\n [ 0., 0., 0.]], dtype=float32)\n >>> mx.nd.lesser(x, y).asnumpy()\n array([[ 0., 0., 0.],\n [ 0., 0., 0.]], dtype=float32)\n >>> (z < y).asnumpy()\n array([[ 0., 0.],\n [ 1., 0.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_lesser,\n lambda x, y: 1 if x < y else 0,\n _internal._lesser_scalar,\n _internal._greater_scalar)\n # pylint: enable= no-member, protected-access\n\n\ndef lesser_equal(lhs, rhs):\n \"\"\"Returns the result of element-wise **lesser than or equal to** (<=) comparison\n operation with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements are\n lesser than equal to rhs, otherwise return 0(false).\n\n Equivalent to ``lhs <= rhs`` and ``mx.nd.broadcast_lesser_equal(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First array to be compared.\n rhs : scalar or mxnet.ndarray.array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n Output array of boolean values.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x <= 1).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (x <= y).asnumpy()\n array([[ 0., 0., 0.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.lesser_equal(x, y).asnumpy()\n array([[ 0., 0., 0.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (z <= y).asnumpy()\n array([[ 1., 0.],\n [ 1., 1.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_lesser_equal,\n lambda x, y: 1 if x <= y else 0,\n _internal._lesser_equal_scalar,\n _internal._greater_equal_scalar)\n # pylint: enable= no-member, protected-access\n\ndef logical_and(lhs, rhs):\n \"\"\"Returns the result of element-wise **logical and** comparison\n operation with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements and rhs elements\n are true, otherwise return 0(false).\n\n Equivalent to ``lhs and rhs`` and ``mx.nd.broadcast_logical_and(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First input of the function.\n rhs : scalar or mxnet.ndarray.array\n Second input of the function. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n Output array of boolean values.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> mx.nd.logical_and(x, 1).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.logical_and(x, y).asnumpy()\n array([[ 0., 0., 0.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.logical_and(z, y).asnumpy()\n array([[ 0., 0.],\n [ 0., 1.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_logical_and,\n lambda x, y: 1 if x and y else 0,\n _internal._logical_and_scalar,\n None)\n # pylint: enable= no-member, protected-access\n\ndef logical_or(lhs, rhs):\n \"\"\"Returns the result of element-wise **logical or** comparison\n operation with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements or rhs elements\n are true, otherwise return 0(false).\n\n Equivalent to ``lhs or rhs`` and ``mx.nd.broadcast_logical_or(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First input of the function.\n rhs : scalar or mxnet.ndarray.array\n Second input of the function. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n Output array of boolean values.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> mx.nd.logical_or(x, 1).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.logical_or(x, y).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.logical_or(z, y).asnumpy()\n array([[ 0., 1.],\n [ 1., 1.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_logical_or,\n lambda x, y: 1 if x or y else 0,\n _internal._logical_or_scalar,\n None)\n # pylint: enable= no-member, protected-access\n\ndef logical_xor(lhs, rhs):\n \"\"\"Returns the result of element-wise **logical xor** comparison\n operation with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements or rhs elements\n are true, otherwise return 0(false).\n\n Equivalent to ``bool(lhs) ^ bool(rhs)`` and ``mx.nd.broadcast_logical_xor(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or mxnet.ndarray.array\n First input of the function.\n rhs : scalar or mxnet.ndarray.array\n Second input of the function. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n Output array of boolean values.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> mx.nd.logical_xor(x, y).asnumpy()\n array([[ 1., 1., 1.],\n [ 0., 0., 0.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_logical_xor,\n lambda x, y: 1 if bool(x) ^ bool(y) else 0,\n _internal._logical_xor_scalar,\n None)\n # pylint: enable= no-member, protected-access\n\ndef true_divide(lhs, rhs):\n\n \"\"\"This function is similar to :meth:`divide`.\n \"\"\"\n return divide(lhs, rhs)\n\n\ndef concatenate(arrays, axis=0, always_copy=True):\n \"\"\"DEPRECATED, use ``concat`` instead\n\n Parameters\n ----------\n arrays : list of `NDArray`\n Arrays to be concatenate. They must have identical shape except\n the first dimension. They also must have the same data type.\n axis : int\n The axis along which to concatenate.\n always_copy : bool\n Default `True`. When not `True`, if the arrays only contain one\n `NDArray`, that element will be returned directly, avoid copying.\n\n Returns\n -------\n NDArray\n An `NDArray` that lives on the same context as `arrays[0].context`.\n \"\"\"\n assert isinstance(arrays, list)\n assert len(arrays) > 0\n assert isinstance(arrays[0], NDArray)\n\n if not always_copy and len(arrays) == 1:\n return arrays[0]\n\n shape_axis = arrays[0].shape[axis]\n shape_rest1 = arrays[0].shape[0:axis]\n shape_rest2 = arrays[0].shape[axis+1:]\n dtype = arrays[0].dtype\n for arr in arrays[1:]:\n shape_axis += arr.shape[axis]\n assert shape_rest1 == arr.shape[0:axis]\n assert shape_rest2 == arr.shape[axis+1:]\n assert dtype == arr.dtype\n ret_shape = shape_rest1 + (shape_axis,) + shape_rest2\n ret = empty(ret_shape, ctx=arrays[0].context, dtype=dtype)\n\n idx = 0\n begin = [0 for _ in ret_shape]\n end = list(ret_shape)\n for arr in arrays:\n if axis == 0:\n ret[idx:idx+arr.shape[0]] = arr\n else:\n begin[axis] = idx\n end[axis] = idx+arr.shape[axis]\n # pylint: disable=no-member,protected-access\n _internal._crop_assign(ret, arr, out=ret,\n begin=tuple(begin),\n end=tuple(end))\n # pylint: enable=no-member,protected-access\n idx += arr.shape[axis]\n\n return ret\n\n\n# pylint: disable=redefined-outer-name\ndef imdecode(str_img, clip_rect=(0, 0, 0, 0), out=None, index=0, channels=3, mean=None):\n \"\"\"DEPRECATED, use mx.img instead\n\n Parameters\n ----------\n str_img : str\n Binary image data\n clip_rect : iterable of 4 int\n Clip decoded image to rectangle (x0, y0, x1, y1).\n out : NDArray\n Output buffer. Can be 3 dimensional (c, h, w) or 4 dimensional (n, c, h, w).\n index : int\n Output decoded image to i-th slice of 4 dimensional buffer.\n channels : int\n Number of channels to output. Decode to grey scale when channels = 1.\n mean : NDArray\n Subtract mean from decode image before outputing.\n \"\"\"\n # pylint: disable= no-member, protected-access, too-many-arguments\n if mean is None:\n mean = NDArray(_new_empty_handle())\n if out is None:\n return _internal._imdecode(mean, index,\n clip_rect[0],\n clip_rect[1],\n clip_rect[2],\n clip_rect[3],\n channels,\n len(str_img),\n str_img=str_img)\n else:\n return _internal._imdecode(mean, index,\n clip_rect[0],\n clip_rect[1],\n clip_rect[2],\n clip_rect[3],\n channels,\n len(str_img),\n str_img=str_img,\n out=out)\n\n\ndef zeros(shape, ctx=None, dtype=None, **kwargs):\n \"\"\"Returns a new array filled with all zeros, with the given shape and type.\n\n Parameters\n ----------\n shape : int or tuple of int\n The shape of the empty array.\n ctx : Context, optional\n An optional device context (default is the current default context).\n dtype : str or numpy.dtype, optional\n An optional value type (default is `float32`).\n out : NDArray, optional\n The output NDArray (default is `None`).\n\n Returns\n -------\n NDArray\n A created array\n\n Examples\n --------\n >>> mx.nd.zeros(1).asnumpy()\n array([ 0.], dtype=float32)\n >>> mx.nd.zeros((1,2), mx.gpu(0))\n <NDArray 1x2 @gpu(0)>\n >>> mx.nd.zeros((1,2), mx.gpu(0), 'float16').asnumpy()\n array([[ 0., 0.]], dtype=float16)\n \"\"\"\n # pylint: disable= unused-argument\n if ctx is None:\n ctx = current_context()\n dtype = mx_real_t if dtype is None else dtype\n # pylint: disable= no-member, protected-access\n return _internal._zeros(shape=shape, ctx=ctx, dtype=dtype, **kwargs)\n # pylint: enable= no-member, protected-access\n\ndef eye(N, M=0, k=0, ctx=None, dtype=None, **kwargs):\n \"\"\"Return a 2-D array with ones on the diagonal and zeros elsewhere.\n\n Parameters\n ----------\n N: int\n Number of rows in the output.\n M: int, optional\n Number of columns in the output. If 0, defaults to N.\n k: int, optional\n Index of the diagonal: 0 (the default) refers to the main diagonal,\n a positive value refers to an upper diagonal,\n and a negative value to a lower diagonal.\n ctx: Context, optional\n An optional device context (default is the current default context)\n dtype: str or numpy.dtype, optional\n An optional value type (default is `float32`)\n\n Returns\n -------\n NDArray\n A created array\n\n Examples\n --------\n >>> mx.nd.eye(2)\n [[ 1. 0.]\n [ 0. 1.]]\n <NDArray 2x2 @cpu(0)>\n >>> mx.nd.eye(2, 3, 1)\n [[ 0. 1. 0.]\n [ 0. 0. 1.]]\n <NDArray 2x3 @cpu(0)>\n \"\"\"\n # pylint: disable= unused-argument\n if ctx is None:\n ctx = current_context()\n dtype = mx_real_t if dtype is None else dtype\n # pylint: disable= no-member, protected-access\n return _internal._eye(N=N, M=M, k=k, ctx=ctx, dtype=dtype, **kwargs)\n # pylint: enable= no-member, protected-access\n\n\ndef empty(shape, ctx=None, dtype=None):\n \"\"\"Returns a new array of given shape and type, without initializing entries.\n\n Parameters\n ----------\n shape : int or tuple of int\n The shape of the empty array.\n ctx : Context, optional\n An optional device context (default is the current default context).\n dtype : str or numpy.dtype, optional\n An optional value type (default is `float32`).\n\n Returns\n -------\n NDArray\n A created array.\n\n \"\"\"\n if isinstance(shape, int):\n shape = (shape, )\n if ctx is None:\n ctx = current_context()\n if dtype is None:\n dtype = mx_real_t\n return NDArray(handle=_new_alloc_handle(shape, ctx, False, dtype))\n\n\n# pylint: disable= redefined-builtin\ndef histogram(a, bins=10, range=None):\n \"\"\"Compute the histogram of the input data.\n\n Parameters\n ----------\n a : NDArray\n Input data. The histogram is computed over the flattened array.\n bins : int or sequence of scalars\n If bins is an int, it defines the number of equal-width bins in the\n given range (10, by default). If bins is a sequence, it defines the bin edges,\n including the rightmost edge, allowing for non-uniform bin widths.\n range : (float, float), optional\n The lower and upper range of the bins. If not provided, range is simply (a.min(), a.max()).\n Values outside the range are ignored. The first element of the range must be less than or\n equal to the second. range affects the automatic bin computation as well, the range will\n be equally divided by the number of bins.\n\n Returns\n -------\n NDArray\n A created array.\n\n \"\"\"\n\n # pylint: disable= no-member, protected-access\n if isinstance(bins, NDArray):\n return _internal._histogram(data=a, bins=bins)\n elif isinstance(bins, integer_types):\n if range is None:\n warnings.warn(\"range is not specified, using numpy's result \"\n \"to ensure consistency with numpy\")\n res, bin_bounds = np.histogram(a.asnumpy(), bins=bins)\n return array(res), array(bin_bounds)\n return _internal._histogram(data=a, bin_cnt=bins, range=range)\n raise ValueError(\"bins argument should be either an integer or an NDArray\")\n # pylint: enable= no-member, protected-access, redefined-builtin\n\ndef split_v2(ary, indices_or_sections, axis=0, squeeze_axis=False):\n \"\"\"Split an array into multiple sub-arrays.\n\n Parameters\n ----------\n ary : NDArray\n Array to be divided into sub-arrays.\n indices_or_sections : int or tuple of ints\n If `indices_or_sections` is an integer, N, the array will be divided\n into N equal arrays along `axis`. If such a split is not possible,\n an error is raised.\n If `indices_or_sections` is a 1-D array of sorted integers, the entries\n indicate where along `axis` the array is split. For example,\n ``[2, 3]`` would, for ``axis=0``, result in\n - ary[:2]\n - ary[2:3]\n - ary[3:]\n If an index exceeds the dimension of the array along `axis`,\n an empty sub-array is returned correspondingly.\n axis : int, optional\n The axis along which to split, default is 0.\n squeeze_axis: boolean, optional\n Whether to squeeze the axis of sub-arrays or not, only useful when size\n of the sub-arrays are 1 on the `axis`. Default is False.\n\n Returns\n -------\n NDArray\n A created array.\n\n \"\"\"\n indices = []\n axis_size = ary.shape[axis]\n if isinstance(indices_or_sections, int):\n sections = indices_or_sections\n if axis_size % sections:\n raise ValueError('array split does not result in an equal division')\n section_size = int(axis_size / sections)\n indices = [i * section_size for i in range(sections)]\n elif isinstance(indices_or_sections, tuple):\n indices = [0] + list(indices_or_sections)\n else:\n raise ValueError('indices_or_sections must either int or tuple of ints')\n return _internal._split_v2(ary, indices, axis, squeeze_axis)\n\nPyCapsuleDestructor = ctypes.CFUNCTYPE(None, ctypes.c_void_p)\n_c_str_dltensor = c_str('dltensor')\n_c_str_used_dltensor = c_str('used_dltensor')\n\ndef _dlpack_deleter(pycapsule):\n pycapsule = ctypes.c_void_p(pycapsule)\n if ctypes.pythonapi.PyCapsule_IsValid(pycapsule, _c_str_dltensor):\n ptr = ctypes.c_void_p(\n ctypes.pythonapi.PyCapsule_GetPointer(pycapsule, _c_str_dltensor))\n check_call(_LIB.MXNDArrayCallDLPackDeleter(ptr))\n\n_c_dlpack_deleter = PyCapsuleDestructor(_dlpack_deleter)\n\ndef to_dlpack_for_read(data):\n \"\"\"Returns a reference view of NDArray that represents as DLManagedTensor until\n all previous write operations on the current array are finished.\n\n Parameters\n ----------\n data: NDArray\n input data.\n\n Returns\n -------\n PyCapsule (the pointer of DLManagedTensor)\n a reference view of NDArray that represents as DLManagedTensor.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.to_dlpack_for_read(x)\n >>> type(y)\n <class 'PyCapsule'>\n >>> z = mx.nd.from_dlpack(y)\n >>> z\n [[1. 1. 1.]\n [1. 1. 1.]]\n <NDArray 2x3 @cpu(0)>\n \"\"\"\n data.wait_to_read()\n dlpack = DLPackHandle()\n check_call(_LIB.MXNDArrayToDLPack(data.handle, ctypes.byref(dlpack)))\n return ctypes.pythonapi.PyCapsule_New(dlpack, _c_str_dltensor, _c_dlpack_deleter)\n\ndef to_dlpack_for_write(data):\n \"\"\"Returns a reference view of NDArray that represents as DLManagedTensor until\n all previous read/write operations on the current array are finished.\n\n Parameters\n ----------\n data: NDArray\n input data.\n\n Returns\n -------\n PyCapsule (the pointer of DLManagedTensor)\n a reference view of NDArray that represents as DLManagedTensor.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> w = mx.nd.to_dlpack_for_write(x)\n >>> type(w)\n <class 'PyCapsule'>\n >>> u = mx.nd.from_dlpack(w)\n >>> u += 1\n >>> x\n [[2. 2. 2.]\n [2. 2. 2.]]\n <NDArray 2x3 @cpu(0)>\n \"\"\"\n check_call(_LIB.MXNDArrayWaitToWrite(data.handle))\n dlpack = DLPackHandle()\n check_call(_LIB.MXNDArrayToDLPack(data.handle, ctypes.byref(dlpack)))\n return ctypes.pythonapi.PyCapsule_New(dlpack, _c_str_dltensor, _c_dlpack_deleter)\n\ndef from_dlpack(dlpack):\n \"\"\"Returns a NDArray backed by a dlpack tensor.\n\n Parameters\n ----------\n dlpack: PyCapsule (the pointer of DLManagedTensor)\n input data\n\n Returns\n -------\n NDArray\n a NDArray backed by a dlpack tensor\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.to_dlpack_for_read(x)\n >>> type(y)\n <class 'PyCapsule'>\n >>> z = mx.nd.from_dlpack(y)\n >>> type(z)\n <class 'mxnet.ndarray.ndarray.NDArray'>\n >>> z\n [[ 1. 1. 1.]\n [ 1. 1. 1.]]\n <NDArray 2x3 @cpu(0)>\n\n >>> w = mx.nd.to_dlpack_for_write(x)\n >>> type(w)\n <class 'PyCapsule'>\n >>> u = mx.nd.from_dlpack(w)\n >>> u += 1\n >>> x\n [[2. 2. 2.]\n [2. 2. 2.]]\n <NDArray 2x3 @cpu(0)>\n \"\"\"\n handle = NDArrayHandle()\n dlpack = ctypes.py_object(dlpack)\n assert ctypes.pythonapi.PyCapsule_IsValid(dlpack, _c_str_dltensor), ValueError(\n 'Invalid DLPack Tensor. DLTensor capsules can be consumed only once.')\n dlpack_handle = ctypes.c_void_p(ctypes.pythonapi.PyCapsule_GetPointer(dlpack, _c_str_dltensor))\n check_call(_LIB.MXNDArrayFromDLPack(dlpack_handle, ctypes.byref(handle)))\n # Rename PyCapsule (DLPack)\n ctypes.pythonapi.PyCapsule_SetName(dlpack, _c_str_used_dltensor)\n # delete the deleter of the old dlpack\n ctypes.pythonapi.PyCapsule_SetDestructor(dlpack, None)\n return NDArray(handle=handle)\n\nclass DLContext(ctypes.Structure):\n _fields_ = [(\"device_type\", ctypes.c_int),\n (\"device_id\", ctypes.c_int)]\n\n\nclass DLDataType(ctypes.Structure):\n _fields_ = [(\"type_code\", ctypes.c_uint8),\n (\"bits\", ctypes.c_uint8),\n (\"lanes\", ctypes.c_uint16)]\n TYPE_MAP = {\n \"int32\": (0, 32, 1),\n \"int64\": (0, 64, 1),\n \"bool\": (1, 1, 1),\n \"uint32\": (1, 32, 1),\n \"uint64\": (1, 64, 1),\n \"float32\": (2, 32, 1),\n \"float64\": (2, 64, 1),\n }\n\n\nclass DLTensor(ctypes.Structure):\n _fields_ = [(\"data\", ctypes.c_void_p),\n (\"ctx\", DLContext),\n (\"ndim\", ctypes.c_int),\n (\"dtype\", DLDataType),\n (\"shape\", ctypes.POINTER(ctypes.c_int64)),\n (\"strides\", ctypes.POINTER(ctypes.c_int64)),\n (\"byte_offset\", ctypes.c_uint64)]\n\nclass DLManagedTensor(ctypes.Structure):\n pass\n\n\nDeleterFunc = ctypes.CFUNCTYPE(None, ctypes.POINTER(DLManagedTensor))\n\n\nDLManagedTensor._fields_ = [(\"dl_tensor\", DLTensor), # pylint: disable=protected-access\n (\"manager_ctx\", ctypes.c_void_p),\n (\"deleter\", DeleterFunc)]\n\n\n@DeleterFunc\ndef dl_managed_tensor_deleter(dl_managed_tensor_handle):\n void_p = dl_managed_tensor_handle.contents.manager_ctx\n pyobj = ctypes.cast(void_p, ctypes.py_object)\n ctypes.pythonapi.Py_DecRef(pyobj)\n\n\ndef from_numpy(ndarray, zero_copy=True):\n \"\"\"Returns an MXNet's NDArray backed by Numpy's ndarray.\n\n Parameters\n ----------\n ndarray: numpy.ndarray\n input data\n\n zero_copy: bool\n Whether we use DLPack's zero-copy conversion to convert to MXNet's NDArray.\n This is only available for c-contiguous arrays, i.e. array.flags[C_CONTIGUOUS] == True.\n\n Returns\n -------\n NDArray\n a NDArray backed by a dlpack tensor\n\n \"\"\"\n\n def _make_manager_ctx(obj):\n pyobj = ctypes.py_object(obj)\n void_p = ctypes.c_void_p.from_buffer(pyobj)\n ctypes.pythonapi.Py_IncRef(pyobj)\n return void_p\n\n def _make_dl_tensor(array):\n if str(array.dtype) not in DLDataType.TYPE_MAP:\n raise ValueError(str(array.dtype) + \" is not supported.\")\n dl_tensor = DLTensor()\n dl_tensor.data = array.ctypes.data_as(ctypes.c_void_p)\n dl_tensor.ctx = DLContext(1, 0)\n dl_tensor.ndim = array.ndim\n dl_tensor.dtype = DLDataType.TYPE_MAP[str(array.dtype)]\n dl_tensor.shape = array.ctypes.shape_as(ctypes.c_int64)\n dl_tensor.strides = None\n dl_tensor.byte_offset = 0\n return dl_tensor\n\n def _make_dl_managed_tensor(array):\n c_obj = DLManagedTensor()\n c_obj.dl_tensor = _make_dl_tensor(array)\n c_obj.manager_ctx = _make_manager_ctx(array)\n c_obj.deleter = dl_managed_tensor_deleter\n return c_obj\n\n if not zero_copy:\n return array(ndarray, dtype=ndarray.dtype)\n\n if not ndarray.flags['C_CONTIGUOUS']:\n raise ValueError(\"Only c-contiguous arrays are supported for zero-copy\")\n c_obj = _make_dl_managed_tensor(ndarray)\n address = ctypes.addressof(c_obj)\n address = ctypes.cast(address, ctypes.c_void_p)\n handle = NDArrayHandle()\n check_call(_LIB.MXNDArrayFromDLPack(address, ctypes.byref(handle)))\n return NDArray(handle=handle)\n" ]
[ [ "numpy.reshape", "numpy.transpose" ], [ "numpy.asarray", "numpy.core.numeric.normalize_axis_tuple", "numpy.dtype", "numpy.broadcast_to", "numpy.prod", "numpy.array", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ivan2kh/pysparnn
[ "c53f98b27635f721bdccac61d2c3530386bcb741" ]
[ "pysparnn/cluster_index.py" ]
[ "# Copyright (c) 2016-present, Facebook, Inc.\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. An additional grant\n# of patent rights can be found in the PATENTS file in the same directory.\n\"\"\"Defines a cluster pruing search structure to do K-NN Queries\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport collections as _collections\nimport random as _random\n\nimport numpy as _np\n\nimport pysparnn.matrix_distance\n\n\ndef _k_best(tuple_list, k):\n \"\"\"For a list of tuples [(distance, value), ...] - Get the k-best tuples by\n distance.\n Args:\n tuple_list: List of tuples. (distance, value)\n k: Number of tuples to return.\n \"\"\"\n tuple_lst = sorted(tuple_list, key=lambda x: x[0],\n reverse=False)[:k]\n\n return tuple_lst\n\n\ndef _filter_unique(tuple_list):\n \"\"\"For a list of tuples [(distance, value), ...] - filter out duplicate\n values.\n Args:\n tuple_list: List of tuples. (distance, value)\n \"\"\"\n\n added = set()\n ret = []\n for distance, value in tuple_list:\n if not value in added:\n ret.append((distance, value))\n added.add(value)\n return ret\n\n\ndef _filter_distance(results, return_distance):\n \"\"\"For a list of tuples [(distance, value), ...] - optionally filter out\n the distance elements.\n Args:\n tuple_list: List of tuples. (distance, value)\n return_distance: boolean to determine if distances should be returned.\n \"\"\"\n if return_distance:\n return results\n else:\n return list([x for y, x in results])\n\n\nclass ClusterIndex(object):\n \"\"\"Search structure which gives speedup at slight loss of recall.\n\n Uses cluster pruning structure as defined in:\n http://nlp.stanford.edu/IR-book/html/htmledition/cluster-pruning-1.html\n\n tldr - searching for a document in an index of K documents is naievely\n O(K). However you can create a tree structure where the first level\n is O(sqrt(K)) and each of the leaves are also O(sqrt(K)).\n\n You randomly pick sqrt(K) items to be in the top level. Then for\n the K doccuments you assign it to the closest neighbor in the top\n level.\n\n This breaks up one O(K) search into O(2 * sqrt(K)) searches which\n is much much faster when K is big.\n\n This generalizes to h levels. The runtime becomes:\n O(h * h_root(K))\n \"\"\"\n\n def __init__(self, features, records_data,\n distance_type=pysparnn.matrix_distance.CosineDistance,\n matrix_size=None,\n parent=None):\n \"\"\"Create a search index composed of recursively defined\n matricies. Does recursive KNN search. See class docstring for a\n description of the method.\n\n Args:\n features: A csr_matrix with rows that represent records\n (corresponding to the elements in records_data) and columns\n that describe a point in space for each row.\n records_data: Data to return when a doc is matched. Index of\n corresponds to records_features.\n distance_type: Class that defines the distance measure to use.\n matrix_size: Ideal size for matrix multiplication. This controls\n the depth of the tree. Defaults to 2 levels (approx). Highly\n reccomended that the default value is used.\n \"\"\"\n\n self.is_terminal = False\n self.parent = parent\n self.distance_type = distance_type\n self.desired_matrix_size = matrix_size\n features = distance_type.features_to_matrix(features)\n num_records = features.shape[0]\n\n if matrix_size is None:\n matrix_size = max(int(_np.sqrt(num_records)), 1000)\n else:\n matrix_size = int(matrix_size)\n\n self.matrix_size = matrix_size\n\n num_levels = _np.log(num_records) / _np.log(self.matrix_size)\n\n if num_levels <= 1.4:\n self.is_terminal = True\n self.root = distance_type(features, records_data)\n else:\n self.is_terminal = False\n records_data = _np.array(records_data)\n\n records_index = list(_np.arange(features.shape[0]))\n clusters_size = min(self.matrix_size, num_records)\n clusters_selection = _random.sample(records_index, clusters_size)\n clusters_selection = features[clusters_selection]\n\n item_to_clusters = _collections.defaultdict(list)\n\n root = distance_type(clusters_selection,\n list(_np.arange(clusters_selection.shape[0])))\n\n root.remove_near_duplicates()\n root = distance_type(root.matrix,\n list(_np.arange(root.matrix.shape[0])))\n\n rng_step = self.matrix_size\n for rng in range(0, features.shape[0], rng_step):\n max_rng = min(rng + rng_step, features.shape[0])\n records_rng = features[rng:max_rng]\n for i, clstrs in enumerate(root.nearest_search(records_rng)):\n _random.shuffle(clstrs)\n for _, cluster in _k_best(clstrs, k=1):\n item_to_clusters[cluster].append(i + rng)\n\n clusters = []\n cluster_keeps = []\n for k, clust_sel in enumerate(clusters_selection):\n clustr = item_to_clusters[k]\n if len(clustr) > 0:\n index = ClusterIndex(self.distance_type.vstack(features[clustr]),\n records_data[clustr],\n distance_type=distance_type,\n matrix_size=self.matrix_size,\n parent=self)\n\n clusters.append(index)\n cluster_keeps.append(clust_sel)\n\n cluster_keeps = self.distance_type.vstack(cluster_keeps)\n clusters = _np.array(clusters)\n\n self.root = distance_type(cluster_keeps, clusters)\n\n def insert(self, feature, record):\n \"\"\"Insert a single record into the index.\n\n Args:\n feature: feature vector\n record: record to return as the result of a search\n \"\"\"\n feature = self.distance_type.features_to_matrix(feature)\n nearest = self\n while not nearest.is_terminal:\n nearest = nearest.root.nearest_search(feature)\n _, nearest = nearest[0][0]\n\n cluster_index = nearest\n parent_index = cluster_index.parent\n while parent_index and cluster_index.matrix_size * 2 < \\\n len(cluster_index.root.get_records()):\n cluster_index = parent_index\n parent_index = cluster_index.parent\n\n cluster_index._reindex(feature, record)\n\n def _get_child_data(self):\n \"\"\"Get all of the features and corresponding records represented in the\n full tree structure.\n\n Returns:\n A tuple of (list(features), list(records)).\n \"\"\"\n\n if self.is_terminal:\n return [self.root.get_feature_matrix()], [self.root.get_records()]\n else:\n result_features = []\n result_records = []\n\n for c in self.root.get_records():\n features, records = c._get_child_data()\n\n result_features.extend(features)\n result_records.extend(records)\n\n return result_features, result_records\n\n def _reindex(self, feature=None, record=None):\n \"\"\"Rebuild the search index. Optionally add a record. This is used\n when inserting records to the index.\n\n Args:\n feature: feature vector\n record: record to return as the result of a search\n \"\"\"\n\n features, records = self._get_child_data()\n\n flat_rec = []\n for x in records:\n flat_rec.extend(x)\n\n if feature is not None and record is not None:\n features.append(feature)\n flat_rec.append(record)\n\n self.__init__(self.distance_type.vstack(features), flat_rec, self.distance_type,\n self.desired_matrix_size, self.parent)\n\n def _search(self, features, k=1, k_clusters=1):\n \"\"\"Find the closest item(s) for each feature_list in.\n\n Args:\n features: A matrix with rows that represent records\n (corresponding to the elements in records_data) and columns\n that describe a point in space for each row.\n k: Return the k closest results.\n k_clusters: number of branches (clusters) to search at each level.\n This increases recall at the cost of some speed.\n\n Returns:\n For each element in features_list, return the k-nearest items\n and their distance score\n [[(score1_1, item1_1), ..., (score1_k, item1_k)],\n [(score2_1, item2_1), ..., (score2_k, item2_k)], ...]\n \"\"\"\n if self.is_terminal:\n nearest = self.root.nearest_search(features)\n return [r[:k] for r in nearest]\n else:\n ret = []\n nearest = self.root.nearest_search(features)\n\n for search_i, nearest_clusters in enumerate(nearest):\n curr_ret = []\n\n for cluster_i, distance_cluster in enumerate(nearest_clusters):\n distance, cluster = distance_cluster\n cluster_items = cluster.search(features[search_i], k=k,\n k_clusters=k_clusters)\n\n for elements in cluster_items:\n if len(elements) > 0:\n curr_ret.extend(elements)\n\n # if we have k elements and we have searched at least\n # k_clusters then we are done\n if len(curr_ret) >= k and cluster_i + 1 >= k_clusters:\n break\n\n ret.append(_k_best(curr_ret, k))\n return ret\n\n def search(self, features, k=1, k_clusters=1,\n return_distance=True):\n \"\"\"Find the closest item(s) for each feature_list in the index.\n\n Args:\n features: A matrix with rows that represent records\n (corresponding to the elements in records_data) and columns\n that describe a point in space for each row.\n k: Return the k closest results.\n k_clusters: number of branches (clusters) to search at each level.\n This increases recall at the cost of some speed.\n\n Returns:\n For each element in features_list, return the k-nearest items\n and (optionally) their distance score\n [[(score1_1, item1_1), ..., (score1_k, item1_k)],\n [(score2_1, item2_1), ..., (score2_k, item2_k)], ...]\n\n Note: if return_distance == False then the scores are omitted\n [[item1_1, ..., item1_k],\n [item2_1, ..., item2_k], ...]\n \"\"\"\n\n # search no more than 1k records at once\n # helps keap the matrix multiplies small\n batch_size = 1000\n results = []\n rng_step = batch_size\n features = self.distance_type.features_to_matrix(features)\n for rng in range(0, features.shape[0], rng_step):\n max_rng = min(rng + rng_step, features.shape[0])\n records_rng = features[rng:max_rng]\n\n results.extend(self._search(features=records_rng,\n k=k,\n k_clusters=k_clusters))\n\n return [_filter_distance(res, return_distance) for res in results]\n\n def _print_structure(self, tabs=''):\n \"\"\"Pretty print the tree index structure's matrix sizes\"\"\"\n print(tabs + str(self.root.matrix.shape[0]))\n if not self.is_terminal:\n for index in self.root.records_data:\n index._print_structure(tabs + ' ')\n\n def _max_depth(self):\n \"\"\"Yield the max depth of the tree index\"\"\"\n if not self.is_terminal:\n max_dep = 0\n for index in self.root.records_data:\n max_dep = max(max_dep, index._max_depth())\n return 1 + max_dep\n else:\n return 1\n\n def _matrix_sizes(self, ret=None):\n \"\"\"Return all of the matrix sizes within the index\"\"\"\n if ret is None:\n ret = []\n ret.append(len(self.root.records_data))\n if not self.is_terminal:\n for index in self.root.records_data:\n ret.extend(index._matrix_sizes())\n return ret\n\n\nclass MultiClusterIndex(object):\n \"\"\"Search structure which provides query speedup at the loss of recall.\n\n There are two components to this.\n\n = Cluster Indexes =\n Uses cluster pruning index structure as defined in:\n http://nlp.stanford.edu/IR-book/html/htmledition/cluster-pruning-1.html\n\n Refer to ClusterIndex documentation.\n\n = Multiple Indexes =\n The MultiClusterIndex creates multiple ClusterIndexes. This method\n gives better recall at the cost of allocating more memory. The\n ClusterIndexes are created by randomly picking representative clusters.\n The randomization tends to do a pretty good job but it is not perfect.\n Elements can be assigned to clusters that are far from an optimal match.\n Creating more Indexes (random cluster allocations) increases the chances\n of finding a good match.\n\n There are three perameters that impact recall. Will discuss them all\n here:\n 1) MuitiClusterIndex(matrix_size)\n This impacts the tree structure (see cluster index documentation).\n Has a good default value. By increasing this value your index will\n behave increasingly like brute force search and you will loose query\n efficiency. If matrix_size is greater than your number of records\n you get brute force search.\n 2) MuitiClusterIndex.search(k_clusters)\n Number of clusters to check when looking for records. This increases\n recall at the cost of query speed. Can be specified dynamically.\n 3) MuitiClusterIndex(num_indexes)\n Number of indexes to generate. This increases recall at the cost of\n query speed. It also increases memory usage. It can only be\n specified at index construction time.\n\n Compared to (2) this argument gives better recall and has comparable\n speed. This statement assumes default (automatic) matrix_size is\n used.\n Scenario 1:\n\n (a) num_indexes=2, k_clusters=1\n (b) num_indexes=1, k_clusters=2\n\n (a) will have better recall but consume 2x the memory. (a) will be\n slightly slower than (b).\n\n Scenario 2:\n\n (a) num_indexes=2, k_clusters=1, matrix_size >> records\n (b) num_indexes=1, k_clusters=2, matrix_size >> records\n\n This means that each index does a brute force search. (a) and (b)\n will have the same recall. (a) will be 2x slower than (b). (a) will\n consume 2x the memory of (b).\n\n Scenario 1 will be much faster than Scenario 2 for large data.\n Scenario 2 will have better recall than Scenario 1.\n \"\"\"\n\n def __init__(self, features, records_data,\n distance_type=pysparnn.matrix_distance.CosineDistance,\n matrix_size=None, num_indexes=2):\n \"\"\"Create a search index composed of multtiple ClusterIndexes. See\n class docstring for a description of the method.\n\n Args:\n features: A matrix with rows that represent records\n (corresponding to the elements in records_data) and columns\n that describe a point in space for each row.\n records_data: Data to return when a doc is matched. Index of\n corresponds to records_features.\n distance_type: Class that defines the distance measure to use.\n matrix_size: Ideal size for matrix multiplication. This controls\n the depth of the tree. Defaults to 2 levels (approx). Highly\n reccomended that the default value is used.\n num_indexes: Number of ClusterIndexes to construct. Improves recall\n at the cost of memory.\n \"\"\"\n\n self.indexes = []\n for _ in range(num_indexes):\n self.indexes.append((ClusterIndex(features, records_data,\n distance_type, matrix_size)))\n\n def insert(self, feature, record):\n \"\"\"Insert a single record into the index.\n\n Args:\n feature: feature vector\n record: record to return as the result of a search\n \"\"\"\n for ind in self.indexes:\n ind.insert(feature, record)\n\n def search(self, features, k=1, k_clusters=1,\n return_distance=True, num_indexes=None):\n \"\"\"Find the closest item(s) for each feature_list in the index.\n\n Args:\n features: A matrix with rows that represent records\n (corresponding to the elements in records_data) and columns\n that describe a point in space for each row.\n k: Return the k closest results.\n k_clusters: number of branches (clusters) to search at each level\n within each index. This increases recall at the cost of some\n speed.\n\n num_indexes: number of indexes to search. This increases recall at\n the cost of some speed. Can not be larger than the number of\n num_indexes that was specified in the constructor. Defaults to\n searching all indexes.\n\n Returns:\n For each element in features_list, return the k-nearest items\n and (optionally) their distance score\n [[(score1_1, item1_1), ..., (score1_k, item1_k)],\n [(score2_1, item2_1), ..., (score2_k, item2_k)], ...]\n\n Note: if return_distance == False then the scores are omitted\n [[item1_1, ..., item1_k],\n [item2_1, ..., item2_k], ...]\n \"\"\"\n results = []\n if num_indexes is None:\n num_indexes = len(self.indexes)\n for ind in self.indexes[:num_indexes]:\n results.append(ind.search(features, k, k_clusters, True))\n ret = []\n for r in _np.hstack(results):\n ret.append(\n _filter_distance(\n _k_best(_filter_unique(r), k),\n return_distance\n )\n )\n\n return ret\n" ]
[ [ "numpy.hstack", "numpy.log", "numpy.sqrt", "numpy.arange", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
InnovativeInventor/GerryChain
[ "4ee30472072b26f86bf6349b5a1dc90412a4acc1" ]
[ "tests/test_make_graph.py" ]
[ "import pathlib\nfrom tempfile import TemporaryDirectory\nfrom unittest.mock import patch\n\nimport geopandas as gp\nimport pandas\nimport pytest\nfrom shapely.geometry import Polygon\n\nfrom gerrychain.graph import Graph\nfrom gerrychain.graph.geo import GeometryError\n\n\[email protected]\ndef geodataframe():\n a = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])\n b = Polygon([(0, 1), (0, 2), (1, 2), (1, 1)])\n c = Polygon([(1, 0), (1, 1), (2, 1), (2, 0)])\n d = Polygon([(1, 1), (1, 2), (2, 2), (2, 1)])\n df = gp.GeoDataFrame({\"ID\": [\"a\", \"b\", \"c\", \"d\"], \"geometry\": [a, b, c, d]})\n df.crs = \"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs\"\n return df\n\n\[email protected]\ndef gdf_with_data(geodataframe):\n geodataframe[\"data\"] = list(range(len(geodataframe)))\n geodataframe[\"data2\"] = list(range(len(geodataframe)))\n return geodataframe\n\n\[email protected]\ndef geodataframe_with_boundary():\n \"\"\"\n abe\n ade\n ace\n \"\"\"\n a = Polygon([(0, 0), (0, 1), (0, 2), (0, 3), (1, 3), (1, 2), (1, 1), (1, 0)])\n b = Polygon([(1, 2), (1, 3), (2, 3), (2, 2)])\n c = Polygon([(1, 0), (1, 1), (2, 1), (2, 0)])\n d = Polygon([(1, 1), (1, 2), (2, 2), (2, 1)])\n e = Polygon([(2, 0), (2, 1), (2, 2), (2, 3), (3, 3), (3, 2), (3, 1), (3, 0)])\n df = gp.GeoDataFrame({\"ID\": [\"a\", \"b\", \"c\", \"d\", \"e\"], \"geometry\": [a, b, c, d, e]})\n df.crs = \"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs\"\n return df\n\n\[email protected]\ndef shapefile(gdf_with_data):\n with TemporaryDirectory() as d:\n filepath = pathlib.Path(d) / \"temp.shp\"\n filename = str(filepath.absolute())\n gdf_with_data.to_file(filename)\n yield filename\n\n\[email protected]\ndef target_file():\n with TemporaryDirectory() as d:\n filepath = pathlib.Path(d) / \"temp.shp\"\n filename = str(filepath.absolute())\n yield filename\n\n\ndef test_add_data_to_graph_can_handle_column_names_that_start_with_numbers():\n graph = Graph([(\"01\", \"02\"), (\"02\", \"03\"), (\"03\", \"01\")])\n df = pandas.DataFrame({\"16SenDVote\": [20, 30, 50], \"node\": [\"01\", \"02\", \"03\"]})\n df = df.set_index(\"node\")\n\n graph.add_data(df, [\"16SenDVote\"])\n\n assert graph.nodes[\"01\"][\"16SenDVote\"] == 20\n assert graph.nodes[\"02\"][\"16SenDVote\"] == 30\n assert graph.nodes[\"03\"][\"16SenDVote\"] == 50\n\n\ndef test_join_can_handle_right_index():\n graph = Graph([(\"01\", \"02\"), (\"02\", \"03\"), (\"03\", \"01\")])\n df = pandas.DataFrame({\"16SenDVote\": [20, 30, 50], \"node\": [\"01\", \"02\", \"03\"]})\n\n graph.join(df, [\"16SenDVote\"], right_index=\"node\")\n\n assert graph.nodes[\"01\"][\"16SenDVote\"] == 20\n assert graph.nodes[\"02\"][\"16SenDVote\"] == 30\n assert graph.nodes[\"03\"][\"16SenDVote\"] == 50\n\n\ndef test_make_graph_from_dataframe_creates_graph(geodataframe):\n graph = Graph.from_geodataframe(geodataframe)\n assert isinstance(graph, Graph)\n\n\ndef test_make_graph_from_dataframe_preserves_df_index(geodataframe):\n df = geodataframe.set_index(\"ID\")\n graph = Graph.from_geodataframe(df)\n assert set(graph.nodes) == {\"a\", \"b\", \"c\", \"d\"}\n\n\ndef test_make_graph_from_dataframe_gives_correct_graph(geodataframe):\n df = geodataframe.set_index(\"ID\")\n graph = Graph.from_geodataframe(df)\n\n assert edge_set_equal(\n set(graph.edges), {(\"a\", \"b\"), (\"a\", \"c\"), (\"b\", \"d\"), (\"c\", \"d\")}\n )\n\n\ndef test_make_graph_works_with_queen_adjacency(geodataframe):\n df = geodataframe.set_index(\"ID\")\n graph = Graph.from_geodataframe(df, adjacency=\"queen\")\n\n assert edge_set_equal(\n set(graph.edges),\n {(\"a\", \"b\"), (\"a\", \"c\"), (\"b\", \"d\"), (\"c\", \"d\"), (\"a\", \"d\"), (\"b\", \"c\")},\n )\n\n\ndef test_can_pass_queen_or_rook_strings_to_control_adjacency(geodataframe):\n df = geodataframe.set_index(\"ID\")\n graph = Graph.from_geodataframe(df, adjacency=\"queen\")\n\n assert edge_set_equal(\n set(graph.edges),\n {(\"a\", \"b\"), (\"a\", \"c\"), (\"b\", \"d\"), (\"c\", \"d\"), (\"a\", \"d\"), (\"b\", \"c\")},\n )\n\n\ndef test_can_insist_on_not_reprojecting(geodataframe):\n df = geodataframe.set_index(\"ID\")\n graph = Graph.from_geodataframe(df, reproject=False)\n\n for node in (\"a\", \"b\", \"c\", \"d\"):\n assert graph.nodes[node][\"area\"] == 1\n\n for edge in graph.edges:\n assert graph.edges[edge][\"shared_perim\"] == 1\n\n\ndef test_does_not_reproject_by_default(geodataframe):\n df = geodataframe.set_index(\"ID\")\n graph = Graph.from_geodataframe(df)\n\n for node in (\"a\", \"b\", \"c\", \"d\"):\n assert graph.nodes[node][\"area\"] == 1.0\n\n for edge in graph.edges:\n assert graph.edges[edge][\"shared_perim\"] == 1.0\n\n\ndef test_reproject(geodataframe):\n # I don't know what the areas and perimeters are in UTM for these made-up polygons,\n # but I'm pretty sure they're not 1.\n df = geodataframe.set_index(\"ID\")\n graph = Graph.from_geodataframe(df, reproject=True)\n\n for node in (\"a\", \"b\", \"c\", \"d\"):\n assert graph.nodes[node][\"area\"] != 1\n\n for edge in graph.edges:\n assert graph.edges[edge][\"shared_perim\"] != 1\n\n\ndef test_identifies_boundary_nodes(geodataframe_with_boundary):\n df = geodataframe_with_boundary.set_index(\"ID\")\n graph = Graph.from_geodataframe(df)\n\n for node in (\"a\", \"b\", \"c\", \"e\"):\n assert graph.nodes[node][\"boundary_node\"]\n assert not graph.nodes[\"d\"][\"boundary_node\"]\n\n\ndef test_computes_boundary_perims(geodataframe_with_boundary):\n df = geodataframe_with_boundary.set_index(\"ID\")\n graph = Graph.from_geodataframe(df, reproject=False)\n\n expected = {\"a\": 5, \"e\": 5, \"b\": 1, \"c\": 1}\n\n for node, value in expected.items():\n assert graph.nodes[node][\"boundary_perim\"] == value\n\n\ndef edge_set_equal(set1, set2):\n return {(y, x) for x, y in set1} | set1 == {(y, x) for x, y in set2} | set2\n\n\ndef test_from_file_adds_all_data_by_default(shapefile):\n graph = Graph.from_file(shapefile)\n\n assert all(\"data\" in node_data for node_data in graph.nodes.values())\n assert all(\"data2\" in node_data for node_data in graph.nodes.values())\n\n\ndef test_from_file_and_then_to_json_does_not_error(shapefile, target_file):\n graph = Graph.from_file(shapefile)\n\n # Even the geometry column is copied to the graph\n assert all(\"geometry\" in node_data for node_data in graph.nodes.values())\n\n graph.to_json(target_file)\n\n\ndef test_from_file_and_then_to_json_with_geometries(shapefile, target_file):\n graph = Graph.from_file(shapefile)\n\n # Even the geometry column is copied to the graph\n assert all(\"geometry\" in node_data for node_data in graph.nodes.values())\n\n graph.to_json(target_file, include_geometries_as_geojson=True)\n\n\ndef test_graph_warns_for_islands():\n graph = Graph()\n graph.add_node(0)\n\n with pytest.warns(Warning):\n graph.warn_for_islands()\n\n\ndef test_graph_raises_if_crs_is_missing_when_reprojecting(geodataframe):\n geodataframe.crs = None\n\n with pytest.raises(ValueError):\n Graph.from_geodataframe(geodataframe, reproject=True)\n\n\ndef test_raises_geometry_error_if_invalid_geometry(shapefile):\n with patch(\"gerrychain.graph.geo.explain_validity\") as explain:\n explain.return_value = \"Invalid geometry\"\n with pytest.raises(GeometryError):\n Graph.from_file(shapefile, ignore_errors=False)\n\n\ndef test_can_ignore_errors_while_making_graph(shapefile):\n with patch(\"gerrychain.graph.geo.explain_validity\") as explain:\n explain.return_value = \"Invalid geometry\"\n assert Graph.from_file(shapefile, ignore_errors=True)\n\n\ndef test_data_and_geometry(gdf_with_data):\n df = gdf_with_data\n graph = Graph.from_geodataframe(df, cols_to_add=[\"data\",\"data2\"])\n assert graph.geometry is df.geometry\n #graph.add_data(df[[\"data\"]])\n assert (graph.data[\"data\"] == df[\"data\"]).all()\n #graph.add_data(df[[\"data2\"]])\n assert list(graph.data.columns) == [\"data\", \"data2\"]\n" ]
[ [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
Y0mingZhang/pytorch-lightning
[ "f9b9cdb0d1d4e26d25fe13f19f12ea88690aa0a8", "4610fddb19d502e534b5c5d77c3dfd6f2e5359a5" ]
[ "pytorch_lightning/trainer/connectors/logger_connector/result.py", "pytorch_lightning/loggers/neptune.py" ]
[ "# Copyright The PyTorch Lightning team.\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 collections.abc import Generator\nfrom dataclasses import asdict, dataclass, replace\nfrom functools import partial, wraps\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union\n\nimport torch\nfrom torchmetrics import Metric\nfrom typing_extensions import TypedDict\n\nfrom pytorch_lightning.core.mixins import DeviceDtypeModuleMixin\nfrom pytorch_lightning.utilities import rank_zero_warn\nfrom pytorch_lightning.utilities.apply_func import apply_to_collection, apply_to_collections, move_data_to_device\nfrom pytorch_lightning.utilities.data import extract_batch_size\nfrom pytorch_lightning.utilities.exceptions import MisconfigurationException\nfrom pytorch_lightning.utilities.memory import recursive_detach\nfrom pytorch_lightning.utilities.metrics import metrics_to_scalars\nfrom pytorch_lightning.utilities.warnings import WarningCache\n\n# TODO(@tchaton): Typing-pickle issue on python<3.7 (https://github.com/cloudpipe/cloudpickle/pull/318)\n_IN_METRIC = Any # Union[Metric, torch.Tensor] # Do not include scalars as they were converted to tensors\n_OUT_METRIC = Union[torch.Tensor, Dict[str, torch.Tensor]]\n_PBAR_METRIC = Union[float, Dict[str, float]]\n_OUT_DICT = Dict[str, _OUT_METRIC]\n_PBAR_DICT = Dict[str, _PBAR_METRIC]\n\n\nclass _METRICS(TypedDict):\n callback: _OUT_DICT\n log: _OUT_DICT\n pbar: _PBAR_DICT\n\n\nwarning_cache = WarningCache()\n\n\n@dataclass\nclass _Sync:\n fn: Optional[Callable] = None\n _should: bool = False\n rank_zero_only: bool = False\n op: Optional[str] = None\n group: Optional[Any] = None\n\n def __post_init__(self) -> None:\n self._generate_sync_fn()\n\n @property\n def should(self) -> bool:\n return self._should\n\n @should.setter\n def should(self, should: bool) -> None:\n self._should = should\n # `self._fn` needs to be re-generated.\n self._generate_sync_fn()\n\n def _generate_sync_fn(self) -> None:\n \"\"\"Used to compute the syncing function and cache it.\"\"\"\n fn = self.no_op if self.fn is None or not self.should or self.rank_zero_only else self.fn\n # save the function as `_fn` as the meta are being re-created and the object references need to match.\n # ignore typing, bad support for `partial`: mypy/issues/1484\n self._fn: Callable = partial(fn, reduce_op=self.op, group=self.group) # type: ignore [arg-type]\n\n @property\n def __call__(self) -> Any:\n return self._fn\n\n @staticmethod\n def no_op(value: Any, *_: Any, **__: Any) -> Any:\n return value\n\n\n@dataclass\nclass _Metadata:\n fx: str\n name: str\n prog_bar: bool = False\n logger: bool = True\n on_step: bool = False\n on_epoch: bool = True\n reduce_fx: Callable = torch.mean\n enable_graph: bool = False\n dataloader_idx: Optional[int] = None\n metric_attribute: Optional[str] = None\n _sync: Optional[_Sync] = None\n\n def __post_init__(self) -> None:\n if not self.on_step and not self.on_epoch:\n raise MisconfigurationException(\"`self.log(on_step=False, on_epoch=False)` is not useful.\")\n self._parse_reduce_fx()\n\n def _parse_reduce_fx(self) -> None:\n error = (\n \"Only `self.log(..., reduce_fx={min,max,mean,sum})` are currently supported.\"\n \" Please, open an issue in `https://github.com/PyTorchLightning/pytorch-lightning/issues`.\"\n f\" Found: {self.reduce_fx}\"\n )\n if isinstance(self.reduce_fx, str):\n reduce_fx = self.reduce_fx.lower()\n if reduce_fx == \"avg\":\n reduce_fx = \"mean\"\n if reduce_fx not in (\"min\", \"max\", \"mean\", \"sum\"):\n raise MisconfigurationException(error)\n self.reduce_fx = getattr(torch, reduce_fx)\n elif self.is_custom_reduction:\n raise MisconfigurationException(error)\n\n @property\n def sync(self) -> _Sync:\n assert self._sync is not None\n return self._sync\n\n @sync.setter\n def sync(self, sync: _Sync) -> None:\n if sync.op is None:\n sync.op = self.reduce_fx.__name__\n self._sync = sync\n\n @property\n def forked(self) -> bool:\n return self.on_step and self.on_epoch\n\n def forked_name(self, on_step: bool) -> str:\n if self.forked:\n return f'{self.name}_{\"step\" if on_step else \"epoch\"}'\n return self.name\n\n @property\n def is_mean_reduction(self) -> bool:\n return self.reduce_fx is torch.mean\n\n @property\n def is_sum_reduction(self) -> bool:\n return self.reduce_fx in (torch.sum, sum)\n\n @property\n def is_max_reduction(self) -> bool:\n return self.reduce_fx in (torch.max, max)\n\n @property\n def is_min_reduction(self) -> bool:\n return self.reduce_fx in (torch.min, min)\n\n @property\n def is_custom_reduction(self) -> bool:\n return not (self.is_mean_reduction or self.is_max_reduction or self.is_min_reduction or self.is_sum_reduction)\n\n def __getstate__(self) -> dict:\n # drop the `sync.fn` to avoid potential pickle errors\n # need to drop `fn` first otherwise `asdict` produces a `RecursionError`\n copy = replace(self, _sync=replace(self.sync, fn=None))\n d = asdict(copy)\n # delete the `None` value so it does not override\n del d[\"_sync\"][\"fn\"]\n return d\n\n def __setstate__(self, state: dict, sync_fn: Optional[Callable] = None) -> None:\n d = {**state, \"_sync\": _Sync(**state[\"_sync\"], fn=sync_fn)}\n self.__dict__.update(d)\n\n @classmethod\n def _reconstruct(cls, state: dict, sync_fn: Optional[Callable] = None) -> \"_Metadata\":\n meta = cls(state[\"fx\"], state[\"name\"])\n meta.__setstate__(state, sync_fn=sync_fn)\n return meta\n\n\nclass ResultMetric(Metric, DeviceDtypeModuleMixin):\n \"\"\"Wraps the value provided to `:meth:`~pytorch_lightning.core.lightning.LightningModule.log`\"\"\"\n\n def __init__(self, metadata: _Metadata, is_tensor: bool) -> None:\n super().__init__()\n self.is_tensor = is_tensor\n self.meta = metadata\n self.has_reset = False\n if is_tensor:\n self.add_state(\"value\", torch.tensor(0, dtype=torch.float), dist_reduce_fx=torch.sum)\n if self.meta.is_mean_reduction:\n self.add_state(\"cumulated_batch_size\", torch.tensor(0, dtype=torch.float), dist_reduce_fx=torch.sum)\n\n def update(self, value: _IN_METRIC, batch_size: torch.Tensor) -> None:\n if self.is_tensor:\n value = value.float()\n if self.meta.on_step:\n self._forward_cache = self.meta.sync(value.clone()) # `clone` because `sync` is in-place\n\n # performance: no need to accumulate on values only logged on_step\n if not self.meta.on_epoch:\n self.value = self._forward_cache\n return\n\n # perform accumulation with reduction\n if self.meta.is_mean_reduction:\n self.value += value.mean() * batch_size\n self.cumulated_batch_size += batch_size\n elif self.meta.is_max_reduction or self.meta.is_min_reduction:\n self.value = self.meta.reduce_fx(self.value, value.mean())\n elif self.meta.is_sum_reduction:\n self.value += value.mean()\n else:\n self.value = value\n self._forward_cache = value._forward_cache\n\n def compute(self) -> torch.Tensor:\n if self.is_tensor:\n value = self.meta.sync(self.value)\n if self.meta.is_mean_reduction:\n cumulated_batch_size = self.meta.sync(self.cumulated_batch_size)\n return value / cumulated_batch_size\n return value\n return self.value.compute()\n\n def reset(self) -> None:\n if self.is_tensor:\n super().reset()\n else:\n self.value.reset()\n self.has_reset = True\n\n def forward(self, value: _IN_METRIC, batch_size: torch.Tensor) -> None:\n if self.meta.enable_graph:\n with torch.no_grad():\n self.update(value, batch_size)\n else:\n # performance: skip the `torch.no_grad` context manager by calling `update` directly\n self.update(value, batch_size)\n\n def _wrap_compute(self, compute: Any) -> Any:\n # Override to avoid syncing - we handle it ourselves.\n @wraps(compute)\n def wrapped_func(*args: Any, **kwargs: Any) -> Optional[Any]:\n if not self._update_called:\n rank_zero_warn(\n f\"The ``compute`` method of metric {self.__class__.__name__}\"\n \" was called before the ``update`` method which may lead to errors,\"\n \" as metric states have not yet been updated.\",\n UserWarning,\n )\n\n # return cached value\n if self._computed is not None: # type: ignore\n return self._computed # type: ignore\n self._computed = compute(*args, **kwargs)\n return self._computed\n\n return wrapped_func\n\n def __setattr__(self, key: str, value: Any) -> None:\n # performance: skip the `torch.nn.Module.__setattr__` checks\n object.__setattr__(self, key, value)\n\n def __repr__(self) -> str:\n state = f\"{repr(self.meta.name)}, value={self.value}\"\n if self.is_tensor and self.meta.is_mean_reduction:\n state += f\", cumulated_batch_size={self.cumulated_batch_size}\"\n return f\"{self.__class__.__name__}({state})\"\n\n def __getstate__(self, drop_value: bool = False) -> dict:\n skip = [\"update\", \"compute\", \"_update_signature\", \"_cache\"]\n if not self.is_tensor and drop_value:\n # Avoid serializing ResultMetrics which are passed Metrics\n skip.append(\"value\")\n d = {k: v for k, v in self.__dict__.items() if k not in skip}\n d[\"meta\"] = d[\"meta\"].__getstate__()\n d[\"_class\"] = self.__class__.__name__\n d[\"_is_synced\"] = False # don't consider the state as synced on reload\n return d\n\n def __setstate__(self, state: dict, sync_fn: Optional[Callable] = None) -> None:\n d = {**state, \"meta\": _Metadata._reconstruct(state[\"meta\"], sync_fn=sync_fn)}\n super().__setstate__(d)\n\n @classmethod\n def _reconstruct(cls, state: dict, sync_fn: Optional[Callable] = None) -> \"ResultMetric\":\n # need to reconstruct twice because `meta` is used in `__init__`\n meta = _Metadata._reconstruct(state[\"meta\"])\n result_metric = cls(meta, state[\"is_tensor\"])\n result_metric.__setstate__(state, sync_fn=sync_fn)\n return result_metric\n\n def to(self, *args: Any, **kwargs: Any) -> \"ResultMetric\":\n self.__dict__.update(\n apply_to_collection(self.__dict__, (torch.Tensor, Metric), move_data_to_device, *args, **kwargs)\n )\n return self\n\n\nclass ResultMetricCollection(dict):\n \"\"\"Dict wrapper for easy access to metadata.\n\n All of the leaf items should be instances of\n :class:`~pytorch_lightning.trainer.connectors.logger_connector.result.ResultMetric`\n with the same metadata.\n \"\"\"\n\n def __init__(self, *args: Any) -> None:\n super().__init__(*args)\n\n @property\n def meta(self) -> _Metadata:\n return list(self.values())[0].meta\n\n def __getstate__(self, drop_value: bool = False) -> dict:\n def getstate(item: ResultMetric) -> dict:\n return item.__getstate__(drop_value=drop_value)\n\n items = apply_to_collection(dict(self), ResultMetric, getstate)\n return {\"items\": items, \"meta\": self.meta.__getstate__(), \"_class\": self.__class__.__name__}\n\n def __setstate__(self, state: dict, sync_fn: Optional[Callable] = None) -> None:\n # can't use `apply_to_collection` as it does not recurse items of the same type\n items = {k: ResultMetric._reconstruct(v, sync_fn=sync_fn) for k, v in state[\"items\"].items()}\n self.update(items)\n\n @classmethod\n def _reconstruct(cls, state: dict, sync_fn: Optional[Callable] = None) -> \"ResultMetricCollection\":\n rmc = cls()\n rmc.__setstate__(state, sync_fn=sync_fn)\n return rmc\n\n\n_METRIC_COLLECTION = Union[_IN_METRIC, ResultMetricCollection]\n\n\nclass ResultCollection(dict):\n \"\"\"\n Collection (dictionary) of :class:`~pytorch_lightning.trainer.connectors.logger_connector.result.ResultMetric` or\n :class:`~pytorch_lightning.trainer.connectors.logger_connector.result.ResultMetricCollection`\n\n Example:\n\n # `device` needs to be provided before logging\n result = ResultCollection(training=True, torch.device(\"cpu\"))\n\n # you can log to a specific collection.\n # arguments: fx, key, value, metadata\n result.log('training_step', 'acc', torch.tensor(...), on_step=True, on_epoch=True)\n result.log('validation_step', 'recall', torch.tensor(...), on_step=True, on_epoch=True)\n \"\"\"\n\n DATALOADER_SUFFIX = \"/dataloader_idx_{}\"\n\n def __init__(self, training: bool, device: Optional[Union[str, torch.device]] = None) -> None:\n super().__init__()\n self.training = training\n self._batch_size = torch.tensor(1, device=device)\n self.device: Optional[Union[str, torch.device]] = device\n\n @property\n def result_metrics(self) -> List[ResultMetric]:\n o = []\n\n def append_fn(v: ResultMetric) -> None:\n nonlocal o\n o.append(v)\n\n apply_to_collection(list(self.values()), ResultMetric, append_fn)\n return o\n\n @property\n def batch_size(self) -> torch.Tensor:\n # performance: cache the `batch_size` tensor instead of re-creating it\n return self._batch_size\n\n @batch_size.setter\n def batch_size(self, value: int) -> None:\n self._batch_size = torch.tensor(value, device=self.device)\n\n def log(\n self,\n fx: str,\n name: str,\n value: _METRIC_COLLECTION,\n prog_bar: bool = False,\n logger: bool = True,\n on_step: bool = False,\n on_epoch: bool = True,\n reduce_fx: Callable = torch.mean,\n enable_graph: bool = False,\n sync_dist: bool = False,\n sync_dist_fn: Callable = _Sync.no_op,\n sync_dist_group: Optional[Any] = None,\n dataloader_idx: Optional[int] = None,\n batch_size: Optional[int] = None,\n metric_attribute: Optional[str] = None,\n rank_zero_only: bool = False,\n ) -> None:\n \"\"\"See :meth:`~pytorch_lightning.core.lightning.LightningModule.log`\"\"\"\n # no metrics should be logged with graphs\n if not enable_graph:\n value = recursive_detach(value)\n\n # move metrics to cpu on TPU.\n if isinstance(value, torch.Tensor) and value.device.type == \"xla\":\n value = value.cpu()\n\n # storage key\n key = f\"{fx}.{name}\"\n # add dataloader_suffix to both key and fx\n if dataloader_idx is not None:\n key += f\".{dataloader_idx}\"\n fx += f\".{dataloader_idx}\"\n\n meta = _Metadata(\n fx=fx,\n name=name,\n prog_bar=prog_bar,\n logger=logger,\n on_step=on_step,\n on_epoch=on_epoch,\n reduce_fx=reduce_fx,\n enable_graph=enable_graph,\n dataloader_idx=dataloader_idx,\n metric_attribute=metric_attribute,\n )\n meta.sync = _Sync(_should=sync_dist, fn=sync_dist_fn, group=sync_dist_group, rank_zero_only=rank_zero_only)\n\n # register logged value if it doesn't exist\n if key not in self:\n self.register_key(key, meta, value)\n\n # check the stored metadata and the current one match\n elif meta != self[key].meta:\n raise MisconfigurationException(\n f\"You called `self.log({name}, ...)` twice in `{fx}` with different arguments. This is not allowed\"\n )\n\n if batch_size is not None:\n self.batch_size = batch_size\n\n self.update_metrics(key, value)\n\n def register_key(self, key: str, meta: _Metadata, value: _METRIC_COLLECTION) -> None:\n \"\"\"Create one ResultMetric object per value.\n\n Value can be provided as a nested collection\n \"\"\"\n\n def fn(v: _IN_METRIC) -> ResultMetric:\n metric = ResultMetric(meta, isinstance(v, torch.Tensor))\n return metric.to(self.device)\n\n value = apply_to_collection(value, (torch.Tensor, Metric), fn)\n if isinstance(value, dict):\n value = ResultMetricCollection(value)\n self[key] = value\n\n def update_metrics(self, key: str, value: _METRIC_COLLECTION) -> None:\n def fn(result_metric: ResultMetric, v: ResultMetric) -> None:\n # performance: avoid calling `__call__` to avoid the checks in `torch.nn.Module._call_impl`\n result_metric.forward(v.to(self.device), self.batch_size)\n result_metric.has_reset = False\n\n apply_to_collections(self[key], value, ResultMetric, fn)\n\n @staticmethod\n def _get_cache(result_metric: ResultMetric, on_step: bool) -> Optional[torch.Tensor]:\n cache = None\n if on_step and result_metric.meta.on_step:\n cache = result_metric._forward_cache\n elif not on_step and result_metric.meta.on_epoch:\n if result_metric._computed is None:\n # always reduce on epoch end\n should = result_metric.meta.sync.should\n result_metric.meta.sync.should = True\n result_metric.compute()\n result_metric.meta.sync.should = should\n cache = result_metric._computed\n if cache is not None and not result_metric.meta.enable_graph:\n return cache.detach()\n return cache\n\n def valid_items(self) -> Generator:\n \"\"\"This function is used to iterate over current valid metrics.\"\"\"\n return ((k, v) for k, v in self.items() if not (isinstance(v, ResultMetric) and v.has_reset))\n\n def _forked_name(self, result_metric: ResultMetric, on_step: bool) -> Tuple[str, str]:\n name = result_metric.meta.name\n forked_name = result_metric.meta.forked_name(on_step)\n dl_idx = result_metric.meta.dataloader_idx\n if dl_idx is not None:\n dataloader_suffix = self.DATALOADER_SUFFIX.format(dl_idx)\n name += dataloader_suffix\n forked_name += dataloader_suffix\n return name, forked_name\n\n def metrics(self, on_step: bool) -> _METRICS:\n metrics = _METRICS(callback={}, log={}, pbar={})\n\n for _, result_metric in self.valid_items():\n\n # extract forward_cache or computed from the ResultMetric. ignore when the output is None\n value = apply_to_collection(result_metric, ResultMetric, self._get_cache, on_step, include_none=False)\n\n # convert metric collection to dict container.\n if isinstance(value, ResultMetricCollection):\n value = dict(value.items())\n\n # check if the collection is empty\n has_tensor = False\n\n def any_tensor(_: Any) -> None:\n nonlocal has_tensor\n has_tensor = True\n\n apply_to_collection(value, torch.Tensor, any_tensor)\n if not has_tensor:\n continue\n\n name, forked_name = self._forked_name(result_metric, on_step)\n\n # populate logging metrics\n if result_metric.meta.logger:\n metrics[\"log\"][forked_name] = value\n\n # populate callback metrics. callback metrics don't take `_step` forked metrics\n if self.training or result_metric.meta.on_epoch and not on_step:\n metrics[\"callback\"][name] = value\n metrics[\"callback\"][forked_name] = value\n\n # populate progress_bar metrics. convert tensors to numbers\n if result_metric.meta.prog_bar:\n metrics[\"pbar\"][forked_name] = metrics_to_scalars(value)\n\n return metrics\n\n def reset(self, metrics: Optional[bool] = None, fx: Optional[str] = None) -> None:\n \"\"\"Reset the result collection.\n\n Args:\n metrics: If True, only ``torchmetrics.Metric`` results are reset,\n if False, only ``torch.Tensors`` are reset,\n if ``None``, both are.\n fx: Function to reset\n \"\"\"\n\n def fn(item: ResultMetric) -> None:\n requested_type = metrics is None or metrics ^ item.is_tensor\n same_fx = fx is None or fx == item.meta.fx\n if requested_type and same_fx:\n item.reset()\n\n apply_to_collection(self, ResultMetric, fn)\n\n def extract_batch_size(self, batch: Any) -> int:\n try:\n batch_size = extract_batch_size(batch)\n except RecursionError:\n batch_size = 1\n self.batch_size = batch_size # the setter converts it to `Tensor`\n return batch_size\n\n def to(self, *args: Any, **kwargs: Any) -> \"ResultCollection\":\n \"\"\"Move all data to the given device.\"\"\"\n self.update(apply_to_collection(dict(self), (torch.Tensor, Metric), move_data_to_device, *args, **kwargs))\n\n self._batch_size = self._batch_size.to(*args, **kwargs)\n if \"device\" in kwargs:\n self.device = kwargs[\"device\"]\n return self\n\n def cpu(self) -> \"ResultCollection\":\n \"\"\"Move all data to CPU.\"\"\"\n return self.to(device=\"cpu\")\n\n def sync(self) -> None:\n for result_metric in self.result_metrics:\n if result_metric.is_tensor:\n result_metric.sync()\n\n def unsync(self) -> None:\n for result_metric in self.result_metrics:\n if result_metric.is_tensor and result_metric._is_synced:\n result_metric.unsync()\n\n def __str__(self) -> str:\n # remove empty values\n self_str = str({k: v for k, v in self.items() if v})\n return f\"{self.__class__.__name__}({self_str})\"\n\n def __repr__(self) -> str:\n return f\"{{{self.training}, {repr(self.device)}, {super().__repr__()}}}\"\n\n def __getstate__(self, drop_value: bool = True) -> dict:\n d = self.__dict__.copy()\n # all the items should be either `ResultMetric`s or `ResultMetricCollection`s\n items = {k: v.__getstate__(drop_value=drop_value) for k, v in self.items()}\n return {**d, \"items\": items}\n\n def __setstate__(\n self, state: dict, map_location: Optional[Union[str, torch.device]] = None, sync_fn: Optional[Callable] = None\n ) -> None:\n self.__dict__.update({k: v for k, v in state.items() if k != \"items\"})\n\n def setstate(k: str, item: dict) -> Union[ResultMetric, ResultMetricCollection]:\n if not isinstance(item, dict):\n raise ValueError(f\"Unexpected value: {item}\")\n cls = item[\"_class\"]\n if cls == ResultMetric.__name__:\n cls = ResultMetric\n elif cls == ResultMetricCollection.__name__:\n cls = ResultMetricCollection\n else:\n raise ValueError(f\"Unexpected class name: {cls}\")\n _sync_fn = sync_fn or (self[k].meta.sync.fn if k in self else None)\n return cls._reconstruct(item, sync_fn=_sync_fn)\n\n items = {k: setstate(k, v) for k, v in state[\"items\"].items()}\n self.update(items)\n\n device = map_location or self.device\n self.to(device)\n\n def state_dict(self, drop_value: bool = True) -> dict:\n return self.__getstate__(drop_value)\n\n def load_state_dict(\n self,\n state_dict: dict,\n map_location: Optional[Union[str, torch.device]] = None,\n sync_fn: Optional[Callable] = None,\n metrics: Optional[Dict[str, Metric]] = None,\n ) -> None:\n self.__setstate__(state_dict, map_location=map_location, sync_fn=sync_fn)\n\n if not metrics:\n return\n\n # iterate through result metrics and re-attached Metric references on reload.\n result_metrics = self.result_metrics\n for metric_attribute, metric in metrics.items():\n for result_metric in result_metrics:\n if result_metric.meta.metric_attribute == metric_attribute:\n result_metric.value = metric\n", "# Copyright The PyTorch Lightning team.\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\"\"\"\nNeptune Logger\n--------------\n\"\"\"\n__all__ = [\n \"NeptuneLogger\",\n]\n\nimport logging\nimport os\nimport warnings\nfrom argparse import Namespace\nfrom functools import reduce\nfrom typing import Any, Dict, Generator, Optional, Set, Union\nfrom weakref import ReferenceType\n\nimport torch\n\nfrom pytorch_lightning import __version__\nfrom pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint\nfrom pytorch_lightning.loggers.base import LightningLoggerBase, rank_zero_experiment\nfrom pytorch_lightning.utilities import rank_zero_only\nfrom pytorch_lightning.utilities.imports import _NEPTUNE_AVAILABLE, _NEPTUNE_GREATER_EQUAL_0_9\nfrom pytorch_lightning.utilities.model_summary import ModelSummary\n\nif _NEPTUNE_AVAILABLE and _NEPTUNE_GREATER_EQUAL_0_9:\n try:\n from neptune import new as neptune\n from neptune.new.exceptions import NeptuneLegacyProjectException, NeptuneOfflineModeFetchException\n from neptune.new.run import Run\n from neptune.new.types import File as NeptuneFile\n except ModuleNotFoundError:\n import neptune\n from neptune.exceptions import NeptuneLegacyProjectException\n from neptune.run import Run\n from neptune.types import File as NeptuneFile\nelse:\n # needed for test mocks, and function signatures\n neptune, Run, NeptuneFile = None, None, None\n\nlog = logging.getLogger(__name__)\n\n_INTEGRATION_VERSION_KEY = \"source_code/integrations/pytorch-lightning\"\n\n# kwargs used in previous NeptuneLogger version, now deprecated\n_LEGACY_NEPTUNE_INIT_KWARGS = [\n \"project_name\",\n \"offline_mode\",\n \"experiment_name\",\n \"experiment_id\",\n \"params\",\n \"properties\",\n \"upload_source_files\",\n \"abort_callback\",\n \"logger\",\n \"upload_stdout\",\n \"upload_stderr\",\n \"send_hardware_metrics\",\n \"run_monitoring_thread\",\n \"handle_uncaught_exceptions\",\n \"git_info\",\n \"hostname\",\n \"notebook_id\",\n \"notebook_path\",\n]\n\n# kwargs used in legacy NeptuneLogger from neptune-pytorch-lightning package\n_LEGACY_NEPTUNE_LOGGER_KWARGS = [\n \"base_namespace\",\n \"close_after_fit\",\n]\n\n\nclass NeptuneLogger(LightningLoggerBase):\n r\"\"\"\n Log using `Neptune <https://neptune.ai>`_.\n\n Install it with pip:\n\n .. code-block:: bash\n\n pip install neptune-client\n\n or conda:\n\n .. code-block:: bash\n\n conda install -c conda-forge neptune-client\n\n **Quickstart**\n\n Pass NeptuneLogger instance to the Trainer to log metadata with Neptune:\n\n .. code-block:: python\n\n\n from pytorch_lightning import Trainer\n from pytorch_lightning.loggers import NeptuneLogger\n\n neptune_logger = NeptuneLogger(\n api_key=\"ANONYMOUS\", # replace with your own\n project=\"common/pytorch-lightning-integration\", # format \"<WORKSPACE/PROJECT>\"\n tags=[\"training\", \"resnet\"], # optional\n )\n trainer = Trainer(max_epochs=10, logger=neptune_logger)\n\n **How to use NeptuneLogger?**\n\n Use the logger anywhere in your :class:`~pytorch_lightning.core.lightning.LightningModule` as follows:\n\n .. code-block:: python\n\n from neptune.new.types import File\n from pytorch_lightning import LightningModule\n\n\n class LitModel(LightningModule):\n def training_step(self, batch, batch_idx):\n # log metrics\n acc = ...\n self.log(\"train/loss\", loss)\n\n def any_lightning_module_function_or_hook(self):\n # log images\n img = ...\n self.logger.experiment[\"train/misclassified_images\"].log(File.as_image(img))\n\n # generic recipe\n metadata = ...\n self.logger.experiment[\"your/metadata/structure\"].log(metadata)\n\n Note that syntax: ``self.logger.experiment[\"your/metadata/structure\"].log(metadata)`` is specific to Neptune\n and it extends logger capabilities. Specifically, it allows you to log various types of metadata\n like scores, files, images, interactive visuals, CSVs, etc.\n Refer to the `Neptune docs <https://docs.neptune.ai/you-should-know/logging-metadata#essential-logging-methods>`_\n for more detailed explanations.\n You can also use regular logger methods ``log_metrics()``, and ``log_hyperparams()`` with NeptuneLogger\n as these are also supported.\n\n **Log after fitting or testing is finished**\n\n You can log objects after the fitting or testing methods are finished:\n\n .. code-block:: python\n\n neptune_logger = NeptuneLogger(project=\"common/pytorch-lightning-integration\")\n\n trainer = pl.Trainer(logger=neptune_logger)\n model = ...\n datamodule = ...\n trainer.fit(model, datamodule=datamodule)\n trainer.test(model, datamodule=datamodule)\n\n # Log objects after `fit` or `test` methods\n # model summary\n neptune_logger.log_model_summary(model=model, max_depth=-1)\n\n # generic recipe\n metadata = ...\n neptune_logger.experiment[\"your/metadata/structure\"].log(metadata)\n\n **Log model checkpoints**\n\n If you have :class:`~pytorch_lightning.callbacks.ModelCheckpoint` configured,\n Neptune logger automatically logs model checkpoints.\n Model weights will be uploaded to the: \"model/checkpoints\" namespace in the Neptune Run.\n You can disable this option:\n\n .. code-block:: python\n\n neptune_logger = NeptuneLogger(project=\"common/pytorch-lightning-integration\", log_model_checkpoints=False)\n\n **Pass additional parameters to the Neptune run**\n\n You can also pass ``neptune_run_kwargs`` to specify the run in the greater detail, like ``tags`` or ``description``:\n\n .. testcode::\n\n from pytorch_lightning import Trainer\n from pytorch_lightning.loggers import NeptuneLogger\n\n neptune_logger = NeptuneLogger(\n project=\"common/pytorch-lightning-integration\",\n name=\"lightning-run\",\n description=\"mlp quick run with pytorch-lightning\",\n tags=[\"mlp\", \"quick-run\"],\n )\n trainer = Trainer(max_epochs=3, logger=neptune_logger)\n\n Check `run documentation <https://docs.neptune.ai/essentials/api-reference/run>`_\n for more info about additional run parameters.\n\n **Details about Neptune run structure**\n\n Runs can be viewed as nested dictionary-like structures that you can define in your code.\n Thanks to this you can easily organize your metadata in a way that is most convenient for you.\n\n The hierarchical structure that you apply to your metadata will be reflected later in the UI.\n\n You can organize this way any type of metadata - images, parameters, metrics, model checkpoint, CSV files, etc.\n\n See Also:\n - Read about\n `what object you can log to Neptune <https://docs.neptune.ai/you-should-know/what-can-you-log-and-display>`_.\n - Check `example run <https://app.neptune.ai/o/common/org/pytorch-lightning-integration/e/PTL-1/all>`_\n with multiple types of metadata logged.\n - For more detailed info check\n `user guide <https://docs.neptune.ai/integrations-and-supported-tools/model-training/pytorch-lightning>`_.\n\n Args:\n api_key: Optional.\n Neptune API token, found on https://neptune.ai upon registration.\n Read: `how to find and set Neptune API token <https://docs.neptune.ai/administration/security-and-privacy/\n how-to-find-and-set-neptune-api-token>`_.\n It is recommended to keep it in the `NEPTUNE_API_TOKEN`\n environment variable and then you can drop ``api_key=None``.\n project: Optional.\n Name of a project in a form of \"my_workspace/my_project\" for example \"tom/mask-rcnn\".\n If ``None``, the value of `NEPTUNE_PROJECT` environment variable will be taken.\n You need to create the project in https://neptune.ai first.\n name: Optional. Editable name of the run.\n Run name appears in the \"all metadata/sys\" section in Neptune UI.\n run: Optional. Default is ``None``. The Neptune ``Run`` object.\n If specified, this `Run`` will be used for logging, instead of a new Run.\n When run object is passed you can't specify other neptune properties.\n log_model_checkpoints: Optional. Default is ``True``. Log model checkpoint to Neptune.\n Works only if ``ModelCheckpoint`` is passed to the ``Trainer``.\n prefix: Optional. Default is ``\"training\"``. Root namespace for all metadata logging.\n \\**neptune_run_kwargs: Additional arguments like ``tags``, ``description``, ``capture_stdout``, etc.\n used when run is created.\n\n Raises:\n ModuleNotFoundError:\n If required Neptune package in version >=0.9 is not installed on the device.\n TypeError:\n If configured project has not been migrated to new structure yet.\n ValueError:\n If argument passed to the logger's constructor is incorrect.\n \"\"\"\n\n LOGGER_JOIN_CHAR = \"/\"\n PARAMETERS_KEY = \"hyperparams\"\n ARTIFACTS_KEY = \"artifacts\"\n\n def __init__(\n self,\n *, # force users to call `NeptuneLogger` initializer with `kwargs`\n api_key: Optional[str] = None,\n project: Optional[str] = None,\n name: Optional[str] = None,\n run: Optional[\"Run\"] = None,\n log_model_checkpoints: Optional[bool] = True,\n prefix: str = \"training\",\n **neptune_run_kwargs,\n ):\n\n # verify if user passed proper init arguments\n self._verify_input_arguments(api_key, project, name, run, neptune_run_kwargs)\n\n super().__init__()\n self._log_model_checkpoints = log_model_checkpoints\n self._prefix = prefix\n\n self._run_instance = self._init_run_instance(api_key, project, name, run, neptune_run_kwargs)\n\n self._run_short_id = self.run._short_id # skipcq: PYL-W0212\n try:\n self.run.wait()\n self._run_name = self._run_instance[\"sys/name\"].fetch()\n except NeptuneOfflineModeFetchException:\n self._run_name = \"offline-name\"\n\n def _init_run_instance(self, api_key, project, name, run, neptune_run_kwargs) -> Run:\n if run is not None:\n run_instance = run\n else:\n try:\n run_instance = neptune.init(\n project=project,\n api_token=api_key,\n name=name,\n **neptune_run_kwargs,\n )\n except NeptuneLegacyProjectException as e:\n raise TypeError(\n f\"\"\"Project {project} has not been migrated to the new structure.\n You can still integrate it with the Neptune logger using legacy Python API\n available as part of neptune-contrib package:\n - https://docs-legacy.neptune.ai/integrations/pytorch_lightning.html\\n\n \"\"\"\n ) from e\n\n # make sure that we've log integration version for both newly created and outside `Run` instances\n run_instance[_INTEGRATION_VERSION_KEY] = __version__\n\n # keep api_key and project, they will be required when resuming Run for pickled logger\n self._api_key = api_key\n self._project_name = run_instance._project_name # skipcq: PYL-W0212\n\n return run_instance\n\n def _construct_path_with_prefix(self, *keys) -> str:\n \"\"\"Return sequence of keys joined by `LOGGER_JOIN_CHAR`, started with `_prefix` if defined.\"\"\"\n if self._prefix:\n return self.LOGGER_JOIN_CHAR.join([self._prefix, *keys])\n return self.LOGGER_JOIN_CHAR.join(keys)\n\n @staticmethod\n def _verify_input_arguments(\n api_key: Optional[str],\n project: Optional[str],\n name: Optional[str],\n run: Optional[\"Run\"],\n neptune_run_kwargs: dict,\n ):\n legacy_kwargs_msg = (\n \"Following kwargs are deprecated: {legacy_kwargs}.\\n\"\n \"If you are looking for the Neptune logger using legacy Python API,\"\n \" it's still available as part of neptune-contrib package:\\n\"\n \" - https://docs-legacy.neptune.ai/integrations/pytorch_lightning.html\\n\"\n \"The NeptuneLogger was re-written to use the neptune.new Python API\\n\"\n \" - https://neptune.ai/blog/neptune-new\\n\"\n \" - https://docs.neptune.ai/integrations-and-supported-tools/model-training/pytorch-lightning\\n\"\n \"You should use arguments accepted by either NeptuneLogger.init() or neptune.init()\"\n )\n\n # check if user used legacy kwargs expected in `NeptuneLegacyLogger`\n used_legacy_kwargs = [\n legacy_kwarg for legacy_kwarg in neptune_run_kwargs if legacy_kwarg in _LEGACY_NEPTUNE_INIT_KWARGS\n ]\n if used_legacy_kwargs:\n raise ValueError(legacy_kwargs_msg.format(legacy_kwargs=used_legacy_kwargs))\n\n # check if user used legacy kwargs expected in `NeptuneLogger` from neptune-pytorch-lightning package\n used_legacy_neptune_kwargs = [\n legacy_kwarg for legacy_kwarg in neptune_run_kwargs if legacy_kwarg in _LEGACY_NEPTUNE_LOGGER_KWARGS\n ]\n if used_legacy_neptune_kwargs:\n raise ValueError(legacy_kwargs_msg.format(legacy_kwargs=used_legacy_neptune_kwargs))\n\n # check if user passed new client `Run` object\n if run is not None and not isinstance(run, Run):\n raise ValueError(\n \"Run parameter expected to be of type `neptune.new.Run`.\\n\"\n \"If you are looking for the Neptune logger using legacy Python API,\"\n \" it's still available as part of neptune-contrib package:\\n\"\n \" - https://docs-legacy.neptune.ai/integrations/pytorch_lightning.html\\n\"\n \"The NeptuneLogger was re-written to use the neptune.new Python API\\n\"\n \" - https://neptune.ai/blog/neptune-new\\n\"\n \" - https://docs.neptune.ai/integrations-and-supported-tools/model-training/pytorch-lightning\\n\"\n )\n\n # check if user passed redundant neptune.init arguments when passed run\n any_neptune_init_arg_passed = any(arg is not None for arg in [api_key, project, name]) or neptune_run_kwargs\n if run is not None and any_neptune_init_arg_passed:\n raise ValueError(\n \"When an already initialized run object is provided\"\n \" you can't provide other neptune.init() parameters.\\n\"\n )\n\n def __getstate__(self):\n state = self.__dict__.copy()\n # Run instance can't be pickled\n state[\"_run_instance\"] = None\n return state\n\n def __setstate__(self, state):\n self.__dict__ = state\n self._run_instance = neptune.init(project=self._project_name, api_token=self._api_key, run=self._run_short_id)\n\n @property\n @rank_zero_experiment\n def experiment(self) -> Run:\n r\"\"\"\n Actual Neptune run object. Allows you to use neptune logging features in your\n :class:`~pytorch_lightning.core.lightning.LightningModule`.\n\n Example::\n\n class LitModel(LightningModule):\n def training_step(self, batch, batch_idx):\n # log metrics\n acc = ...\n self.logger.experiment[\"train/acc\"].log(acc)\n\n # log images\n img = ...\n self.logger.experiment[\"train/misclassified_images\"].log(File.as_image(img))\n\n Note that syntax: ``self.logger.experiment[\"your/metadata/structure\"].log(metadata)``\n is specific to Neptune and it extends logger capabilities.\n Specifically, it allows you to log various types of metadata like scores, files,\n images, interactive visuals, CSVs, etc. Refer to the\n `Neptune docs <https://docs.neptune.ai/you-should-know/logging-metadata#essential-logging-methods>`_\n for more detailed explanations.\n You can also use regular logger methods ``log_metrics()``, and ``log_hyperparams()``\n with NeptuneLogger as these are also supported.\n \"\"\"\n return self.run\n\n @property\n def run(self) -> Run:\n return self._run_instance\n\n @rank_zero_only\n def log_hyperparams(self, params: Union[Dict[str, Any], Namespace]) -> None: # skipcq: PYL-W0221\n r\"\"\"\n Log hyper-parameters to the run.\n\n Hyperparams will be logged under the \"<prefix>/hyperparams\" namespace.\n\n Note:\n\n You can also log parameters by directly using the logger instance:\n ``neptune_logger.experiment[\"model/hyper-parameters\"] = params_dict``.\n\n In this way you can keep hierarchical structure of the parameters.\n\n Args:\n params: `dict`.\n Python dictionary structure with parameters.\n\n Example::\n\n from pytorch_lightning.loggers import NeptuneLogger\n\n PARAMS = {\n \"batch_size\": 64,\n \"lr\": 0.07,\n \"decay_factor\": 0.97\n }\n\n neptune_logger = NeptuneLogger(\n api_key=\"ANONYMOUS\",\n project=\"common/pytorch-lightning-integration\"\n )\n\n neptune_logger.log_hyperparams(PARAMS)\n \"\"\"\n params = self._convert_params(params)\n params = self._sanitize_callable_params(params)\n\n parameters_key = self.PARAMETERS_KEY\n parameters_key = self._construct_path_with_prefix(parameters_key)\n\n self.run[parameters_key] = params\n\n @rank_zero_only\n def log_metrics(self, metrics: Dict[str, Union[torch.Tensor, float]], step: Optional[int] = None) -> None:\n \"\"\"Log metrics (numeric values) in Neptune runs.\n\n Args:\n metrics: Dictionary with metric names as keys and measured quantities as values.\n step: Step number at which the metrics should be recorded, currently ignored.\n \"\"\"\n if rank_zero_only.rank != 0:\n raise ValueError(\"run tried to log from global_rank != 0\")\n\n metrics = self._add_prefix(metrics)\n\n for key, val in metrics.items():\n # `step` is ignored because Neptune expects strictly increasing step values which\n # Lighting does not always guarantee.\n self.experiment[key].log(val)\n\n @rank_zero_only\n def finalize(self, status: str) -> None:\n if status:\n self.experiment[self._construct_path_with_prefix(\"status\")] = status\n\n super().finalize(status)\n\n @property\n def save_dir(self) -> Optional[str]:\n \"\"\"Gets the save directory of the experiment which in this case is ``None`` because Neptune does not save\n locally.\n\n Returns:\n the root directory where experiment logs get saved\n \"\"\"\n return os.path.join(os.getcwd(), \".neptune\")\n\n def log_model_summary(self, model, max_depth=-1):\n model_str = str(ModelSummary(model=model, max_depth=max_depth))\n self.experiment[self._construct_path_with_prefix(\"model/summary\")] = neptune.types.File.from_content(\n content=model_str, extension=\"txt\"\n )\n\n def after_save_checkpoint(self, checkpoint_callback: \"ReferenceType[ModelCheckpoint]\") -> None:\n \"\"\"Automatically log checkpointed model. Called after model checkpoint callback saves a new checkpoint.\n\n Args:\n checkpoint_callback: the model checkpoint callback instance\n \"\"\"\n if not self._log_model_checkpoints:\n return\n\n file_names = set()\n checkpoints_namespace = self._construct_path_with_prefix(\"model/checkpoints\")\n\n # save last model\n if checkpoint_callback.last_model_path:\n model_last_name = self._get_full_model_name(checkpoint_callback.last_model_path, checkpoint_callback)\n file_names.add(model_last_name)\n self.experiment[f\"{checkpoints_namespace}/{model_last_name}\"].upload(checkpoint_callback.last_model_path)\n\n # save best k models\n for key in checkpoint_callback.best_k_models.keys():\n model_name = self._get_full_model_name(key, checkpoint_callback)\n file_names.add(model_name)\n self.experiment[f\"{checkpoints_namespace}/{model_name}\"].upload(key)\n\n # remove old models logged to experiment if they are not part of best k models at this point\n if self.experiment.exists(checkpoints_namespace):\n exp_structure = self.experiment.get_structure()\n uploaded_model_names = self._get_full_model_names_from_exp_structure(exp_structure, checkpoints_namespace)\n\n for file_to_drop in list(uploaded_model_names - file_names):\n del self.experiment[f\"{checkpoints_namespace}/{file_to_drop}\"]\n\n # log best model path and best model score\n if checkpoint_callback.best_model_path:\n self.experiment[\n self._construct_path_with_prefix(\"model/best_model_path\")\n ] = checkpoint_callback.best_model_path\n if checkpoint_callback.best_model_score:\n self.experiment[self._construct_path_with_prefix(\"model/best_model_score\")] = (\n checkpoint_callback.best_model_score.cpu().detach().numpy()\n )\n\n @staticmethod\n def _get_full_model_name(model_path: str, checkpoint_callback: \"ReferenceType[ModelCheckpoint]\") -> str:\n \"\"\"Returns model name which is string `modle_path` appended to `checkpoint_callback.dirpath`.\"\"\"\n expected_model_path = f\"{checkpoint_callback.dirpath}/\"\n if not model_path.startswith(expected_model_path):\n raise ValueError(f\"{model_path} was expected to start with {expected_model_path}.\")\n return model_path[len(expected_model_path) :]\n\n @classmethod\n def _get_full_model_names_from_exp_structure(cls, exp_structure: dict, namespace: str) -> Set[str]:\n \"\"\"Returns all paths to properties which were already logged in `namespace`\"\"\"\n structure_keys = namespace.split(cls.LOGGER_JOIN_CHAR)\n uploaded_models_dict = reduce(lambda d, k: d[k], [exp_structure, *structure_keys])\n return set(cls._dict_paths(uploaded_models_dict))\n\n @classmethod\n def _dict_paths(cls, d: dict, path_in_build: str = None) -> Generator:\n for k, v in d.items():\n path = f\"{path_in_build}/{k}\" if path_in_build is not None else k\n if not isinstance(v, dict):\n yield path\n else:\n yield from cls._dict_paths(v, path)\n\n @property\n def name(self) -> str:\n \"\"\"Return the experiment name or 'offline-name' when exp is run in offline mode.\"\"\"\n return self._run_name\n\n @property\n def version(self) -> str:\n \"\"\"Return the experiment version.\n\n It's Neptune Run's short_id\n \"\"\"\n return self._run_short_id\n\n @staticmethod\n def _signal_deprecated_api_usage(f_name, sample_code, raise_exception=False):\n msg_suffix = (\n f\"If you are looking for the Neptune logger using legacy Python API,\"\n f\" it's still available as part of neptune-contrib package:\\n\"\n f\" - https://docs-legacy.neptune.ai/integrations/pytorch_lightning.html\\n\"\n f\"The NeptuneLogger was re-written to use the neptune.new Python API\\n\"\n f\" - https://neptune.ai/blog/neptune-new\\n\"\n f\" - https://docs.neptune.ai/integrations-and-supported-tools/model-training/pytorch-lightning\\n\"\n f\"Instead of `logger.{f_name}` you can use:\\n\"\n f\"\\t{sample_code}\"\n )\n\n if not raise_exception:\n warnings.warn(\n \"The function you've used is deprecated in v1.5.0 and will be removed in v1.7.0. \" + msg_suffix\n )\n else:\n raise ValueError(\"The function you've used is deprecated.\\n\" + msg_suffix)\n\n @rank_zero_only\n def log_metric(self, metric_name: str, metric_value: Union[torch.Tensor, float, str], step: Optional[int] = None):\n key = f\"{self._prefix}/{metric_name}\"\n self._signal_deprecated_api_usage(\"log_metric\", f\"logger.run['{key}'].log(42)\")\n if torch.is_tensor(metric_value):\n metric_value = metric_value.cpu().detach()\n\n self.run[key].log(metric_value, step=step)\n\n @rank_zero_only\n def log_text(self, log_name: str, text: str, step: Optional[int] = None) -> None:\n key = f\"{self._prefix}/{log_name}\"\n self._signal_deprecated_api_usage(\"log_text\", f\"logger.run['{key}].log('text')\")\n self.run[key].log(str(text), step=step)\n\n @rank_zero_only\n def log_image(self, log_name: str, image: Union[str, Any], step: Optional[int] = None) -> None:\n key = f\"{self._prefix}/{log_name}\"\n self._signal_deprecated_api_usage(\"log_image\", f\"logger.run['{key}'].log(File('path_to_image'))\")\n if isinstance(image, str):\n # if `img` is path to file, convert it to file object\n image = NeptuneFile(image)\n self.run[key].log(image, step=step)\n\n @rank_zero_only\n def log_artifact(self, artifact: str, destination: Optional[str] = None) -> None:\n key = f\"{self._prefix}/{self.ARTIFACTS_KEY}/{artifact}\"\n self._signal_deprecated_api_usage(\"log_artifact\", f\"logger.run['{key}].log('path_to_file')\")\n self.run[key].log(destination)\n\n @rank_zero_only\n def set_property(self, *args, **kwargs):\n self._signal_deprecated_api_usage(\n \"log_artifact\", f\"logger.run['{self._prefix}/{self.PARAMETERS_KEY}/key'].log(value)\", raise_exception=True\n )\n\n @rank_zero_only\n def append_tags(self, *args, **kwargs):\n self._signal_deprecated_api_usage(\n \"append_tags\", \"logger.run['sys/tags'].add(['foo', 'bar'])\", raise_exception=True\n )\n" ]
[ [ "torch.no_grad", "torch.tensor" ], [ "torch.is_tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jackraymond/dwave-hybrid
[ "b4ac8fe0620609437fb3844d090d67123461d238" ]
[ "examples/parallel-tempering-alt.py" ]
[ "#!/usr/bin/env python\n\n# Copyright 2019 D-Wave Systems Inc.\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 sys\nimport math\nimport random\n\nimport numpy as np\n\nimport neal\nimport dimod\nimport hybrid\n\nfrom hybrid.reference.pt import FixedTemperatureSampler\nfrom hybrid.reference.pt import SwapReplicaPairRandom\n\n\n# load a problem\nproblem = sys.argv[1]\nwith open(problem) as fp:\n bqm = dimod.BinaryQuadraticModel.from_coo(fp)\n\nprint(\"BQM: {} nodes, {} edges, {:.2f} density\".format(\n len(bqm), len(bqm.quadratic), hybrid.bqm_density(bqm)))\n\n\n# PT workflow: temperature/beta is a property of a branch\n\nn_sweeps = 10000\nn_replicas = 10\nn_random_swaps = n_replicas - 1\nn_iterations = 10\n\n# replicas are initialized with random samples\nstate = hybrid.State.from_problem(bqm)\nreplicas = hybrid.States(*[state.updated() for _ in range(n_replicas)])\n\n# get a reasonable beta range\nbeta_hot, beta_cold = neal.default_beta_range(bqm)\n\n# generate betas for all branches/replicas\nbetas = np.geomspace(beta_hot, beta_cold, n_replicas)\n\n# run replicas update/swap for n_iterations\n# (after each update/sampling step, do n_replicas-1 random adjacent pair swaps)\nupdate = hybrid.Branches(*[\n FixedTemperatureSampler(beta=beta, num_sweeps=n_sweeps) for beta in betas])\nswap = hybrid.Loop(SwapReplicaPairRandom(betas=betas), max_iter=n_random_swaps)\nworkflow = hybrid.Loop(update | swap, max_iter=n_iterations) \\\n | hybrid.MergeSamples(aggregate=True)\n\nsolution = workflow.run(replicas).result()\n\n# show execution profile\nhybrid.profiling.print_counters(workflow)\n\n# show results\nprint(\"Solution: sample={0.samples.first}, energy={0.samples.first.energy}\".format(solution))\n" ]
[ [ "numpy.geomspace" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ruggleslab/phosphodisco-1
[ "4663e2c97b96304483234a80bc9b35befbf92795" ]
[ "phosphodisco/nominate_regulators.py" ]
[ "import pandas as pd\nimport numpy as np\nfrom pandas import DataFrame\nfrom typing import Iterable, Optional\nfrom sklearn import linear_model, preprocessing\nfrom .utils import corr_na, zscore\n\n\ndef collapse_possible_regulators(\n reg_data: DataFrame,\n corr_threshold: float = 0.95\n) -> DataFrame:\n \"\"\"Uses mean to collapse rows of possible regulator data that are highly correlated. Slightly\n chaotic, since it just averages two at a time based on iterating through a dictionary. Use\n with caution.\n\n Args:\n reg_data: DataFrame with possible regulator features as rows, samples as columns.\n corr_threshold: Rows with pearson correlation higher than this value will be averaged\n iteratively until there are no more rows with more than this correlation.\n\n Returns: DataFrame with rows that do not have pairwise correlation above the corr_threshold.\n\n \"\"\"\n reg_data = zscore(reg_data)\n corr = reg_data.transpose().corr()\n \n high_corr_inds = corr.index[((corr > corr_threshold).sum(axis=1) > 1)]\n low_corr_inds = corr.index.difference(high_corr_inds)\n high_corr_data = reg_data.loc[high_corr_inds, :]\n low_corr_data = reg_data.loc[low_corr_inds, :]\n if len(high_corr_inds) == 0:\n return low_corr_data\n corr = corr.mask(\n np.tril(np.ones(corr.shape)).astype(np.bool)\n ).mask(~(corr > corr_threshold)).dropna(how='all').dropna(how='all', axis=1)\n corr = corr.stack(level=[0, 1])\n\n while corr.shape[0] > 0:\n for i in corr.index:\n a, b, c, d = i\n if (a, b) in high_corr_data.index and (c, d) in high_corr_data.index:\n inds_to_mean = [(a, b), (c, d)]\n \n others_ab = [\n (d, e, f, g) for d, e, f, g in corr.index \n if (d, e) is (a, b) or (f, g) is (a, b) \n ]\n others_ab = [(f, g) if (d, e) == (a, b) else (d, e) for d, e, f, g in others_ab]\n inds_to_mean.extend(\n [(e, f) for e, f in others_ab\n if ((e, f, c, d) in high_corr_data.index)\n or ((c, d, e, f) in high_corr_data.index)]\n )\n \n name = ('%s-%s' %(a, c), '%s-%s' % (b, d))\n high_corr_data = high_corr_data.append(\n pd.Series(high_corr_data.loc[inds_to_mean, :].mean(), name=name)\n )\n high_corr_data = high_corr_data.drop(inds_to_mean, axis=0)\n corr = high_corr_data.transpose().corr()\n high_corr_inds = corr.index[((corr > corr_threshold).sum(axis=1) > 1)]\n low_corr_inds = corr.index[((corr > corr_threshold).sum(axis=1) <= 1)]\n\n low_corr_data = low_corr_data.append(high_corr_data.loc[low_corr_inds, :])\n if len(high_corr_inds) == 0:\n return low_corr_data\n high_corr_data = high_corr_data.loc[high_corr_inds, :]\n corr = corr.mask(\n np.tril(np.ones(corr.shape)).astype(np.bool)\n ).mask(~(corr > corr_threshold)).dropna(how='all').dropna(how='all', axis=1)\n corr = corr.stack(level=[0, 1])\n\n return low_corr_data\n\n\ndef calculate_regulator_coefficients(\n reg_data: DataFrame,\n module_scores: DataFrame,\n scale_data: bool = True,\n model: str = 'linear',\n regularization_values: Optional[Iterable] = None,\n cv_fold: int = 5,\n **model_kwargs\n) -> DataFrame:\n \"\"\"Calculates linear model coefficients between regulator data and module scores.\n\n Args:\n reg_data: DataFrame with possible regulator features as rows, samples as columns.\n module_scores: DataFrame with module scores as rows, samples as columns.\n scale_data: Whether to scale the regulator data and module scores with\n sklearn.preprocess.scale before training the linear model.\n model: Whether the relationship between log2(regulator_data) and module scores should be\n modeled as linear or sigmoid.\n regularization_values: Which regularization values should be tried during CV to define\n the coefficients.\n cv_fold: The number of cross validation folds to try for calculating the regularization\n value.\n **model_kwargs: Additional keyword args for sklearn.linear_model.RidgeCV\n\n Returns: The first object is a DataFrame with module scores as rows and regulators as columns,\n and model coefficients as values. The second is a Series with module scores as rows and the\n over all model quality score as values.\n\n \"\"\"\n if regularization_values is None:\n regularization_values = [5 ** i for i in range(-5, 5)]\n\n if model not in ['linear', 'sigmoid']:\n raise ValueError(\n 'Model %s not in accepted models: %s' % (model, ','.join(['linear', 'sigmoid']))\n )\n\n features = reg_data.transpose().values\n targets = module_scores.transpose().values\n if model == 'sigmoid':\n targets = -np.log2(1+(2**-targets))\n if scale_data:\n features = preprocessing.scale(features, copy=True)\n targets = preprocessing.scale(targets, copy=True)\n \n model_kwargs.update({'cv': cv_fold, 'alphas':regularization_values})\n model = linear_model.RidgeCV(**model_kwargs)\n model.fit(features, targets)\n weights = pd.DataFrame(\n model.coef_,\n index=module_scores.index,\n columns=reg_data.index\n ).transpose()\n scores = pd.Series(\n model.score(features, targets),\n index=module_scores.index,\n )\n return weights, scores\n\n\ndef calculate_regulator_corr(\n reg_data: DataFrame,\n module_scores: DataFrame,\n **model_kwargs\n):\n \"\"\"Calculates the correlation between possible regulators and module scores.\n\n Args:\n reg_data: DataFrame with possible regulator features as rows, samples as columns.\n module_scores: DataFrame with module scores as rows, samples as columns.\n **model_kwargs: Additional keyword args for corr_na, including method which can take\n either pearsonr or spearmanr.\n\n Returns: Two DataFrames, both with module scores as rows and possible regulators as columns.\n The first one has correlation R values, the second has correlation p values.\n\n \"\"\"\n rs = pd.DataFrame(index=reg_data.index)\n ps = pd.DataFrame(index=reg_data.index)\n for i, row in module_scores.iterrows():\n res = reg_data.apply(lambda r: pd.Series(corr_na(row, r, **model_kwargs)), axis=1)\n rs[i] = res.iloc[:, 0]\n ps[i] = res.iloc[:, 1]\n return rs, ps\n" ]
[ [ "numpy.log2", "pandas.DataFrame", "numpy.ones", "sklearn.linear_model.RidgeCV", "sklearn.preprocessing.scale" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
flavio92ux/aceleracao-DataScience
[ "2b2e41ec6c9184e161bdc66af0063792f09ce88d" ]
[ "class-week-07/projeto padrao/src/metrics.py" ]
[ "import pandas as pd\r\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\r\n\r\n\r\nclass Metrics:\r\n def __init__(self):\r\n pass\r\n\r\n def calculate_regression(self, y_true, y_pred):\r\n '''\r\n Calculate the metrics from a regression problem\r\n :param y_true: Numpy.ndarray or Pandas.Series\r\n :param y_pred: Numpy.ndarray or Pandas.Series\r\n :return: Dict with metrics\r\n '''\r\n mean_abs_err = mean_absolute_error(y_true, y_pred)\r\n mean_sqr_err = mean_squared_error(y_true, y_pred)\r\n return {'mean_abs_err' : mean_abs_err, 'mean_sqr_err' : mean_sqr_err}\r\n " ]
[ [ "sklearn.metrics.mean_absolute_error", "sklearn.metrics.mean_squared_error" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ccivit/DeepMoji
[ "98f498956951bf2da8eeb098834a71b6729535cc" ]
[ "deepmoji/attlayer.py" ]
[ "# -*- coding: utf-8 -*-\n\n\nimport sys\nfrom os.path import dirname\nsys.path.append(dirname(dirname(__file__)))\nfrom tensorflow.keras import initializers\n# from tensorflow.keras.engine import InputSpec, Layer\nfrom tensorflow.keras.layers import Layer, InputSpec\nfrom tensorflow.keras import backend as K\n\n\nclass AttentionWeightedAverage(Layer):\n \"\"\"\n Computes a weighted average of the different channels across timesteps.\n Uses 1 parameter pr. channel to compute the attention value for a single timestep.\n \"\"\"\n\n def __init__(self, return_attention=False, **kwargs):\n self.init = initializers.get('uniform')\n self.supports_masking = True\n self.return_attention = return_attention\n super(AttentionWeightedAverage, self).__init__(** kwargs)\n\n def get_config(self):\n config = {\n 'return_attention': self.return_attention,\n }\n base_config = super(AttentionWeightedAverage, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n def build(self, input_shape):\n self.input_spec = [InputSpec(ndim=3)]\n assert len(input_shape) == 3\n\n self.W = self.add_weight(shape=(input_shape[2], 1),\n name='{}_W'.format(self.name),\n initializer=self.init)\n # self.trainable_weights = [self.W]\n self._trainable_weights = [self.W] # https://github.com/pierluigiferrari/ssd_keras/issues/322\n super(AttentionWeightedAverage, self).build(input_shape)\n\n def call(self, x, mask=None):\n # computes a probability distribution over the timesteps\n # uses 'max trick' for numerical stability\n # reshape is done to avoid issue with Tensorflow\n # and 1-dimensional weights\n logits = K.dot(x, self.W)\n x_shape = K.shape(x)\n logits = K.reshape(logits, (x_shape[0], x_shape[1]))\n ai = K.exp(logits - K.max(logits, axis=-1, keepdims=True))\n\n # masked timesteps have zero weight\n if mask is not None:\n mask = K.cast(mask, K.floatx())\n ai = ai * mask\n att_weights = ai / (K.sum(ai, axis=1, keepdims=True) + K.epsilon())\n weighted_input = x * K.expand_dims(att_weights)\n result = K.sum(weighted_input, axis=1)\n if self.return_attention:\n return [result, att_weights]\n return result\n\n def get_output_shape_for(self, input_shape):\n return self.compute_output_shape(input_shape)\n\n def compute_output_shape(self, input_shape):\n output_len = input_shape[2]\n if self.return_attention:\n return [(input_shape[0], output_len), (input_shape[0], input_shape[1])]\n return (input_shape[0], output_len)\n\n def compute_mask(self, input, input_mask=None):\n if isinstance(input_mask, list):\n return [None] * len(input_mask)\n else:\n return None\n" ]
[ [ "tensorflow.keras.backend.floatx", "tensorflow.keras.backend.dot", "tensorflow.keras.backend.sum", "tensorflow.keras.backend.max", "tensorflow.keras.backend.reshape", "tensorflow.keras.backend.shape", "tensorflow.keras.backend.expand_dims", "tensorflow.keras.backend.epsilon", "tensorflow.keras.layers.InputSpec", "tensorflow.keras.initializers.get" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] } ]
marcelned/dask
[ "4a5a54302a261876ba453c1ac8fc6f69006161f1" ]
[ "dask/base.py" ]
[ "import datetime\nimport inspect\nimport os\nimport pickle\nimport threading\nimport uuid\nfrom collections import OrderedDict\nfrom concurrent.futures import Executor\nfrom contextlib import contextmanager\nfrom dataclasses import fields, is_dataclass\nfrom functools import partial\nfrom hashlib import md5\nfrom numbers import Integral, Number\nfrom operator import getitem\nfrom typing import Iterator, Mapping, Set\n\nfrom packaging.version import parse as parse_version\nfrom tlz import curry, groupby, identity, merge\nfrom tlz.functoolz import Compose\n\nfrom . import config, local, threaded\nfrom .context import thread_state\nfrom .core import flatten\nfrom .core import get as simple_get\nfrom .core import literal, quote\nfrom .hashing import hash_buffer_hex\nfrom .system import CPU_COUNT\nfrom .utils import Dispatch, apply, ensure_dict, key_split\n\n__all__ = (\n \"DaskMethodsMixin\",\n \"annotate\",\n \"is_dask_collection\",\n \"compute\",\n \"persist\",\n \"optimize\",\n \"visualize\",\n \"tokenize\",\n \"normalize_token\",\n \"get_collection_names\",\n \"get_name_from_key\",\n \"replace_name_in_key\",\n \"clone_key\",\n)\n\n\n@contextmanager\ndef annotate(**annotations):\n \"\"\"Context Manager for setting HighLevelGraph Layer annotations.\n\n Annotations are metadata or soft constraints associated with\n tasks that dask schedulers may choose to respect: They signal intent\n without enforcing hard constraints. As such, they are\n primarily designed for use with the distributed scheduler.\n\n Almost any object can serve as an annotation, but small Python objects\n are preferred, while large objects such as NumPy arrays are discouraged.\n\n Callables supplied as an annotation should take a single *key* argument and\n produce the appropriate annotation. Individual task keys in the annotated collection\n are supplied to the callable.\n\n Parameters\n ----------\n **annotations : key-value pairs\n\n Examples\n --------\n\n All tasks within array A should have priority 100 and be retried 3 times\n on failure.\n\n >>> import dask\n >>> import dask.array as da\n >>> with dask.annotate(priority=100, retries=3):\n ... A = da.ones((10000, 10000))\n\n Prioritise tasks within Array A on flattened block ID.\n\n >>> nblocks = (10, 10)\n >>> with dask.annotate(priority=lambda k: k[1]*nblocks[1] + k[2]):\n ... A = da.ones((1000, 1000), chunks=(100, 100))\n\n Annotations may be nested.\n\n >>> with dask.annotate(priority=1):\n ... with dask.annotate(retries=3):\n ... A = da.ones((1000, 1000))\n ... B = A + 1\n \"\"\"\n\n # Sanity check annotations used in place of\n # legacy distributed Client.{submit, persist, compute} keywords\n if \"workers\" in annotations:\n if isinstance(annotations[\"workers\"], (list, set, tuple)):\n annotations[\"workers\"] = list(annotations[\"workers\"])\n elif isinstance(annotations[\"workers\"], str):\n annotations[\"workers\"] = [annotations[\"workers\"]]\n elif callable(annotations[\"workers\"]):\n pass\n else:\n raise TypeError(\n \"'workers' annotation must be a sequence of str, a str or a callable, but got %s.\"\n % annotations[\"workers\"]\n )\n\n if (\n \"priority\" in annotations\n and not isinstance(annotations[\"priority\"], Number)\n and not callable(annotations[\"priority\"])\n ):\n raise TypeError(\n \"'priority' annotation must be a Number or a callable, but got %s\"\n % annotations[\"priority\"]\n )\n\n if (\n \"retries\" in annotations\n and not isinstance(annotations[\"retries\"], Number)\n and not callable(annotations[\"retries\"])\n ):\n raise TypeError(\n \"'retries' annotation must be a Number or a callable, but got %s\"\n % annotations[\"retries\"]\n )\n\n if (\n \"resources\" in annotations\n and not isinstance(annotations[\"resources\"], dict)\n and not callable(annotations[\"resources\"])\n ):\n raise TypeError(\n \"'resources' annotation must be a dict, but got %s\"\n % annotations[\"resources\"]\n )\n\n if (\n \"allow_other_workers\" in annotations\n and not isinstance(annotations[\"allow_other_workers\"], bool)\n and not callable(annotations[\"allow_other_workers\"])\n ):\n raise TypeError(\n \"'allow_other_workers' annotations must be a bool or a callable, but got %s\"\n % annotations[\"allow_other_workers\"]\n )\n\n prev_annotations = config.get(\"annotations\", {})\n new_annotations = {\n **prev_annotations,\n **{f\"annotations.{k}\": v for k, v in annotations.items()},\n }\n\n with config.set(new_annotations):\n yield\n\n\ndef is_dask_collection(x):\n \"\"\"Returns ``True`` if ``x`` is a dask collection\"\"\"\n try:\n return x.__dask_graph__() is not None\n except (AttributeError, TypeError):\n return False\n\n\nclass DaskMethodsMixin:\n \"\"\"A mixin adding standard dask collection methods\"\"\"\n\n __slots__ = ()\n\n def visualize(self, filename=\"mydask\", format=None, optimize_graph=False, **kwargs):\n \"\"\"Render the computation of this object's task graph using graphviz.\n\n Requires ``graphviz`` to be installed.\n\n Parameters\n ----------\n filename : str or None, optional\n The name of the file to write to disk. If the provided `filename`\n doesn't include an extension, '.png' will be used by default.\n If `filename` is None, no file will be written, and we communicate\n with dot using only pipes.\n format : {'png', 'pdf', 'dot', 'svg', 'jpeg', 'jpg'}, optional\n Format in which to write output file. Default is 'png'.\n optimize_graph : bool, optional\n If True, the graph is optimized before rendering. Otherwise,\n the graph is displayed as is. Default is False.\n color: {None, 'order'}, optional\n Options to color nodes. Provide ``cmap=`` keyword for additional\n colormap\n **kwargs\n Additional keyword arguments to forward to ``to_graphviz``.\n\n Examples\n --------\n >>> x.visualize(filename='dask.pdf') # doctest: +SKIP\n >>> x.visualize(filename='dask.pdf', color='order') # doctest: +SKIP\n\n Returns\n -------\n result : IPython.diplay.Image, IPython.display.SVG, or None\n See dask.dot.dot_graph for more information.\n\n See Also\n --------\n dask.base.visualize\n dask.dot.dot_graph\n\n Notes\n -----\n For more information on optimization see here:\n\n https://docs.dask.org/en/latest/optimize.html\n \"\"\"\n return visualize(\n self,\n filename=filename,\n format=format,\n optimize_graph=optimize_graph,\n **kwargs,\n )\n\n def persist(self, **kwargs):\n \"\"\"Persist this dask collection into memory\n\n This turns a lazy Dask collection into a Dask collection with the same\n metadata, but now with the results fully computed or actively computing\n in the background.\n\n The action of function differs significantly depending on the active\n task scheduler. If the task scheduler supports asynchronous computing,\n such as is the case of the dask.distributed scheduler, then persist\n will return *immediately* and the return value's task graph will\n contain Dask Future objects. However if the task scheduler only\n supports blocking computation then the call to persist will *block*\n and the return value's task graph will contain concrete Python results.\n\n This function is particularly useful when using distributed systems,\n because the results will be kept in distributed memory, rather than\n returned to the local process as with compute.\n\n Parameters\n ----------\n scheduler : string, optional\n Which scheduler to use like \"threads\", \"synchronous\" or \"processes\".\n If not provided, the default is to check the global settings first,\n and then fall back to the collection defaults.\n optimize_graph : bool, optional\n If True [default], the graph is optimized before computation.\n Otherwise the graph is run as is. This can be useful for debugging.\n **kwargs\n Extra keywords to forward to the scheduler function.\n\n Returns\n -------\n New dask collections backed by in-memory data\n\n See Also\n --------\n dask.base.persist\n \"\"\"\n (result,) = persist(self, traverse=False, **kwargs)\n return result\n\n def compute(self, **kwargs):\n \"\"\"Compute this dask collection\n\n This turns a lazy Dask collection into its in-memory equivalent.\n For example a Dask array turns into a NumPy array and a Dask dataframe\n turns into a Pandas dataframe. The entire dataset must fit into memory\n before calling this operation.\n\n Parameters\n ----------\n scheduler : string, optional\n Which scheduler to use like \"threads\", \"synchronous\" or \"processes\".\n If not provided, the default is to check the global settings first,\n and then fall back to the collection defaults.\n optimize_graph : bool, optional\n If True [default], the graph is optimized before computation.\n Otherwise the graph is run as is. This can be useful for debugging.\n kwargs\n Extra keywords to forward to the scheduler function.\n\n See Also\n --------\n dask.base.compute\n \"\"\"\n (result,) = compute(self, traverse=False, **kwargs)\n return result\n\n def __await__(self):\n try:\n from distributed import futures_of, wait\n except ImportError as e:\n raise ImportError(\n \"Using async/await with dask requires the `distributed` package\"\n ) from e\n from tornado import gen\n\n @gen.coroutine\n def f():\n if futures_of(self):\n yield wait(self)\n raise gen.Return(self)\n\n return f().__await__()\n\n\ndef compute_as_if_collection(cls, dsk, keys, scheduler=None, get=None, **kwargs):\n \"\"\"Compute a graph as if it were of type cls.\n\n Allows for applying the same optimizations and default scheduler.\"\"\"\n schedule = get_scheduler(scheduler=scheduler, cls=cls, get=get)\n dsk2 = optimization_function(cls)(dsk, keys, **kwargs)\n return schedule(dsk2, keys, **kwargs)\n\n\ndef dont_optimize(dsk, keys, **kwargs):\n return dsk\n\n\ndef optimization_function(x):\n return getattr(x, \"__dask_optimize__\", dont_optimize)\n\n\ndef collections_to_dsk(collections, optimize_graph=True, optimizations=(), **kwargs):\n \"\"\"\n Convert many collections into a single dask graph, after optimization\n \"\"\"\n from .highlevelgraph import HighLevelGraph\n\n optimizations = tuple(optimizations) + tuple(config.get(\"optimizations\", ()))\n\n if optimize_graph:\n groups = groupby(optimization_function, collections)\n\n graphs = []\n for opt, val in groups.items():\n dsk, keys = _extract_graph_and_keys(val)\n dsk = opt(dsk, keys, **kwargs)\n\n for opt_inner in optimizations:\n dsk = opt_inner(dsk, keys, **kwargs)\n\n graphs.append(dsk)\n\n # Merge all graphs\n if any(isinstance(graph, HighLevelGraph) for graph in graphs):\n dsk = HighLevelGraph.merge(*graphs)\n else:\n dsk = merge(*map(ensure_dict, graphs))\n else:\n dsk, _ = _extract_graph_and_keys(collections)\n\n return dsk\n\n\ndef _extract_graph_and_keys(vals):\n \"\"\"Given a list of dask vals, return a single graph and a list of keys such\n that ``get(dsk, keys)`` is equivalent to ``[v.compute() for v in vals]``.\"\"\"\n from .highlevelgraph import HighLevelGraph\n\n graphs, keys = [], []\n for v in vals:\n graphs.append(v.__dask_graph__())\n keys.append(v.__dask_keys__())\n\n if any(isinstance(graph, HighLevelGraph) for graph in graphs):\n graph = HighLevelGraph.merge(*graphs)\n else:\n graph = merge(*map(ensure_dict, graphs))\n\n return graph, keys\n\n\ndef unpack_collections(*args, traverse=True):\n \"\"\"Extract collections in preparation for compute/persist/etc...\n\n Intended use is to find all collections in a set of (possibly nested)\n python objects, do something to them (compute, etc...), then repackage them\n in equivalent python objects.\n\n Parameters\n ----------\n *args\n Any number of objects. If it is a dask collection, it's extracted and\n added to the list of collections returned. By default, python builtin\n collections are also traversed to look for dask collections (for more\n information see the ``traverse`` keyword).\n traverse : bool, optional\n If True (default), builtin python collections are traversed looking for\n any dask collections they might contain.\n\n Returns\n -------\n collections : list\n A list of all dask collections contained in ``args``\n repack : callable\n A function to call on the transformed collections to repackage them as\n they were in the original ``args``.\n \"\"\"\n\n collections = []\n repack_dsk = {}\n\n collections_token = uuid.uuid4().hex\n\n def _unpack(expr):\n if is_dask_collection(expr):\n tok = tokenize(expr)\n if tok not in repack_dsk:\n repack_dsk[tok] = (getitem, collections_token, len(collections))\n collections.append(expr)\n return tok\n\n tok = uuid.uuid4().hex\n if not traverse:\n tsk = quote(expr)\n else:\n # Treat iterators like lists\n typ = list if isinstance(expr, Iterator) else type(expr)\n if typ in (list, tuple, set):\n tsk = (typ, [_unpack(i) for i in expr])\n elif typ in (dict, OrderedDict):\n tsk = (typ, [[_unpack(k), _unpack(v)] for k, v in expr.items()])\n elif is_dataclass(expr) and not isinstance(expr, type):\n tsk = (\n apply,\n typ,\n (),\n (\n dict,\n [\n [f.name, _unpack(getattr(expr, f.name))]\n for f in fields(expr)\n ],\n ),\n )\n else:\n return expr\n\n repack_dsk[tok] = tsk\n return tok\n\n out = uuid.uuid4().hex\n repack_dsk[out] = (tuple, [_unpack(i) for i in args])\n\n def repack(results):\n dsk = repack_dsk.copy()\n dsk[collections_token] = quote(results)\n return simple_get(dsk, out)\n\n return collections, repack\n\n\ndef optimize(*args, traverse=True, **kwargs):\n \"\"\"Optimize several dask collections at once.\n\n Returns equivalent dask collections that all share the same merged and\n optimized underlying graph. This can be useful if converting multiple\n collections to delayed objects, or to manually apply the optimizations at\n strategic points.\n\n Note that in most cases you shouldn't need to call this method directly.\n\n Parameters\n ----------\n *args : objects\n Any number of objects. If a dask object, its graph is optimized and\n merged with all those of all other dask objects before returning an\n equivalent dask collection. Non-dask arguments are passed through\n unchanged.\n traverse : bool, optional\n By default dask traverses builtin python collections looking for dask\n objects passed to ``optimize``. For large collections this can be\n expensive. If none of the arguments contain any dask objects, set\n ``traverse=False`` to avoid doing this traversal.\n optimizations : list of callables, optional\n Additional optimization passes to perform.\n **kwargs\n Extra keyword arguments to forward to the optimization passes.\n\n Examples\n --------\n >>> import dask as d\n >>> import dask.array as da\n >>> a = da.arange(10, chunks=2).sum()\n >>> b = da.arange(10, chunks=2).mean()\n >>> a2, b2 = d.optimize(a, b)\n\n >>> a2.compute() == a.compute()\n True\n >>> b2.compute() == b.compute()\n True\n \"\"\"\n collections, repack = unpack_collections(*args, traverse=traverse)\n if not collections:\n return args\n\n dsk = collections_to_dsk(collections, **kwargs)\n\n postpersists = []\n for a in collections:\n r, s = a.__dask_postpersist__()\n postpersists.append(r(dsk, *s))\n\n return repack(postpersists)\n\n\ndef compute(\n *args, traverse=True, optimize_graph=True, scheduler=None, get=None, **kwargs\n):\n \"\"\"Compute several dask collections at once.\n\n Parameters\n ----------\n args : object\n Any number of objects. If it is a dask object, it's computed and the\n result is returned. By default, python builtin collections are also\n traversed to look for dask objects (for more information see the\n ``traverse`` keyword). Non-dask arguments are passed through unchanged.\n traverse : bool, optional\n By default dask traverses builtin python collections looking for dask\n objects passed to ``compute``. For large collections this can be\n expensive. If none of the arguments contain any dask objects, set\n ``traverse=False`` to avoid doing this traversal.\n scheduler : string, optional\n Which scheduler to use like \"threads\", \"synchronous\" or \"processes\".\n If not provided, the default is to check the global settings first,\n and then fall back to the collection defaults.\n optimize_graph : bool, optional\n If True [default], the optimizations for each collection are applied\n before computation. Otherwise the graph is run as is. This can be\n useful for debugging.\n get : ``None``\n Should be left to ``None`` The get= keyword has been removed.\n kwargs\n Extra keywords to forward to the scheduler function.\n\n Examples\n --------\n >>> import dask as d\n >>> import dask.array as da\n >>> a = da.arange(10, chunks=2).sum()\n >>> b = da.arange(10, chunks=2).mean()\n >>> d.compute(a, b)\n (45, 4.5)\n\n By default, dask objects inside python collections will also be computed:\n\n >>> d.compute({'a': a, 'b': b, 'c': 1})\n ({'a': 45, 'b': 4.5, 'c': 1},)\n \"\"\"\n\n collections, repack = unpack_collections(*args, traverse=traverse)\n if not collections:\n return args\n\n schedule = get_scheduler(\n scheduler=scheduler,\n collections=collections,\n get=get,\n )\n\n dsk = collections_to_dsk(collections, optimize_graph, **kwargs)\n keys, postcomputes = [], []\n for x in collections:\n keys.append(x.__dask_keys__())\n postcomputes.append(x.__dask_postcompute__())\n\n results = schedule(dsk, keys, **kwargs)\n return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)])\n\n\ndef visualize(*args, filename=\"mydask\", optimize_graph=False, maxval=None, **kwargs):\n \"\"\"\n Visualize several low level dask graphs at once.\n\n Requires ``graphviz`` to be installed. All options that are not the dask\n graph(s) should be passed as keyword arguments.\n\n Parameters\n ----------\n args : dict(s) or collection(s)\n The low level dask graph(s) to visualize.\n filename : str or None, optional\n The name of the file to write to disk. If the provided `filename`\n doesn't include an extension, '.png' will be used by default.\n If `filename` is None, no file will be written, and we communicate\n with dot using only pipes.\n format : {'png', 'pdf', 'dot', 'svg', 'jpeg', 'jpg'}, optional\n Format in which to write output file. Default is 'png'.\n optimize_graph : bool, optional\n If True, the graph is optimized before rendering. Otherwise,\n the graph is displayed as is. Default is False.\n color : {None, 'order', 'ages', 'freed', 'memoryincreases', 'memorydecreases', 'memorypressure'}, optional\n Options to color nodes. colormap:\n\n - None, the default, no colors.\n - 'order', colors the nodes' border based on the order they appear in the graph.\n - 'ages', how long the data of a node is held.\n - 'freed', the number of dependencies released after running a node.\n - 'memoryincreases', how many more outputs are held after the lifetime of a node.\n Large values may indicate nodes that should have run later.\n - 'memorydecreases', how many fewer outputs are held after the lifetime of a node.\n Large values may indicate nodes that should have run sooner.\n - 'memorypressure', the number of data held when the node is run (circle), or\n the data is released (rectangle).\n maxval : {int, float}, optional\n Maximum value for colormap to normalize form 0 to 1.0. Default is ``None``\n will make it the max number of values\n collapse_outputs : bool, optional\n Whether to collapse output boxes, which often have empty labels.\n Default is False.\n verbose : bool, optional\n Whether to label output and input boxes even if the data aren't chunked.\n Beware: these labels can get very long. Default is False.\n **kwargs\n Additional keyword arguments to forward to ``to_graphviz``.\n\n Examples\n --------\n >>> x.visualize(filename='dask.pdf') # doctest: +SKIP\n >>> x.visualize(filename='dask.pdf', color='order') # doctest: +SKIP\n\n Returns\n -------\n result : IPython.diplay.Image, IPython.display.SVG, or None\n See dask.dot.dot_graph for more information.\n\n See Also\n --------\n dask.dot.dot_graph\n\n Notes\n -----\n For more information on optimization see here:\n\n https://docs.dask.org/en/latest/optimize.html\n \"\"\"\n from dask.dot import dot_graph\n\n dsks = []\n args3 = []\n for arg in args:\n if isinstance(arg, (list, tuple, set)):\n for a in arg:\n if isinstance(a, Mapping):\n dsks.append(a)\n if is_dask_collection(a):\n args3.append(a)\n else:\n if isinstance(arg, Mapping):\n dsks.append(arg)\n if is_dask_collection(arg):\n args3.append(arg)\n\n dsk = dict(collections_to_dsk(args3, optimize_graph=optimize_graph))\n for d in dsks:\n dsk.update(d)\n\n color = kwargs.get(\"color\")\n\n if color in {\n \"order\",\n \"order-age\",\n \"order-freed\",\n \"order-memoryincreases\",\n \"order-memorydecreases\",\n \"order-memorypressure\",\n \"age\",\n \"freed\",\n \"memoryincreases\",\n \"memorydecreases\",\n \"memorypressure\",\n }:\n import matplotlib.pyplot as plt\n\n from .order import diagnostics, order\n\n o = order(dsk)\n try:\n cmap = kwargs.pop(\"cmap\")\n except KeyError:\n cmap = plt.cm.RdBu\n if isinstance(cmap, str):\n import matplotlib.pyplot as plt\n\n cmap = getattr(plt.cm, cmap)\n\n def label(x):\n return str(values[x])\n\n data_values = None\n if color != \"order\":\n info = diagnostics(dsk, o)[0]\n if color.endswith(\"age\"):\n values = {key: val.age for key, val in info.items()}\n elif color.endswith(\"freed\"):\n values = {key: val.num_dependencies_freed for key, val in info.items()}\n elif color.endswith(\"memorypressure\"):\n values = {key: val.num_data_when_run for key, val in info.items()}\n data_values = {\n key: val.num_data_when_released for key, val in info.items()\n }\n elif color.endswith(\"memoryincreases\"):\n values = {\n key: max(0, val.num_data_when_released - val.num_data_when_run)\n for key, val in info.items()\n }\n else: # memorydecreases\n values = {\n key: max(0, val.num_data_when_run - val.num_data_when_released)\n for key, val in info.items()\n }\n\n if color.startswith(\"order-\"):\n\n def label(x):\n return str(o[x]) + \"-\" + str(values[x])\n\n else:\n values = o\n if maxval is None:\n maxval = max(1, max(values.values()))\n colors = {k: _colorize(cmap(v / maxval, bytes=True)) for k, v in values.items()}\n if data_values is None:\n data_values = values\n data_colors = colors\n else:\n data_colors = {\n k: _colorize(cmap(v / maxval, bytes=True))\n for k, v in data_values.items()\n }\n\n kwargs[\"function_attributes\"] = {\n k: {\"color\": v, \"label\": label(k)} for k, v in colors.items()\n }\n kwargs[\"data_attributes\"] = {k: {\"color\": v} for k, v in data_colors.items()}\n elif color:\n raise NotImplementedError(\"Unknown value color=%s\" % color)\n\n return dot_graph(dsk, filename=filename, **kwargs)\n\n\ndef persist(*args, traverse=True, optimize_graph=True, scheduler=None, **kwargs):\n \"\"\"Persist multiple Dask collections into memory\n\n This turns lazy Dask collections into Dask collections with the same\n metadata, but now with their results fully computed or actively computing\n in the background.\n\n For example a lazy dask.array built up from many lazy calls will now be a\n dask.array of the same shape, dtype, chunks, etc., but now with all of\n those previously lazy tasks either computed in memory as many small :class:`numpy.array`\n (in the single-machine case) or asynchronously running in the\n background on a cluster (in the distributed case).\n\n This function operates differently if a ``dask.distributed.Client`` exists\n and is connected to a distributed scheduler. In this case this function\n will return as soon as the task graph has been submitted to the cluster,\n but before the computations have completed. Computations will continue\n asynchronously in the background. When using this function with the single\n machine scheduler it blocks until the computations have finished.\n\n When using Dask on a single machine you should ensure that the dataset fits\n entirely within memory.\n\n Examples\n --------\n >>> df = dd.read_csv('/path/to/*.csv') # doctest: +SKIP\n >>> df = df[df.name == 'Alice'] # doctest: +SKIP\n >>> df['in-debt'] = df.balance < 0 # doctest: +SKIP\n >>> df = df.persist() # triggers computation # doctest: +SKIP\n\n >>> df.value().min() # future computations are now fast # doctest: +SKIP\n -10\n >>> df.value().max() # doctest: +SKIP\n 100\n\n >>> from dask import persist # use persist function on multiple collections\n >>> a, b = persist(a, b) # doctest: +SKIP\n\n Parameters\n ----------\n *args: Dask collections\n scheduler : string, optional\n Which scheduler to use like \"threads\", \"synchronous\" or \"processes\".\n If not provided, the default is to check the global settings first,\n and then fall back to the collection defaults.\n traverse : bool, optional\n By default dask traverses builtin python collections looking for dask\n objects passed to ``persist``. For large collections this can be\n expensive. If none of the arguments contain any dask objects, set\n ``traverse=False`` to avoid doing this traversal.\n optimize_graph : bool, optional\n If True [default], the graph is optimized before computation.\n Otherwise the graph is run as is. This can be useful for debugging.\n **kwargs\n Extra keywords to forward to the scheduler function.\n\n Returns\n -------\n New dask collections backed by in-memory data\n \"\"\"\n collections, repack = unpack_collections(*args, traverse=traverse)\n if not collections:\n return args\n\n schedule = get_scheduler(scheduler=scheduler, collections=collections)\n\n if inspect.ismethod(schedule):\n try:\n from distributed.client import default_client\n except ImportError:\n pass\n else:\n try:\n client = default_client()\n except ValueError:\n pass\n else:\n if client.get == schedule:\n results = client.persist(\n collections, optimize_graph=optimize_graph, **kwargs\n )\n return repack(results)\n\n dsk = collections_to_dsk(collections, optimize_graph, **kwargs)\n keys, postpersists = [], []\n for a in collections:\n a_keys = list(flatten(a.__dask_keys__()))\n rebuild, state = a.__dask_postpersist__()\n keys.extend(a_keys)\n postpersists.append((rebuild, a_keys, state))\n\n results = schedule(dsk, keys, **kwargs)\n d = dict(zip(keys, results))\n results2 = [r({k: d[k] for k in ks}, *s) for r, ks, s in postpersists]\n return repack(results2)\n\n\n############\n# Tokenize #\n############\n\n\ndef tokenize(*args, **kwargs):\n \"\"\"Deterministic token\n\n >>> tokenize([1, 2, '3'])\n '7d6a880cd9ec03506eee6973ff551339'\n\n >>> tokenize('Hello') == tokenize('Hello')\n True\n \"\"\"\n if kwargs:\n args = args + (kwargs,)\n return md5(str(tuple(map(normalize_token, args))).encode()).hexdigest()\n\n\nnormalize_token = Dispatch()\nnormalize_token.register(\n (\n int,\n float,\n str,\n bytes,\n type(None),\n type,\n slice,\n complex,\n type(Ellipsis),\n datetime.date,\n ),\n identity,\n)\n\n\n@normalize_token.register(dict)\ndef normalize_dict(d):\n return normalize_token(sorted(d.items(), key=str))\n\n\n@normalize_token.register(OrderedDict)\ndef normalize_ordered_dict(d):\n return type(d).__name__, normalize_token(list(d.items()))\n\n\n@normalize_token.register(set)\ndef normalize_set(s):\n return normalize_token(sorted(s, key=str))\n\n\n@normalize_token.register((tuple, list))\ndef normalize_seq(seq):\n def func(seq):\n try:\n return list(map(normalize_token, seq))\n except RecursionError:\n if not config.get(\"tokenize.ensure-deterministic\"):\n return uuid.uuid4().hex\n\n raise RuntimeError(\n f\"Sequence {str(seq)} cannot be deterministically hashed. Please, see \"\n \"https://docs.dask.org/en/latest/custom-collections.html#implementing-deterministic-hashing \"\n \"for more information\"\n )\n\n return type(seq).__name__, func(seq)\n\n\n@normalize_token.register(literal)\ndef normalize_literal(lit):\n return \"literal\", normalize_token(lit())\n\n\n@normalize_token.register(range)\ndef normalize_range(r):\n return list(map(normalize_token, [r.start, r.stop, r.step]))\n\n\n@normalize_token.register(object)\ndef normalize_object(o):\n method = getattr(o, \"__dask_tokenize__\", None)\n if method is not None:\n return method()\n\n if callable(o):\n return normalize_function(o)\n\n if not config.get(\"tokenize.ensure-deterministic\"):\n return uuid.uuid4().hex\n\n raise RuntimeError(\n f\"Object {str(o)} cannot be deterministically hashed. Please, see \"\n \"https://docs.dask.org/en/latest/custom-collections.html#implementing-deterministic-hashing \"\n \"for more information\"\n )\n\n\nfunction_cache = {}\nfunction_cache_lock = threading.Lock()\n\n\ndef normalize_function(func):\n try:\n return function_cache[func]\n except KeyError:\n result = _normalize_function(func)\n if len(function_cache) >= 500: # clear half of cache if full\n with function_cache_lock:\n if len(function_cache) >= 500:\n for k in list(function_cache)[::2]:\n del function_cache[k]\n function_cache[func] = result\n return result\n except TypeError: # not hashable\n return _normalize_function(func)\n\n\ndef _normalize_function(func):\n if isinstance(func, Compose):\n first = getattr(func, \"first\", None)\n funcs = reversed((first,) + func.funcs) if first else func.funcs\n return tuple(normalize_function(f) for f in funcs)\n elif isinstance(func, (partial, curry)):\n args = tuple(normalize_token(i) for i in func.args)\n if func.keywords:\n kws = tuple(\n (k, normalize_token(v)) for k, v in sorted(func.keywords.items())\n )\n else:\n kws = None\n return (normalize_function(func.func), args, kws)\n else:\n try:\n result = pickle.dumps(func, protocol=0)\n if b\"__main__\" not in result: # abort on dynamic functions\n return result\n except Exception:\n pass\n try:\n import cloudpickle\n\n return cloudpickle.dumps(func, protocol=0)\n except Exception:\n return str(func)\n\n\n@normalize_token.register_lazy(\"pandas\")\ndef register_pandas():\n import pandas as pd\n\n PANDAS_GT_130 = parse_version(pd.__version__) >= parse_version(\"1.3.0\")\n\n @normalize_token.register(pd.Index)\n def normalize_index(ind):\n values = ind.array\n return [ind.name, normalize_token(values)]\n\n @normalize_token.register(pd.MultiIndex)\n def normalize_index(ind):\n codes = ind.codes\n return (\n [ind.name]\n + [normalize_token(x) for x in ind.levels]\n + [normalize_token(x) for x in codes]\n )\n\n @normalize_token.register(pd.Categorical)\n def normalize_categorical(cat):\n return [normalize_token(cat.codes), normalize_token(cat.dtype)]\n\n @normalize_token.register(pd.arrays.PeriodArray)\n @normalize_token.register(pd.arrays.DatetimeArray)\n @normalize_token.register(pd.arrays.TimedeltaArray)\n def normalize_period_array(arr):\n return [normalize_token(arr.asi8), normalize_token(arr.dtype)]\n\n @normalize_token.register(pd.arrays.IntervalArray)\n def normalize_interval_array(arr):\n return [\n normalize_token(arr.left),\n normalize_token(arr.right),\n normalize_token(arr.closed),\n ]\n\n @normalize_token.register(pd.Series)\n def normalize_series(s):\n return [\n s.name,\n s.dtype,\n normalize_token(s._values),\n normalize_token(s.index),\n ]\n\n @normalize_token.register(pd.DataFrame)\n def normalize_dataframe(df):\n mgr = df._data\n\n if PANDAS_GT_130:\n # for compat with ArrayManager, pandas 1.3.0 introduced a `.arrays`\n # attribute that returns the column arrays/block arrays for both\n # BlockManager and ArrayManager\n data = list(mgr.arrays)\n else:\n data = [block.values for block in mgr.blocks]\n data.extend([df.columns, df.index])\n return list(map(normalize_token, data))\n\n @normalize_token.register(pd.api.extensions.ExtensionArray)\n def normalize_extension_array(arr):\n import numpy as np\n\n return normalize_token(np.asarray(arr))\n\n # Dtypes\n @normalize_token.register(pd.api.types.CategoricalDtype)\n def normalize_categorical_dtype(dtype):\n return [normalize_token(dtype.categories), normalize_token(dtype.ordered)]\n\n @normalize_token.register(pd.api.extensions.ExtensionDtype)\n def normalize_period_dtype(dtype):\n return normalize_token(dtype.name)\n\n\n@normalize_token.register_lazy(\"numpy\")\ndef register_numpy():\n import numpy as np\n\n @normalize_token.register(np.ndarray)\n def normalize_array(x):\n if not x.shape:\n return (x.item(), x.dtype)\n if hasattr(x, \"mode\") and getattr(x, \"filename\", None):\n if hasattr(x.base, \"ctypes\"):\n offset = (\n x.ctypes._as_parameter_.value - x.base.ctypes._as_parameter_.value\n )\n else:\n offset = 0 # root memmap's have mmap object as base\n if hasattr(\n x, \"offset\"\n ): # offset numpy used while opening, and not the offset to the beginning of the file\n offset += getattr(x, \"offset\")\n return (\n x.filename,\n os.path.getmtime(x.filename),\n x.dtype,\n x.shape,\n x.strides,\n offset,\n )\n if x.dtype.hasobject:\n try:\n try:\n # string fast-path\n data = hash_buffer_hex(\n \"-\".join(x.flat).encode(\n encoding=\"utf-8\", errors=\"surrogatepass\"\n )\n )\n except UnicodeDecodeError:\n # bytes fast-path\n data = hash_buffer_hex(b\"-\".join(x.flat))\n except (TypeError, UnicodeDecodeError):\n try:\n data = hash_buffer_hex(pickle.dumps(x, pickle.HIGHEST_PROTOCOL))\n except Exception:\n # pickling not supported, use UUID4-based fallback\n if not config.get(\"tokenize.ensure-deterministic\"):\n data = uuid.uuid4().hex\n else:\n raise RuntimeError(\n f\"``np.ndarray`` with object ``dtype`` {str(x)} cannot \"\n \"be deterministically hashed. Please, see \"\n \"https://docs.dask.org/en/latest/custom-collections.html#implementing-deterministic-hashing \" # noqa: E501\n \"for more information\"\n )\n else:\n try:\n data = hash_buffer_hex(x.ravel(order=\"K\").view(\"i1\"))\n except (BufferError, AttributeError, ValueError):\n data = hash_buffer_hex(x.copy().ravel(order=\"K\").view(\"i1\"))\n return (data, x.dtype, x.shape, x.strides)\n\n @normalize_token.register(np.matrix)\n def normalize_matrix(x):\n return type(x).__name__, normalize_array(x.view(type=np.ndarray))\n\n normalize_token.register(np.dtype, repr)\n normalize_token.register(np.generic, repr)\n\n @normalize_token.register(np.ufunc)\n def normalize_ufunc(x):\n try:\n name = x.__name__\n if getattr(np, name) is x:\n return \"np.\" + name\n except AttributeError:\n return normalize_function(x)\n\n\n@normalize_token.register_lazy(\"scipy\")\ndef register_scipy():\n import scipy.sparse as sp\n\n def normalize_sparse_matrix(x, attrs):\n return (\n type(x).__name__,\n normalize_seq(normalize_token(getattr(x, key)) for key in attrs),\n )\n\n for cls, attrs in [\n (sp.dia_matrix, (\"data\", \"offsets\", \"shape\")),\n (sp.bsr_matrix, (\"data\", \"indices\", \"indptr\", \"blocksize\", \"shape\")),\n (sp.coo_matrix, (\"data\", \"row\", \"col\", \"shape\")),\n (sp.csr_matrix, (\"data\", \"indices\", \"indptr\", \"shape\")),\n (sp.csc_matrix, (\"data\", \"indices\", \"indptr\", \"shape\")),\n (sp.lil_matrix, (\"data\", \"rows\", \"shape\")),\n ]:\n normalize_token.register(cls, partial(normalize_sparse_matrix, attrs=attrs))\n\n @normalize_token.register(sp.dok_matrix)\n def normalize_dok_matrix(x):\n return type(x).__name__, normalize_token(sorted(x.items()))\n\n\ndef _colorize(t):\n \"\"\"Convert (r, g, b) triple to \"#RRGGBB\" string\n\n For use with ``visualize(color=...)``\n\n Examples\n --------\n >>> _colorize((255, 255, 255))\n '#FFFFFF'\n >>> _colorize((0, 32, 128))\n '#002080'\n \"\"\"\n t = t[:3]\n i = sum(v * 256 ** (len(t) - i - 1) for i, v in enumerate(t))\n h = hex(int(i))[2:].upper()\n h = \"0\" * (6 - len(h)) + h\n return \"#\" + h\n\n\nnamed_schedulers = {\n \"sync\": local.get_sync,\n \"synchronous\": local.get_sync,\n \"single-threaded\": local.get_sync,\n \"threads\": threaded.get,\n \"threading\": threaded.get,\n}\n\ntry:\n from dask import multiprocessing as dask_multiprocessing\nexcept ImportError:\n pass\nelse:\n named_schedulers.update(\n {\n \"processes\": dask_multiprocessing.get,\n \"multiprocessing\": dask_multiprocessing.get,\n }\n )\n\n\nget_err_msg = \"\"\"\nThe get= keyword has been removed.\n\nPlease use the scheduler= keyword instead with the name of\nthe desired scheduler like 'threads' or 'processes'\n\n x.compute(scheduler='single-threaded')\n x.compute(scheduler='threads')\n x.compute(scheduler='processes')\n\nor with a function that takes the graph and keys\n\n x.compute(scheduler=my_scheduler_function)\n\nor with a Dask client\n\n x.compute(scheduler=client)\n\"\"\".strip()\n\n\ndef get_scheduler(get=None, scheduler=None, collections=None, cls=None):\n \"\"\"Get scheduler function\n\n There are various ways to specify the scheduler to use:\n\n 1. Passing in scheduler= parameters\n 2. Passing these into global configuration\n 3. Using defaults of a dask collection\n\n This function centralizes the logic to determine the right scheduler to use\n from those many options\n \"\"\"\n if get:\n raise TypeError(get_err_msg)\n\n if scheduler is not None:\n if callable(scheduler):\n return scheduler\n elif \"Client\" in type(scheduler).__name__ and hasattr(scheduler, \"get\"):\n return scheduler.get\n elif isinstance(scheduler, str):\n scheduler = scheduler.lower()\n if scheduler in named_schedulers:\n return named_schedulers[scheduler]\n elif scheduler in (\"dask.distributed\", \"distributed\"):\n from distributed.worker import get_client\n\n return get_client().get\n else:\n raise ValueError(\n \"Expected one of [distributed, %s]\"\n % \", \".join(sorted(named_schedulers))\n )\n elif isinstance(scheduler, Executor):\n # Get `num_workers` from `Executor`'s `_max_workers` attribute.\n # If undefined, fallback to `config` or worst case CPU_COUNT.\n num_workers = getattr(scheduler, \"_max_workers\", None)\n if num_workers is None:\n num_workers = config.get(\"num_workers\", CPU_COUNT)\n assert isinstance(num_workers, Integral) and num_workers > 0\n return partial(local.get_async, scheduler.submit, num_workers)\n else:\n raise ValueError(\"Unexpected scheduler: %s\" % repr(scheduler))\n # else: # try to connect to remote scheduler with this name\n # return get_client(scheduler).get\n\n if config.get(\"scheduler\", None):\n return get_scheduler(scheduler=config.get(\"scheduler\", None))\n\n if config.get(\"get\", None):\n raise ValueError(get_err_msg)\n\n if getattr(thread_state, \"key\", False):\n from distributed.worker import get_worker\n\n return get_worker().client.get\n\n if cls is not None:\n return cls.__dask_scheduler__\n\n if collections:\n collections = [c for c in collections if c is not None]\n if collections:\n get = collections[0].__dask_scheduler__\n if not all(c.__dask_scheduler__ == get for c in collections):\n raise ValueError(\n \"Compute called on multiple collections with \"\n \"differing default schedulers. Please specify a \"\n \"scheduler=` parameter explicitly in compute or \"\n \"globally with `dask.config.set`.\"\n )\n return get\n\n return None\n\n\ndef wait(x, timeout=None, return_when=\"ALL_COMPLETED\"):\n \"\"\"Wait until computation has finished\n\n This is a compatibility alias for ``dask.distributed.wait``.\n If it is applied onto Dask collections without Dask Futures or if Dask\n distributed is not installed then it is a no-op\n \"\"\"\n try:\n from distributed import wait\n\n return wait(x, timeout=timeout, return_when=return_when)\n except (ImportError, ValueError):\n return x\n\n\ndef get_collection_names(collection) -> Set[str]:\n \"\"\"Infer the collection names from the dask keys, under the assumption that all keys\n are either tuples with matching first element, and that element is a string, or\n there is exactly one key and it is a string.\n\n Examples\n --------\n >>> a.__dask_keys__() # doctest: +SKIP\n [\"foo\", \"bar\"]\n >>> get_collection_names(a) # doctest: +SKIP\n {\"foo\", \"bar\"}\n >>> b.__dask_keys__() # doctest: +SKIP\n [[(\"foo-123\", 0, 0), (\"foo-123\", 0, 1)], [(\"foo-123\", 1, 0), (\"foo-123\", 1, 1)]]\n >>> get_collection_names(b) # doctest: +SKIP\n {\"foo-123\"}\n \"\"\"\n if not is_dask_collection(collection):\n raise TypeError(f\"Expected Dask collection; got {type(collection)}\")\n return {get_name_from_key(k) for k in flatten(collection.__dask_keys__())}\n\n\ndef get_name_from_key(key) -> str:\n \"\"\"Given a dask collection's key, extract the collection name.\n\n Parameters\n ----------\n key: string or tuple\n Dask collection's key, which must be either a single string or a tuple whose\n first element is a string (commonly referred to as a collection's 'name'),\n\n Examples\n --------\n >>> get_name_from_key(\"foo\")\n 'foo'\n >>> get_name_from_key((\"foo-123\", 1, 2))\n 'foo-123'\n \"\"\"\n if isinstance(key, tuple) and key and isinstance(key[0], str):\n return key[0]\n if isinstance(key, str):\n return key\n raise TypeError(f\"Expected str or tuple[str, Hashable, ...]; got {key}\")\n\n\ndef replace_name_in_key(key, rename: Mapping[str, str]):\n \"\"\"Given a dask collection's key, replace the collection name with a new one.\n\n Parameters\n ----------\n key: string or tuple\n Dask collection's key, which must be either a single string or a tuple whose\n first element is a string (commonly referred to as a collection's 'name'),\n rename:\n Mapping of zero or more names from : to. Extraneous names will be ignored.\n Names not found in this mapping won't be replaced.\n\n Examples\n --------\n >>> replace_name_in_key(\"foo\", {})\n 'foo'\n >>> replace_name_in_key(\"foo\", {\"foo\": \"bar\"})\n 'bar'\n >>> replace_name_in_key((\"foo-123\", 1, 2), {\"foo-123\": \"bar-456\"})\n ('bar-456', 1, 2)\n \"\"\"\n if isinstance(key, tuple) and key and isinstance(key[0], str):\n return (rename.get(key[0], key[0]),) + key[1:]\n if isinstance(key, str):\n return rename.get(key, key)\n raise TypeError(f\"Expected str or tuple[str, Hashable, ...]; got {key}\")\n\n\ndef clone_key(key, seed):\n \"\"\"Clone a key from a Dask collection, producing a new key with the same prefix and\n indices and a token which a deterministic function of the previous token and seed.\n\n Examples\n --------\n >>> clone_key(\"inc-cbb1eca3bafafbb3e8b2419c4eebb387\", 123) # doctest: +SKIP\n 'inc-1d291de52f5045f8a969743daea271fd'\n >>> clone_key((\"sum-cbb1eca3bafafbb3e8b2419c4eebb387\", 4, 3), 123) # doctest: +SKIP\n ('sum-f0962cc58ef4415689a86cc1d4cc1723', 4, 3)\n \"\"\"\n if isinstance(key, tuple) and key and isinstance(key[0], str):\n return (clone_key(key[0], seed),) + key[1:]\n if isinstance(key, str):\n prefix = key_split(key)\n token = key[len(prefix) + 1 :]\n if token:\n return prefix + \"-\" + tokenize(token, seed)\n else:\n return tokenize(key, seed)\n raise TypeError(f\"Expected str or tuple[str, Hashable, ...]; got {key}\")\n" ]
[ [ "numpy.asarray" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]